+
+# Although we may know the offset of certain text fields in TeX DVI
+# and font files, we can't use them reliably because they are not
+# zero terminated. [but we do anyway, christos]
+0 string \367\002 application/x-dvi
+#0 string \367\203 TeX generic font data
+#0 string \367\131 TeX packed font data
+#0 string \367\312 TeX virtual font data
+#0 string This\ is\ TeX, TeX transcript text
+#0 string This\ is\ METAFONT, METAFONT transcript text
+
+# There is no way to detect TeX Font Metric (*.tfm) files without
+# breaking them apart and reading the data. The following patterns
+# match most *.tfm files generated by METAFONT or afm2tfm.
+#2 string \000\021 TeX font metric data
+#2 string \000\022 TeX font metric data
+#>34 string >\0 (%s)
+
+# Texinfo and GNU Info, from Daniel Quinlan (quinlan@yggdrasil.com)
+#0 string \\input\ texinfo Texinfo source text
+#0 string This\ is\ Info\ file GNU Info text
+
+# correct TeX magic for Linux (and maybe more)
+# from Peter Tobias (tobias@server.et-inf.fho-emden.de)
+#
+0 leshort 0x02f7 application/x-dvi
+
+# RTF - Rich Text Format
+0 string {\\rtf application/rtf
+
+#------------------------------------------------------------------------------
+# animation: file(1) magic for animation/movie formats
+#
+# animation formats, originally from vax@ccwf.cc.utexas.edu (VaX#n8)
+# MPEG file
+0 string \000\000\001\263 video/mpeg
+#
+# The contributor claims:
+# I couldn't find a real magic number for these, however, this
+# -appears- to work. Note that it might catch other files, too,
+# so BE CAREFUL!
+#
+# Note that title and author appear in the two 20-byte chunks
+# at decimal offsets 2 and 22, respectively, but they are XOR'ed with
+# 255 (hex FF)! DL format SUCKS BIG ROCKS.
+#
+# DL file version 1 , medium format (160x100, 4 images/screen)
+0 byte 1 video/unknown
+0 byte 2 video/unknown
+
diff --git a/docs/conf/mime.types b/docs/conf/mime.types
new file mode 100644
index 00000000000..d53db0f4e88
--- /dev/null
+++ b/docs/conf/mime.types
@@ -0,0 +1,276 @@
+# This is a comment. I love comments.
+
+# This file controls what Internet media types are sent to the client for
+# given file extension(s). Sending the correct media type to the client
+# is important so they know how to handle the content of the file.
+# Extra types can either be added here or by using an AddType directive
+# in your config files. For more information about Internet media types,
+# please read RFC 2045, 2046, 2047, 2048, and 2077. The Internet media type
+# registry is at .
+
+# MIME type Extension
+application/EDI-Consent
+application/EDI-X12
+application/EDIFACT
+application/activemessage
+application/andrew-inset ez
+application/applefile
+application/atomicmail
+application/cals-1840
+application/commonground
+application/cybercash
+application/dca-rft
+application/dec-dx
+application/eshop
+application/hyperstudio
+application/iges
+application/mac-binhex40 hqx
+application/mac-compactpro cpt
+application/macwriteii
+application/marc
+application/mathematica
+application/msword doc
+application/news-message-id
+application/news-transmission
+application/octet-stream bin dms lha lzh exe class
+application/oda oda
+application/pdf pdf
+application/pgp-encrypted
+application/pgp-keys
+application/pgp-signature
+application/pkcs10
+application/pkcs7-mime
+application/pkcs7-signature
+application/postscript ai eps ps
+application/prs.alvestrand.titrax-sheet
+application/prs.cww
+application/prs.nprend
+application/remote-printing
+application/riscos
+application/rtf rtf
+application/set-payment
+application/set-payment-initiation
+application/set-registration
+application/set-registration-initiation
+application/sgml
+application/sgml-open-catalog
+application/slate
+application/smil smi smil
+application/vemmi
+application/vnd.3M.Post-it-Notes
+application/vnd.FloGraphIt
+application/vnd.acucobol
+application/vnd.anser-web-certificate-issue-initiation
+application/vnd.anser-web-funds-transfer-initiation
+application/vnd.audiograph
+application/vnd.businessobjects
+application/vnd.claymore
+application/vnd.comsocaller
+application/vnd.dna
+application/vnd.dxr
+application/vnd.ecdis-update
+application/vnd.ecowin.chart
+application/vnd.ecowin.filerequest
+application/vnd.ecowin.fileupdate
+application/vnd.ecowin.series
+application/vnd.ecowin.seriesrequest
+application/vnd.ecowin.seriesupdate
+application/vnd.enliven
+application/vnd.epson.salt
+application/vnd.fdf
+application/vnd.ffsns
+application/vnd.framemaker
+application/vnd.fujitsu.oasys
+application/vnd.fujitsu.oasys2
+application/vnd.fujitsu.oasys3
+application/vnd.fujitsu.oasysgp
+application/vnd.fujitsu.oasysprs
+application/vnd.fujixerox.docuworks
+application/vnd.hp-HPGL
+application/vnd.hp-PCL
+application/vnd.hp-PCLXL
+application/vnd.hp-hps
+application/vnd.ibm.MiniPay
+application/vnd.ibm.modcap
+application/vnd.intercon.formnet
+application/vnd.intertrust.digibox
+application/vnd.intertrust.nncp
+application/vnd.is-xpr
+application/vnd.japannet-directory-service
+application/vnd.japannet-jpnstore-wakeup
+application/vnd.japannet-payment-wakeup
+application/vnd.japannet-registration
+application/vnd.japannet-registration-wakeup
+application/vnd.japannet-setstore-wakeup
+application/vnd.japannet-verification
+application/vnd.japannet-verification-wakeup
+application/vnd.koan
+application/vnd.lotus-1-2-3
+application/vnd.lotus-approach
+application/vnd.lotus-freelance
+application/vnd.lotus-organizer
+application/vnd.lotus-screencam
+application/vnd.lotus-wordpro
+application/vnd.meridian-slingshot
+application/vnd.mif mif
+application/vnd.minisoft-hp3000-save
+application/vnd.mitsubishi.misty-guard.trustweb
+application/vnd.ms-artgalry
+application/vnd.ms-asf
+application/vnd.ms-excel xls
+application/vnd.ms-powerpoint ppt
+application/vnd.ms-project
+application/vnd.ms-tnef
+application/vnd.ms-works
+application/vnd.music-niff
+application/vnd.musician
+application/vnd.netfpx
+application/vnd.noblenet-directory
+application/vnd.noblenet-sealer
+application/vnd.noblenet-web
+application/vnd.novadigm.EDM
+application/vnd.novadigm.EDX
+application/vnd.novadigm.EXT
+application/vnd.osa.netdeploy
+application/vnd.powerbuilder6
+application/vnd.powerbuilder6-s
+application/vnd.rapid
+application/vnd.seemail
+application/vnd.shana.informed.formtemplate
+application/vnd.shana.informed.interchange
+application/vnd.shana.informed.package
+application/vnd.street-stream
+application/vnd.svd
+application/vnd.swiftview-ics
+application/vnd.truedoc
+application/vnd.visio
+application/vnd.webturbo
+application/vnd.wrq-hp3000-labelled
+application/vnd.wt.stf
+application/vnd.xara
+application/vnd.yellowriver-custom-menu
+application/wita
+application/wordperfect5.1
+application/x-bcpio bcpio
+application/x-cdlink vcd
+application/x-chess-pgn pgn
+application/x-compress
+application/x-cpio cpio
+application/x-csh csh
+application/x-director dcr dir dxr
+application/x-dvi dvi
+application/x-futuresplash spl
+application/x-gtar gtar
+application/x-gzip
+application/x-hdf hdf
+application/x-javascript js
+application/x-koan skp skd skt skm
+application/x-latex latex
+application/x-netcdf nc cdf
+application/x-sh sh
+application/x-shar shar
+application/x-shockwave-flash swf
+application/x-stuffit sit
+application/x-sv4cpio sv4cpio
+application/x-sv4crc sv4crc
+application/x-tar tar
+application/x-tcl tcl
+application/x-tex tex
+application/x-texinfo texinfo texi
+application/x-troff t tr roff
+application/x-troff-man man
+application/x-troff-me me
+application/x-troff-ms ms
+application/x-ustar ustar
+application/x-wais-source src
+application/x400-bp
+application/xml
+application/zip zip
+audio/32kadpcm
+audio/basic au snd
+audio/midi mid midi kar
+audio/mpeg mpga mp2 mp3
+audio/vnd.qcelp
+audio/x-aiff aif aiff aifc
+audio/x-pn-realaudio ram rm
+audio/x-pn-realaudio-plugin rpm
+audio/x-realaudio ra
+audio/x-wav wav
+chemical/x-pdb pdb xyz
+image/bmp bmp
+image/cgm
+image/g3fax
+image/gif gif
+image/ief ief
+image/jpeg jpeg jpg jpe
+image/naplps
+image/png png
+image/prs.btif
+image/tiff tiff tif
+image/vnd.dwg
+image/vnd.dxf
+image/vnd.fpx
+image/vnd.net-fpx
+image/vnd.svf
+image/vnd.xiff
+image/x-cmu-raster ras
+image/x-portable-anymap pnm
+image/x-portable-bitmap pbm
+image/x-portable-graymap pgm
+image/x-portable-pixmap ppm
+image/x-rgb rgb
+image/x-xbitmap xbm
+image/x-xpixmap xpm
+image/x-xwindowdump xwd
+message/delivery-status
+message/disposition-notification
+message/external-body
+message/http
+message/news
+message/partial
+message/rfc822
+model/iges igs iges
+model/mesh msh mesh silo
+model/vnd.dwf
+model/vrml wrl vrml
+multipart/alternative
+multipart/appledouble
+multipart/byteranges
+multipart/digest
+multipart/encrypted
+multipart/form-data
+multipart/header-set
+multipart/mixed
+multipart/parallel
+multipart/related
+multipart/report
+multipart/signed
+multipart/voice-message
+text/css css
+text/directory
+text/enriched
+text/html html htm
+text/plain asc txt
+text/prs.lines.tag
+text/rfc822-headers
+text/richtext rtx
+text/rtf rtf
+text/sgml sgml sgm
+text/tab-separated-values tsv
+text/uri-list
+text/vnd.abc
+text/vnd.flatland.3dml
+text/vnd.fmi.flexstor
+text/vnd.in3d.3dml
+text/vnd.in3d.spot
+text/vnd.latex-z
+text/x-setext etx
+text/xml xml
+video/mpeg mpeg mpg mpe
+video/quicktime qt mov
+video/vnd.motorola.video
+video/vnd.motorola.videop
+video/vnd.vivo
+video/x-msvideo avi
+video/x-sgi-movie movie
+x-conference/x-cooltalk ice
diff --git a/docs/docroot/index.html.ca b/docs/docroot/index.html.ca
new file mode 100644
index 00000000000..a71a6853569
--- /dev/null
+++ b/docs/docroot/index.html.ca
@@ -0,0 +1,51 @@
+
+
+
+ Pàgina de prova de l'instal·lació d'Apache
+
+
+
+
+ Funciona ! El servidor web Apache està instal·lat
+ en aquest lloc !
+
+
+ Si veu aquesta pàgina, es que els propietaris d'aquest domini
+ acaben d'instal·lar satisfactòriament el
+ servidor web Apache.
+ Ara han d'afegir contingut en aquest directori i substituir aquesta pàgina,
+ o bè dirigir aquest servidor cap al contingut real.
+
+
+
+ Si està veien aquesta pàgina i no es la que esperava, posis en
+ contacte amb
+ l'administrador web d'aquest lloc.
+ (Provi d'enviar un correu electrònic a <Webmaster@domain>.)
+ Encara que aquest lloc està utilitzant el programari Apache, es gairebé segur
+ que no tè res a veure amb el Grup Apache, per tant
+ no enviï cap correu electrònic als autors d'Apache referent a aquest lloc o al seu contingut.
+ Si es que ho fa, el seu missatge serà ignorat.
+
+
+
+ La
+ documentació
+ d'Apache ha estat inclosa en aquesta distribució.
+
+
+ L'administrador de web pot utilitzar lliurement la imatge d'aquí sota
+ en el servidor web equipat amb el programari Apache.
+ Gràcies per utilitzar Apache !
+
+
+

+
+
+
diff --git a/docs/docroot/index.html.de b/docs/docroot/index.html.de
new file mode 100644
index 00000000000..a5420e933a0
--- /dev/null
+++ b/docs/docroot/index.html.de
@@ -0,0 +1,61 @@
+
+
+
+ Testseite fuer die Apache-Installation auf dieser Web Site
+
+
+
+
+
+ Es klappt! Der Apache Web-Server ist auf dieser Web-Site installiert!
+
+
+ Wenn Sie diese Seite sehen, dann bedeutet das, dass die
+ Eigentümer dieser Domäne soeben einen neuen
+ Apache Web-Server
+ erfolgreich installiert haben. Jetzt muss noch der
+ richtige Web-Inhalt zugefügt und diese Platzhalter-Seite
+ ersetzt werden (oder der Web-Server für den Zugriff auf den
+ richtigen Inhalt umkonfiguriert werden).
+
+
+
+ Wenn Sie diese Seite an Stelle einer anderen erwarteten Web-Site
+ sehen sollten, dann nehmen Sie bitte Kontakt mit dem
+ Eigentümer dieser Site auf (Versuchen Sie, eine EMail
+ an <Webmaster@domänenname>
+ zu senden)!
+
+ Obwohl der Eigentümer dieser Domäne die Apache
+ Web-Server Software verwendet, hat diese Web-Site ziemlich sicher
+ keinerlei Verbindung mit der Apache Software Foundation
+ (die diese Software kostenlos vertreibt). Es besteht also
+ keinerlei Veranlassung, eine EMail an
+ die Entwickler der Software zu senden. Sollten Sie das dennoch
+ tun, wird Ihre Mail stillschweigend
+ ignoriert.
+
+
+
+ Die englische Online-Dokumentation für die
+ Apache Web-Server Software ist Bestandteil dieser
+ Software-Distribution.
+
+
+ Dem WebMaster dieser Web-Site steht es frei, das
+ untenstehende "Powered by Apache"-Logo auf einem Apache-basierten
+ Web-Server zu verwenden.
+ Vielen Dank, dass Sie Apache gewählt haben!
+
+
+

+
+
+
diff --git a/docs/docroot/index.html.dk b/docs/docroot/index.html.dk
new file mode 100644
index 00000000000..22b3931aac5
--- /dev/null
+++ b/docs/docroot/index.html.dk
@@ -0,0 +1,47 @@
+
+
+
+ Prøveside for Apache installationen
+
+
+
+
+ Det virkede! Apache Webserveren er installeret på denne maskine!
+
+
+ Hvis du kan se denne side, så har dem som ejer dette domæne lige
+ installeret Apache Webserveren.
+ Du må nu placere web sider i dette directory og fjerne denne side, eller
+ konfigurere serveren til at anvende et andet directory.
+
+
+
+ Hvis du ser denne side istedet for en anden forventet side, kontakt
+ venligst administratoren for den server du prøver at kontakte.
+ (Prøv at sende mail til <Webmaster@domain>.)
+ Apachegruppen har ikke noget at gøre med denne site, så det vil ikke
+ hjælpe at sende mail to Apache udviklerne angående denne site.
+
+
+
+ Apache-
+ documentationen
+ er inkluderet med denne distribution.
+
+
+ Webmasteren af denne site må gerne bruge den følgende grafik
+ på en Apache-drevet webserver. Mange tak for at bruge Apache!
+
+
+

+
+
+
diff --git a/docs/docroot/index.html.ee b/docs/docroot/index.html.ee
new file mode 100644
index 00000000000..879c30e3815
--- /dev/null
+++ b/docs/docroot/index.html.ee
@@ -0,0 +1,53 @@
+
+
+
+ Apache veebiserveri installatsiooni testlehekülg
+
+
+
+
+
+ Kujuta pilti, käima läks! Apache veebiserver on installeeritud!
+
+
+ Kui Sa näed seda lehekülge, siis selle domeeni omanikud on
+ edukalt hakkama saanud Apache veebiserveri
+ installeerimisega. Järgmiseks peaks nad selle lehekülje asendama
+ misiganes materjaliga, mida nad oma veebisaidis näidata tahavad,
+ või siis juhatama veebiserverile kätte tegeliku materjali
+ asukoha.
+
+
+
+ Kui Sa ootasid siin leheküljel näha hoopis midagi muud,
+ siis palun võta ühendust selle veebisaidi
+ administraatoriga. (Võid näiteks kirjutada aadressil
+ <Webmaster@domain>.) Kuigi see veebisait
+ kasutab Apache tarkvara, pole ta peaaegu kindlasti mitte Apache Group'iga
+ mingil muul moel seotud. Seega, palun ära kirjuta selle saidi
+ asjus Apache autoritele. Kui sa seda teed, siis sinu kirja
+ ignoreeritakse.
+
+
+
+ Ka Apache
+ dokumentatsioon
+ on selles distributsioonis olemas.
+
+
+ Kohalik veebmeister võib vabalt kasutada allpool olevat
+ pilti oma Apache veebiserveril. Aitäh Apachet kasutamast!
+
+
+

+
+
+
diff --git a/docs/docroot/index.html.en b/docs/docroot/index.html.en
new file mode 100644
index 00000000000..73f5eca36c7
--- /dev/null
+++ b/docs/docroot/index.html.en
@@ -0,0 +1,38 @@
+
+
+
+ Test Page for Apache Installation
+
+
+
+
+
+
+If you can see this, it means that the installation of the Apache web server software on this system was successful. You may now add content to this directory and replace this page.
+
+
+
+Seeing this instead of the website you expected?
+
+
+This page is here because the site administrator has changed the configuration of this web server.
+Please contact the person responsible for maintaining this server with questions. The Apache Software Foundation, which wrote the web server software this site administrator is using, has nothing to do with maintaining this site and cannot help resolve configuration issues.
+
+
+
+
+
+The Apache documentation has been included with this distribution.
+
+
+You are free to use the image below on an Apache-powered web server. Thanks for using Apache!
+
+
+
+
diff --git a/docs/docroot/index.html.es b/docs/docroot/index.html.es
new file mode 100644
index 00000000000..b5f81070b74
--- /dev/null
+++ b/docs/docroot/index.html.es
@@ -0,0 +1,51 @@
+
+
+
+ Pagína para probar la instalación de Apache
+
+
+
+
+ ¡Funcionó! ¡El Servidor de Red Apache ha sido instalado en ese sitio!
+
+
+ Si usted puede ver esta pagína, entonces los dueños de esta
+ maquína han instalado el Servidor de
+ Red Apache con exíto. Ahora deben añadir contenido a este directorio
+ y reemplazar esta pagína, ó apuntar este servidor al contenido real.
+
+
+
+ Si usted esta leyendo esta pagína y no es lo que esperaba, por favor
+ contacte el administrador de este sitio.
+ (Trate de enviar correo electrónico a <Webmaster@domain>.)
+ Aunque este sitio esta utilizando el programa Apache es casi seguro
+ que no tiene ninguna conexión con el Apache Group, por eso favor de
+ no enviar correo sobre este sitio o su contenido a los autores de
+ Apache. Si lo hace, su mensaje sera
+ ignorado.
+
+
+
+ La
+ documentación
+ de Apache ha sido incluida en esta distribución.
+
+
+ El administrador del sitio esta invitado a usar la siguiente
+ imagen para indicar que su sitio es servido por Apache.
+ ¡Gracias por usar Apache!
+
+
+

+
+
+
diff --git a/docs/docroot/index.html.et b/docs/docroot/index.html.et
new file mode 100644
index 00000000000..879c30e3815
--- /dev/null
+++ b/docs/docroot/index.html.et
@@ -0,0 +1,53 @@
+
+
+
+ Apache veebiserveri installatsiooni testlehekülg
+
+
+
+
+
+ Kujuta pilti, käima läks! Apache veebiserver on installeeritud!
+
+
+ Kui Sa näed seda lehekülge, siis selle domeeni omanikud on
+ edukalt hakkama saanud Apache veebiserveri
+ installeerimisega. Järgmiseks peaks nad selle lehekülje asendama
+ misiganes materjaliga, mida nad oma veebisaidis näidata tahavad,
+ või siis juhatama veebiserverile kätte tegeliku materjali
+ asukoha.
+
+
+
+ Kui Sa ootasid siin leheküljel näha hoopis midagi muud,
+ siis palun võta ühendust selle veebisaidi
+ administraatoriga. (Võid näiteks kirjutada aadressil
+ <Webmaster@domain>.) Kuigi see veebisait
+ kasutab Apache tarkvara, pole ta peaaegu kindlasti mitte Apache Group'iga
+ mingil muul moel seotud. Seega, palun ära kirjuta selle saidi
+ asjus Apache autoritele. Kui sa seda teed, siis sinu kirja
+ ignoreeritakse.
+
+
+
+ Ka Apache
+ dokumentatsioon
+ on selles distributsioonis olemas.
+
+
+ Kohalik veebmeister võib vabalt kasutada allpool olevat
+ pilti oma Apache veebiserveril. Aitäh Apachet kasutamast!
+
+
+

+
+
+
diff --git a/docs/docroot/index.html.fr b/docs/docroot/index.html.fr
new file mode 100644
index 00000000000..7ffa0979d61
--- /dev/null
+++ b/docs/docroot/index.html.fr
@@ -0,0 +1,53 @@
+
+
+
+ Page de test de l'installation d'Apache
+
+
+
+
+ Ça fonctionne ! Le serveur web Apache est installé sur
+ ce site !
+
+
+ Si vous lisez cette page, c'est que les propriétaires de ce domaine
+ viennent d'installer le
+ serveur web Apache
+ avec succès. Ils doivent maintenant ajouter du contenu à ce
+ répertoire et remplacer cette page, ou bien faire pointer le serveur
+ vers l'endroit où se trouve le contenu réel du site.
+
+
+
+ Si vous voyez cette page au lieu du site attendu, veuillez contacter
+ l'administrateur du site concerné.
+ (Essayez d'envoyer un email à
+ <Webmaster@domaine>.)
+ Bien que ce site utilise le logiciel Apache, il n'a certainement
+ rien à voir avec le Groupe Apache, par conséquent
+ veuillez ne pas envoyer d'email aux
+ auteurs d'Apache concernant ce site ou son contenu. Si vous le faites,
+ votre message sera ignoré.
+
+
+
+ La
+ documentation
+ Apache est incluse dans cette distribution.
+
+
+ Le webmaster de ce site peut librement utiliser l'image ci-dessous
+ sur un site web utilisant le logiciel Apache. Merci d'avoir choisi
+ Apache !
+
+
+

+
+
+
diff --git a/docs/docroot/index.html.he.iso8859-8 b/docs/docroot/index.html.he.iso8859-8
new file mode 100644
index 00000000000..84254886bc7
--- /dev/null
+++ b/docs/docroot/index.html.he.iso8859-8
@@ -0,0 +1,62 @@
+
+
+
+
+ Apache-ä úøù úð÷úäì ïåéñð óã
+
+
+
+
+
+
+
+
+
äæä ãåîòä úà äàåø äúà íà
+
Apache èðøèðéàä úøù ìù äð÷úääù øîà äæ
+
!!!äçìöäá äøáò
+
êìù íéöá÷ä úà óéñåäì ìåëé äúà åéùëò
+
.äæä óãä úà óéìçäìå úàæä äöéçîì
+
+
+
+
+
+ ?úéôéöù øúàä íå÷îá úàæ àåø
+
+
+
äæä øúàä ìò éàøçà éë ,ïàë äöîð äæä ãåîòä
+
.äæ èðøèðéàä úøùä ìù äéöøåâéôðå÷ä úà äðéù
+
.úåìàù íà úøùä éàøçà íà øù÷ øåöéì àð
+
úà äøöé øùà Apache Software Foundation
+
úøùä ú÷åæçú ìò úéàøçà äðéà ,äæ úøùä úðëåú
+
äéöøåâéôðå÷ úåéòá ïåøúôá äééòñì äìåëé äðéàå
+ .íäùìë
+
+
+
+
+
+
+
+
+
êåúá íéòöîð äéöèðîå÷åãä éëîñî
+ .úøùä úðëåú úìéáç
+
+
+
+
ãåîòä úéúçúá äöîðä ìîñá ùîúùäì éàùø äúà
+
.Apache é''ò ìòôåîù úøùä ìò ÷ø
+
+ !!!Apache-á ùåîéùä ìò äãåú
+
+
+
+
+
+
diff --git a/docs/docroot/index.html.it b/docs/docroot/index.html.it
new file mode 100644
index 00000000000..ab32d04a509
--- /dev/null
+++ b/docs/docroot/index.html.it
@@ -0,0 +1,38 @@
+
+
+
+
+ Pagina di prova dell'installazione di un sito Web con Apache
+
+
+
+
+
+
+Funziona! Il Server Web Apache e' stato installato su questo sito Web!
+Se riuscite a vedere questa pagina, allora vuol dire che coloro che gestiscono
+questo dominio hanno appena installato il software Web Server
+Apache correttamente. Ora e' necessario aggiungere il vostro materiale
+in questo direttorio e sostituire questa pagina di prova, oppure configurare
+il server per far riferimento al vostro materiale se collocato altrove.
+
+
+Se state vedendo questa pagina invece del sito che pensavate,
+vi preghiamo di contattare l'amministratore del sito in questione.
+(Provate ad inviare un email a <Webmaster@domain>.)
+Nonostante questo sito stia utilizzando il software Apache, questo non
+vi garantisce nessun tipo di contatto diretto al Gruppo Apache, quindi
+vi preghiamo di non inviare email riguardanti questo sito o al materiale
+in esso contenuto agli autori di Apache. Ogni messaggio del genere verra'
+ignorato.
+
+
+
La documentazione relativa di Apache
+e' inclusa nella distribuzione.
+Il Webmaster di questo sito e' libero di utilizzare l'immagine qui sotto
+su qualsiasi Web server potenziato con Apache. Grazie per aver scelto Apache!
+
+
+
+
+
diff --git a/docs/docroot/index.html.ja.iso2022-jp b/docs/docroot/index.html.ja.iso2022-jp
new file mode 100644
index 00000000000..0a4e5452613
--- /dev/null
+++ b/docs/docroot/index.html.ja.iso2022-jp
@@ -0,0 +1,42 @@
+
+
+
+
+ Apache $B%$%s%9%H!<%k;~$N%F%9%H%Z!<%8(B
+
+
+
+
+
+
+$B$b$7$3$N%Z!<%8$,FI$a$?$N$G$"$l$P!"(BApache $B%&%'%V%5!<%P(B$B$N%$%s%9%H!<%k$,$3$N7W;;5!$GL5;v$K=*N;$7$?$3$H$r0UL#$7$^$9!#$"$J$?$O!"$3$N%G%#%l%/%H%j$KJ8=q$r2C$($?$j!"$3$N%Z!<%8$rCV$-$+$($k$3$H$,$G$-$^$9!#(B
+
+
+
+$B$"$J$?$NM=A[$KH?$7$F!"$3$N%Z!<%8$,8+$($F$$$k$G$7$g$&$+(B?
+
+
+$B$3$N%Z!<%8$O!"%5%$%H4IM}$B$3$N%5!<%P$r4IM}$9$k@UG$$r;}$C$F$$$kJ}$KO"Mm$r$H$C$F(B$B$/$@$5$$!#$3$N%5%$%H4IM}
+
+
+
+
+Apache $B$K4X$9$k(B$BJ8=q(B $B$O!"$3$N(B web $B%5!<%PG[I[J*$NCf$K4^$^$l$F$$$^$9!#(B
+
+
+$B0J2<$N2hA|$O!"(BApache $B$rMxMQ$7$F$$$k(B web $B%5!<%P$G<+M3$K;H$&$3$H$,$G$-$^$9!#(BApache $B$r$4MxMQ$$$?$@$-!"$"$j$,$H$&$4$6$$$^$9(B!
+
+
+

+
+
+
diff --git a/docs/docroot/index.html.nl b/docs/docroot/index.html.nl
new file mode 100644
index 00000000000..b00747cd2a9
--- /dev/null
+++ b/docs/docroot/index.html.nl
@@ -0,0 +1,54 @@
+
+
+
+ Test Pagina voor de Apache Installatie op deze Web Site
+
+
+
+
+
+ Alles Werkt! De Apache Web Server is geinstalleerd op deze Web Site
+
+
+ Mocht u deze pagina zien, dan betekent dat, dat de eigenaren van dit
+ domein zojuist een nieuwe Apache Web
+ Server hebben geinstalleerd. Nu moet men nog de echte inhoud gaan
+ toevoegen, en moet men deze pagina gaan vervangen door de echte web
+ site.
+
+
+
+ Mocht u deze pagina zien, in plaats van de pagina of web site die u
+ verwachtte, neem dan contact op met de beheerder van
+ deze site. Bijvoorbeeld door een berichtje te sturen naar
+ <Webmaster@dit-domain>.
+
+ Alhoewel deze web site gebruik maakt van de Apache Software is er
+ verder geen enkele relatie tussen de beheerders van deze web site en
+ de Apache Groep (die de web software geschreven heeft). Het heeft dus
+ absoluut
+ geen zin de web software auteurs een emailtje te sturen. Mocht u dat
+ toch doen, dan wordt uw bericht gewoon genegeerd.
+
+
+
+ De
+ handleiding voor de apache web
+ server software maakt deel uit van deze distributie.
+
+
+ Als beheerder of webmaster is het u toegestaan het onderstaande
+ plaatje vrijelijk te gebruiken op uw 'Apache Powered' web site. Bedankt
+ voor het kiezen voor, en gebruiken van, Apache!
+
+
+

+
+
+
diff --git a/docs/docroot/index.html.no b/docs/docroot/index.html.no
new file mode 100644
index 00000000000..b69c4ce163c
--- /dev/null
+++ b/docs/docroot/index.html.no
@@ -0,0 +1,49 @@
+
+
+
+ Testside for Apache Installasjon på Webside
+
+
+
+
+ Det gikk bra! Det Apache Web Server Er Nå Installert her!
+
+
+ Hvis du kan se denne siden, det betyr at de som eier denne domene (domain)
+ har nettopp greid å installere Apache Web server
+ software. De må tilføye innhold til denne katalog og erstatte denne
+ plassholder siden, ellers peke serveren til de virkelige innhold.
+
+
+
+ Hvis du ser denne siden istedenfor den du ventet for, vennligst
+ ta kontakt med websever administratøren.
+ (Prøv å sende e-post til <Webmaster@domene>.)
+ Selv om denne hjemmesiden driver med Apache software, har den ingen annen
+ tilknytting til Apache Gruppen. Vennligst ikke send post angående denne hjemmesiden eller
+ dets innhold til Apache programmerere. Hvis du gjør det, din beskjed blir
+ oversett.
+
+
+
+ Den Apache
+ dokumentasjon
+ er inkludert i denne distribusjonen.
+
+
+ Denne sidens Webmaster kan bruke det grafikk nedenfør på en Apache-drevet Webserver.
+ Takk for at du bruker Apache!
+
+
+

+
+
+
diff --git a/docs/docroot/index.html.pt b/docs/docroot/index.html.pt
new file mode 100644
index 00000000000..4e2645f5d8a
--- /dev/null
+++ b/docs/docroot/index.html.pt
@@ -0,0 +1,42 @@
+
+
+
+ Página de teste da instalação do Apache Web Server
+
+
+
+
+
+
+ Se está a ver esta página significa que a instalação
+ do Apache Web Server foi efectuada
+ com sucesso. Pode agora adicionar conteúdo a esta directoria e substituir
+ esta página.
+
+
+Está a ver esta página em vez do website que
+ esperava?
+
+ Esta página está neste momento activa porque o administrador
+ deste site alterou a configuração do web server. Por favor contacte
+ a pessoa responsável pela manutenção deste servidor.
+ A Fundação Apache Software (Apache Software Foundation), apesar
+ de ter produzido o web server que o administrador deste site está a usar,
+ não tem qualquer tipo de responsabilidade pela manutenção
+ deste nem pode ajudar a resolver problemas de configuração.
+
+
+
+ A documentação foi incluída
+ juntamente com esta distribuição.
+
A imagem abaixo pode ser usada livremente em qualquer site presente num servidor
+ com o Apache Web Server instalado. Obrigado por usar o Apache Web Server!
+
+
+
diff --git a/docs/docroot/index.html.pt-br b/docs/docroot/index.html.pt-br
new file mode 100644
index 00000000000..72428d5a2a9
--- /dev/null
+++ b/docs/docroot/index.html.pt-br
@@ -0,0 +1,55 @@
+
+
+
+ Pagina teste para a instalacao do Apache no Web Site
+
+
+
+
+
+ Funcionou! O Apache Web Server esta instalado neste Web Site!
+
+
+ Se conseguir ver esta pagina, entao as pessoas que possuem este
+ dominio acabaram
+ de instalar o software Apache Web
+ server
+ com sucesso. Agora tem de adicionar o conteudo a esta directoria
+ e substituir esta pagina "placeholder", ou apontar o servidor para o
+ seu conteudo real.
+
+
+
+ Se esta a ver esta pagina em vez do site que esperava, por favor
+ contacte o administrador do site envolvido.
+ (Tente enviar um e-mail para
+ <Webmaster@domain>.)
+ Apesar de neste site estar a
+ correr o software Apache e quase certo que nao tem
+ outra ligacao com o Grupo Apache, por isso por favor nao envie
+ e-mails acerca deste
+ site ou do seu conteudo para os autores do Apache. Se o fizer, a
+ sua mensagem vai ser
+ ignorada.
+
+
+
+ O Apache documentation
+ foi incluido com esta distribuicao.
+
+
+ O Webmaster deste site e livre para utilizar a imagem abaixo num
+ Web server instalado com o Apache. Obrigado por utilizar o Apache!
+
+
+

+
+
+
diff --git a/docs/docroot/index.html.ru.cp-1251 b/docs/docroot/index.html.ru.cp-1251
new file mode 100644
index 00000000000..bfb8a166351
--- /dev/null
+++ b/docs/docroot/index.html.ru.cp-1251
@@ -0,0 +1,34 @@
+
+
+
+
+
+ Òåñòîâàÿ ñòðàíèöà óñòàíîâêè Apache
+
+
+
+Åñëè Âû ýòî âèäèòå, ýòî çíà÷èò, ÷òî óñòàíîâêà
+ÏÎ âåá-ñåðâåðà Apache íà ýòîé
+ñèñòåìå çàâåðøèëàñü óñïåøíî. Âû ìîæåòå òåïåðü äîáàâëÿòü ñîäåðæèìîå â ýòó
+äèðåêòîðèþ è çàìåíèòü ýòó ñòðàíèöó.
+
+
+
+
+Âû âèäèòå ýòî âìåñòî îæèäàåìîé ñòðàíèöû?
+Ýòà ñòðàíèöà íàõîäèòñÿ çäåñü ïîòîìó, ÷òî àäìèíèñòðàòîð ñèñòåìû èçìåíèë
+êîíôèãóðàöèþ ýòîãî âåá-ñåðâåðà. Ïîæàëóéñòà, ñâÿæèòåñü ñ ëèöîì, îòâåòñâåííûì
+çà ïîääåðæêó ýòîãî ñåðâåðà äëÿ âûÿñíåíèÿ âàøèõ âîïðîñîâ. Apache Software
+Foundation, àâòîð ÏÎ âåá-ñåðâåðà, êîòîðûì ïîëüçóåòñÿ àäìèíèñòðàòîð ýòîé
+ñèñòåìû, íå ñâÿçàí ñ ïîääåðæêîé ýòîé ñèñòåìû è íå ìîæåò ïîìî÷ü Âàì
+ðàçðåøèòü ïðîáëåìû êîíôèãóðàöèè.
+
+
+Äîêóìåíòàöèÿ ïî âåá-ñåðâåðó Apache ïðèëàãàåòñÿ
+ê êîìïëåêòó ÏÎ.
+
Âû ìîæåòå ñâîáîäíî èñïîëüçîâàòü ïèêòîãðàììó, íàõîäÿùóþñÿ íèæå, íà âåá-ñåðâåðå,
+èñïîëüçóþùèì ÏÎ Apache. Ñïàñèáî çà èñïîëüçîâàíèå Apache!
+
+
+
+
diff --git a/docs/docroot/index.html.ru.cp866 b/docs/docroot/index.html.ru.cp866
new file mode 100644
index 00000000000..b9f2615f379
--- /dev/null
+++ b/docs/docroot/index.html.ru.cp866
@@ -0,0 +1,34 @@
+
+
+
+
+
+ ¥á⮢ ï áâà ¨æ ãáâ ®¢ª¨ Apache
+
+
+
+
᫨ ë íâ® ¢¨¤¨â¥, íâ® § ç¨â, çâ® ãáâ ®¢ª
+ ¢¥¡-á¥à¢¥à Apache í⮩
+á¨á⥬¥ § ¢¥à訫 áì ãᯥè®. ë ¬®¦¥â¥ ⥯¥àì ¤®¡ ¢«ïâì ᮤ¥à¦¨¬®¥ ¢ íâã
+¤¨à¥ªâ®à¨î ¨ § ¬¥¨âì íâã áâà ¨æã.
+
+
+
+
+ë ¢¨¤¨â¥ íâ® ¢¬¥áâ® ®¦¨¤ ¥¬®© áâà ¨æë?
+â áâà ¨æ 室¨âáï §¤¥áì ¯®â®¬ã, çâ® ¤¬¨¨áâà â®à á¨áâ¥¬ë ¨§¬¥¨«
+ª®ä¨£ãà æ¨î í⮣® ¢¥¡-á¥à¢¥à . ®¦ «ã©áâ , á¢ï¦¨â¥áì á «¨æ®¬, ®â¢¥âᢥë¬
+§ ¯®¤¤¥à¦ªã í⮣® á¥à¢¥à ¤«ï ¢ëïá¥¨ï ¢ è¨å ¢®¯à®á®¢. Apache Software
+Foundation, ¢â®à ¢¥¡-á¥à¢¥à , ª®â®àë¬ ¯®«ì§ã¥âáï ¤¬¨¨áâà â®à í⮩
+á¨á⥬ë, ¥ á¢ï§ á ¯®¤¤¥à¦ª®© í⮩ á¨áâ¥¬ë ¨ ¥ ¬®¦¥â ¯®¬®çì ¬
+à §à¥è¨âì ¯à®¡«¥¬ë ª®ä¨£ãà æ¨¨.
+
+
+®ªã¬¥â æ¨ï ¯® ¢¥¡-á¥à¢¥àã Apache ¯à¨« £ ¥âáï
+ª ª®¬¯«¥ªâã .
+
ë ¬®¦¥â¥ ᢮¡®¤® ¨á¯®«ì§®¢ âì ¯¨ªâ®£à ¬¬ã, 室ïéãîáï ¨¦¥, ¢¥¡-á¥à¢¥à¥,
+¨á¯®«ì§ãî騬 Apache. ¯ ᨡ® § ¨á¯®«ì§®¢ ¨¥ Apache!
+
+
+
+
diff --git a/docs/docroot/index.html.ru.iso-ru b/docs/docroot/index.html.ru.iso-ru
new file mode 100644
index 00000000000..114d9f75054
--- /dev/null
+++ b/docs/docroot/index.html.ru.iso-ru
@@ -0,0 +1,34 @@
+
+
+
+
+
+ ÂÕáâÞÒÐï áâàÐÝØæÐ ãáâÐÝÞÒÚØ Apache
+
+
+
+µáÛØ ²ë íâÞ ÒØÔØâÕ, íâÞ ×ÝÐçØâ, çâÞ ãáâÐÝÞÒÚÐ
+¿¾ ÒÕÑ-áÕàÒÕàÐ Apache ÝÐ íâÞÙ
+áØáâÕÜÕ ×ÐÒÕàèØÛÐáì ãáßÕèÝÞ. ²ë ÜÞÖÕâÕ âÕßÕàì ÔÞÑÐÒÛïâì áÞÔÕàÖØÜÞÕ Ò íâã
+ÔØàÕÚâÞàØî Ø ×ÐÜÕÝØâì íâã áâàÐÝØæã.
+
+
+
+
+²ë ÒØÔØâÕ íâÞ ÒÜÕáâÞ ÞÖØÔÐÕÜÞÙ áâàÐÝØæë?
+ÍâÐ áâàÐÝØæÐ ÝÐåÞÔØâáï ×ÔÕáì ßÞâÞÜã, çâÞ ÐÔÜØÝØáâàÐâÞà áØáâÕÜë Ø×ÜÕÝØÛ
+ÚÞÝäØÓãàÐæØî íâÞÓÞ ÒÕÑ-áÕàÒÕàÐ. ¿ÞÖÐÛãÙáâÐ, áÒïÖØâÕáì á ÛØæÞÜ, ÞâÒÕâáÒÕÝÝëÜ
+×Ð ßÞÔÔÕàÖÚã íâÞÓÞ áÕàÒÕàÐ ÔÛï ÒëïáÝÕÝØï ÒÐèØå ÒÞßàÞáÞÒ. Apache Software
+Foundation, ÐÒâÞà ¿¾ ÒÕÑ-áÕàÒÕàÐ, ÚÞâÞàëÜ ßÞÛì×ãÕâáï ÐÔÜØÝØáâàÐâÞà íâÞÙ
+áØáâÕÜë, ÝÕ áÒï×ÐÝ á ßÞÔÔÕàÖÚÞÙ íâÞÙ áØáâÕÜë Ø ÝÕ ÜÞÖÕâ ßÞÜÞçì ²ÐÜ
+àÐ×àÕèØâì ßàÞÑÛÕÜë ÚÞÝäØÓãàÐæØØ.
+
+
+´ÞÚãÜÕÝâÐæØï ßÞ ÒÕÑ-áÕàÒÕàã Apache ßàØÛÐÓÐÕâáï
+Ú ÚÞÜßÛÕÚâã ¿¾.
+
²ë ÜÞÖÕâÕ áÒÞÑÞÔÝÞ ØáßÞÛì×ÞÒÐâì ߨÚâÞÓàÐÜÜã, ÝÐåÞÔïéãîáï ÝØÖÕ, ÝÐ ÒÕÑ-áÕàÒÕàÕ,
+ØáßÞÛì×ãîéØÜ ¿¾ Apache. ÁßÐáØÑÞ ×Ð ØáßÞÛì×ÞÒÐÝØÕ Apache!
+
+
+
+
diff --git a/docs/docroot/index.html.ru.koi8-r b/docs/docroot/index.html.ru.koi8-r
new file mode 100644
index 00000000000..685b56207d0
--- /dev/null
+++ b/docs/docroot/index.html.ru.koi8-r
@@ -0,0 +1,34 @@
+
+
+
+
+
+ ôÅÓÔÏ×ÁÑ ÓÔÒÁÎÉÃÁ ÕÓÔÁÎÏ×ËÉ Apache
+
+
+
+åÓÌÉ ÷Ù ÜÔÏ ×ÉÄÉÔÅ, ÜÔÏ ÚÎÁÞÉÔ, ÞÔÏ ÕÓÔÁÎÏ×ËÁ
+ðï ×ÅÂ-ÓÅÒ×ÅÒÁ Apache ÎÁ ÜÔÏÊ
+ÓÉÓÔÅÍÅ ÚÁ×ÅÒÛÉÌÁÓØ ÕÓÐÅÛÎÏ. ÷Ù ÍÏÖÅÔÅ ÔÅÐÅÒØ ÄÏÂÁ×ÌÑÔØ ÓÏÄÅÒÖÉÍÏÅ × ÜÔÕ
+ÄÉÒÅËÔÏÒÉÀ É ÚÁÍÅÎÉÔØ ÜÔÕ ÓÔÒÁÎÉÃÕ.
+
+
+
+
+÷Ù ×ÉÄÉÔÅ ÜÔÏ ×ÍÅÓÔÏ ÏÖÉÄÁÅÍÏÊ ÓÔÒÁÎÉÃÙ?
+üÔÁ ÓÔÒÁÎÉÃÁ ÎÁÈÏÄÉÔÓÑ ÚÄÅÓØ ÐÏÔÏÍÕ, ÞÔÏ ÁÄÍÉÎÉÓÔÒÁÔÏÒ ÓÉÓÔÅÍÙ ÉÚÍÅÎÉÌ
+ËÏÎÆÉÇÕÒÁÃÉÀ ÜÔÏÇÏ ×ÅÂ-ÓÅÒ×ÅÒÁ. ðÏÖÁÌÕÊÓÔÁ, Ó×ÑÖÉÔÅÓØ Ó ÌÉÃÏÍ, ÏÔ×ÅÔÓ×ÅÎÎÙÍ
+ÚÁ ÐÏÄÄÅÒÖËÕ ÜÔÏÇÏ ÓÅÒ×ÅÒÁ ÄÌÑ ×ÙÑÓÎÅÎÉÑ ×ÁÛÉÈ ×ÏÐÒÏÓÏ×. Apache Software
+Foundation, Á×ÔÏÒ ðï ×ÅÂ-ÓÅÒ×ÅÒÁ, ËÏÔÏÒÙÍ ÐÏÌØÚÕÅÔÓÑ ÁÄÍÉÎÉÓÔÒÁÔÏÒ ÜÔÏÊ
+ÓÉÓÔÅÍÙ, ÎÅ Ó×ÑÚÁÎ Ó ÐÏÄÄÅÒÖËÏÊ ÜÔÏÊ ÓÉÓÔÅÍÙ É ÎÅ ÍÏÖÅÔ ÐÏÍÏÞØ ÷ÁÍ
+ÒÁÚÒÅÛÉÔØ ÐÒÏÂÌÅÍÙ ËÏÎÆÉÇÕÒÁÃÉÉ.
+
+
+äÏËÕÍÅÎÔÁÃÉÑ ÐÏ ×ÅÂ-ÓÅÒ×ÅÒÕ Apache ÐÒÉÌÁÇÁÅÔÓÑ
+Ë ËÏÍÐÌÅËÔÕ ðï.
+
÷Ù ÍÏÖÅÔÅ Ó×ÏÂÏÄÎÏ ÉÓÐÏÌØÚÏ×ÁÔØ ÐÉËÔÏÇÒÁÍÍÕ, ÎÁÈÏÄÑÝÕÀÓÑ ÎÉÖÅ, ÎÁ ×ÅÂ-ÓÅÒ×ÅÒÅ,
+ÉÓÐÏÌØÚÕÀÝÉÍ ðï Apache. óÐÁÓÉÂÏ ÚÁ ÉÓÐÏÌØÚÏ×ÁÎÉÅ Apache!
+
+
+
+
diff --git a/docs/docroot/index.html.ru.utf8 b/docs/docroot/index.html.ru.utf8
new file mode 100644
index 00000000000..f8a93c30206
--- /dev/null
+++ b/docs/docroot/index.html.ru.utf8
@@ -0,0 +1,34 @@
+
+
+
+
+
+ ТеÑÑÐ¾Ð²Ð°Ñ ÑÑÑаниÑа ÑÑÑановки Apache
+
+
+
+ÐÑли ÐÑ ÑÑо видиÑе, ÑÑо знаÑиÑ, ÑÑо ÑÑÑановка
+ÐРвеб-ÑеÑвеÑа Apache на ÑÑой
+ÑиÑÑеме завеÑÑилаÑÑ ÑÑпеÑно. ÐÑ Ð¼Ð¾Ð¶ÐµÑе ÑепеÑÑ Ð´Ð¾Ð±Ð°Ð²Ð»ÑÑÑ ÑодеÑжимое в ÑÑÑ
+диÑекÑоÑÐ¸Ñ Ð¸ замениÑÑ ÑÑÑ ÑÑÑаниÑÑ.
+
+
+
+
+ÐÑ Ð²Ð¸Ð´Ð¸Ñе ÑÑо вмеÑÑо ожидаемой ÑÑÑаниÑÑ?
+ÐÑа ÑÑÑаниÑа наÑ
одиÑÑÑ Ð·Ð´ÐµÑÑ Ð¿Ð¾ÑомÑ, ÑÑо админиÑÑÑаÑÐ¾Ñ ÑиÑÑÐµÐ¼Ñ Ð¸Ð·Ð¼ÐµÐ½Ð¸Ð»
+конÑигÑÑаÑÐ¸Ñ ÑÑого веб-ÑеÑвеÑа. ÐожалÑйÑÑа, ÑвÑжиÑеÑÑ Ñ Ð»Ð¸Ñом, оÑвеÑÑвеннÑм
+за поддеÑÐ¶ÐºÑ ÑÑого ÑеÑвеÑа Ð´Ð»Ñ Ð²ÑÑÑÐ½ÐµÐ½Ð¸Ñ Ð²Ð°ÑиÑ
вопÑоÑов. Apache Software
+Foundation, авÑÐ¾Ñ ÐРвеб-ÑеÑвеÑа, коÑоÑÑм полÑзÑеÑÑÑ Ð°Ð´Ð¼Ð¸Ð½Ð¸ÑÑÑаÑÐ¾Ñ ÑÑой
+ÑиÑÑемÑ, не ÑвÑзан Ñ Ð¿Ð¾Ð´Ð´ÐµÑжкой ÑÑой ÑиÑÑÐµÐ¼Ñ Ð¸ не Ð¼Ð¾Ð¶ÐµÑ Ð¿Ð¾Ð¼Ð¾ÑÑ Ðам
+ÑазÑеÑиÑÑ Ð¿ÑÐ¾Ð±Ð»ÐµÐ¼Ñ ÐºÐ¾Ð½ÑигÑÑаÑии.
+
+
+ÐокÑменÑаÑÐ¸Ñ Ð¿Ð¾ веб-ÑеÑвеÑÑ Apache пÑилагаеÑÑÑ
+к комплекÑÑ ÐÐ.
+
ÐÑ Ð¼Ð¾Ð¶ÐµÑе Ñвободно иÑполÑзоваÑÑ Ð¿Ð¸ÐºÑогÑаммÑ, наÑ
одÑÑÑÑÑÑ Ð½Ð¸Ð¶Ðµ, на веб-ÑеÑвеÑе,
+иÑполÑзÑÑÑим ÐÐ Apache. СпаÑибо за иÑполÑзование Apache!
+
+
+
+
diff --git a/docs/icons/README b/docs/icons/README
new file mode 100644
index 00000000000..74b2970b9e8
--- /dev/null
+++ b/docs/icons/README
@@ -0,0 +1,158 @@
+Public Domain Icons
+
+ These icons were originally made for Mosaic for X and have been
+ included in the NCSA httpd and Apache server distributions in the
+ past. They are in the public domain and may be freely included in any
+ application. The originals were done by Kevin Hughes
+ (kevinh@kevcom.com).
+
+ Many thanks to Andy Polyakov for tuning the icon colors and adding a
+ few new images. If you'd like to contribute additions or ideas to
+ this set, please let me know.
+
+ Almost all of these icons are 20x22 pixels in size. There are
+ alternative icons in the "small" directory that are 16x16 in size,
+ provided by Mike Brown (mike@hyperreal.org).
+
+Suggested Uses
+
+The following are a few suggestions, to serve as a starting point for ideas.
+Please feel free to tweak and rename the icons as you like.
+
+ a.gif
+ This might be used to represent PostScript or text layout
+ languages.
+
+ alert.black.gif, alert.red.gif
+ These can be used to highlight any important items, such as a
+ README file in a directory.
+
+ back.gif, forward.gif
+ These can be used as links to go to previous and next areas.
+
+ ball.gray.gif, ball.red.gif
+ These might be used as bullets.
+
+ binary.gif
+ This can be used to represent binary files.
+
+ binhex.gif
+ This can represent BinHex-encoded data.
+
+ blank.gif
+ This can be used as a placeholder or a spacing element.
+
+ bomb.gif
+ This can be used to repreesnt core files.
+
+ box1.gif, box2.gif
+ These icons can be used to represent generic 3D applications and
+ related files.
+
+ broken.gif
+ This can represent corrupted data.
+
+ burst.gif
+ This can call attention to new and important items.
+
+ c.gif
+ This might represent C source code.
+
+ comp.blue.gif, comp.red.gif
+ These little computer icons can stand for telnet or FTP
+ sessions.
+
+ compressed.gif
+ This may represent compressed data.
+
+ continued.gif
+ This can be a link to a continued listing of a directory.
+
+ down.gif, up.gif, left.gif, right.gif
+ These can be used to scroll up, down, left and right in a
+ listing or may be used to denote items in an outline.
+
+ dvi.gif
+ This can represent DVI files.
+
+ f.gif
+ This might represent FORTRAN or Forth source code.
+
+ folder.gif, folder.open.gif, folder.sec.gif
+ The folder can represent directories. There is also a version
+ that can represent secure directories or directories that cannot
+ be viewed.
+
+ generic.gif, generic.sec.gif, generic.red.gif
+ These can represent generic files, secure files, and important
+ files, respectively.
+
+ hand.right.gif, hand.up.gif
+ These can point out important items (pun intended).
+
+ image1.gif, image2.gif, image3.gif
+ These can represent image formats of various types.
+
+ index.gif
+ This might represent a WAIS index or search facility.
+
+ layout.gif
+ This might represent files and formats that contain graphics as
+ well as text layout, such as HTML and PDF files.
+
+ link.gif
+ This might represent files that are symbolic links.
+
+ movie.gif
+ This can represent various movie formats.
+
+ p.gif
+ This may stand for Perl or Python source code.
+
+ pie0.gif ... pie8.gif
+ These icons can be used in applications where a list of
+ documents is returned from a search. The little pie chart images
+ can denote how relevant the documents may be to your search
+ query.
+
+ patch.gif
+ This may stand for patches and diff files.
+
+ portal.gif
+ This might be a link to an online service or a 3D world.
+
+ ps.gif, quill.gif
+ These may represent PostScript files.
+
+ screw1.gif, screw2.gif
+ These may represent CAD or engineering data and formats.
+
+ script.gif
+ This can represent any of various interpreted languages, such as
+ Perl, python, TCL, and shell scripts, as well as server
+ configuration files.
+
+ sound1.gif, sound2.gif
+ These can represent sound files.
+
+ sphere1.gif, sphere2.gif
+ These can represent 3D worlds or rendering applications and
+ formats.
+
+ tex.gif
+ This can represent TeX files.
+
+ text.gif
+ This can represent generic (plain) text files.
+
+ transfer.gif
+ This can represent FTP transfers or uploads/downloads.
+
+ unknown.gif
+ This may represent a file of an unknown type.
+
+ uuencoded.gif
+ This can stand for uuencoded data.
+
+ world1.gif, world2.gif
+ These can represent 3D worlds or other 3D formats.
diff --git a/docs/icons/a.gif b/docs/icons/a.gif
new file mode 100644
index 00000000000..bb23d971f4c
Binary files /dev/null and b/docs/icons/a.gif differ
diff --git a/docs/icons/alert.black.gif b/docs/icons/alert.black.gif
new file mode 100644
index 00000000000..eaecd2172a0
Binary files /dev/null and b/docs/icons/alert.black.gif differ
diff --git a/docs/icons/alert.red.gif b/docs/icons/alert.red.gif
new file mode 100644
index 00000000000..a4238940433
Binary files /dev/null and b/docs/icons/alert.red.gif differ
diff --git a/docs/icons/apache_pb.gif b/docs/icons/apache_pb.gif
new file mode 100644
index 00000000000..3a1c139fc42
Binary files /dev/null and b/docs/icons/apache_pb.gif differ
diff --git a/docs/icons/back.gif b/docs/icons/back.gif
new file mode 100644
index 00000000000..a694ae1ec3f
Binary files /dev/null and b/docs/icons/back.gif differ
diff --git a/docs/icons/ball.gray.gif b/docs/icons/ball.gray.gif
new file mode 100644
index 00000000000..eb84268c4cc
Binary files /dev/null and b/docs/icons/ball.gray.gif differ
diff --git a/docs/icons/ball.red.gif b/docs/icons/ball.red.gif
new file mode 100644
index 00000000000..a8425cb574b
Binary files /dev/null and b/docs/icons/ball.red.gif differ
diff --git a/docs/icons/binary.gif b/docs/icons/binary.gif
new file mode 100644
index 00000000000..9a15cbae04c
Binary files /dev/null and b/docs/icons/binary.gif differ
diff --git a/docs/icons/binhex.gif b/docs/icons/binhex.gif
new file mode 100644
index 00000000000..62d0363108d
Binary files /dev/null and b/docs/icons/binhex.gif differ
diff --git a/docs/icons/blank.gif b/docs/icons/blank.gif
new file mode 100644
index 00000000000..0ccf01e1983
Binary files /dev/null and b/docs/icons/blank.gif differ
diff --git a/docs/icons/bomb.gif b/docs/icons/bomb.gif
new file mode 100644
index 00000000000..270fdb1c064
Binary files /dev/null and b/docs/icons/bomb.gif differ
diff --git a/docs/icons/box1.gif b/docs/icons/box1.gif
new file mode 100644
index 00000000000..65dcd002eaf
Binary files /dev/null and b/docs/icons/box1.gif differ
diff --git a/docs/icons/box2.gif b/docs/icons/box2.gif
new file mode 100644
index 00000000000..c43bc4faecf
Binary files /dev/null and b/docs/icons/box2.gif differ
diff --git a/docs/icons/broken.gif b/docs/icons/broken.gif
new file mode 100644
index 00000000000..9f8cbe9f760
Binary files /dev/null and b/docs/icons/broken.gif differ
diff --git a/docs/icons/burst.gif b/docs/icons/burst.gif
new file mode 100644
index 00000000000..fbdcf575f78
Binary files /dev/null and b/docs/icons/burst.gif differ
diff --git a/docs/icons/c.gif b/docs/icons/c.gif
new file mode 100644
index 00000000000..7555b6c164f
Binary files /dev/null and b/docs/icons/c.gif differ
diff --git a/docs/icons/comp.blue.gif b/docs/icons/comp.blue.gif
new file mode 100644
index 00000000000..f8d76a8c23f
Binary files /dev/null and b/docs/icons/comp.blue.gif differ
diff --git a/docs/icons/comp.gray.gif b/docs/icons/comp.gray.gif
new file mode 100644
index 00000000000..7664cd03649
Binary files /dev/null and b/docs/icons/comp.gray.gif differ
diff --git a/docs/icons/compressed.gif b/docs/icons/compressed.gif
new file mode 100644
index 00000000000..39e732739f5
Binary files /dev/null and b/docs/icons/compressed.gif differ
diff --git a/docs/icons/continued.gif b/docs/icons/continued.gif
new file mode 100644
index 00000000000..b0ffb7e0cc0
Binary files /dev/null and b/docs/icons/continued.gif differ
diff --git a/docs/icons/dir.gif b/docs/icons/dir.gif
new file mode 100644
index 00000000000..48264601ae0
Binary files /dev/null and b/docs/icons/dir.gif differ
diff --git a/docs/icons/down.gif b/docs/icons/down.gif
new file mode 100644
index 00000000000..a354c871cd0
Binary files /dev/null and b/docs/icons/down.gif differ
diff --git a/docs/icons/dvi.gif b/docs/icons/dvi.gif
new file mode 100644
index 00000000000..791be33105d
Binary files /dev/null and b/docs/icons/dvi.gif differ
diff --git a/docs/icons/f.gif b/docs/icons/f.gif
new file mode 100644
index 00000000000..fbe353c2822
Binary files /dev/null and b/docs/icons/f.gif differ
diff --git a/docs/icons/folder.gif b/docs/icons/folder.gif
new file mode 100644
index 00000000000..48264601ae0
Binary files /dev/null and b/docs/icons/folder.gif differ
diff --git a/docs/icons/folder.open.gif b/docs/icons/folder.open.gif
new file mode 100644
index 00000000000..30979cb5285
Binary files /dev/null and b/docs/icons/folder.open.gif differ
diff --git a/docs/icons/folder.sec.gif b/docs/icons/folder.sec.gif
new file mode 100644
index 00000000000..75332d9e59b
Binary files /dev/null and b/docs/icons/folder.sec.gif differ
diff --git a/docs/icons/forward.gif b/docs/icons/forward.gif
new file mode 100644
index 00000000000..b2959b4c85c
Binary files /dev/null and b/docs/icons/forward.gif differ
diff --git a/docs/icons/generic.gif b/docs/icons/generic.gif
new file mode 100644
index 00000000000..de60b2940f9
Binary files /dev/null and b/docs/icons/generic.gif differ
diff --git a/docs/icons/generic.red.gif b/docs/icons/generic.red.gif
new file mode 100644
index 00000000000..94743981d93
Binary files /dev/null and b/docs/icons/generic.red.gif differ
diff --git a/docs/icons/generic.sec.gif b/docs/icons/generic.sec.gif
new file mode 100644
index 00000000000..88d5240c3c3
Binary files /dev/null and b/docs/icons/generic.sec.gif differ
diff --git a/docs/icons/hand.right.gif b/docs/icons/hand.right.gif
new file mode 100644
index 00000000000..5cdbc7206da
Binary files /dev/null and b/docs/icons/hand.right.gif differ
diff --git a/docs/icons/hand.up.gif b/docs/icons/hand.up.gif
new file mode 100644
index 00000000000..85a5d683177
Binary files /dev/null and b/docs/icons/hand.up.gif differ
diff --git a/docs/icons/icon.sheet.gif b/docs/icons/icon.sheet.gif
new file mode 100644
index 00000000000..ad1686e4480
Binary files /dev/null and b/docs/icons/icon.sheet.gif differ
diff --git a/docs/icons/image1.gif b/docs/icons/image1.gif
new file mode 100644
index 00000000000..01e442bfa92
Binary files /dev/null and b/docs/icons/image1.gif differ
diff --git a/docs/icons/image2.gif b/docs/icons/image2.gif
new file mode 100644
index 00000000000..751faeea364
Binary files /dev/null and b/docs/icons/image2.gif differ
diff --git a/docs/icons/image3.gif b/docs/icons/image3.gif
new file mode 100644
index 00000000000..4f30484ff64
Binary files /dev/null and b/docs/icons/image3.gif differ
diff --git a/docs/icons/index.gif b/docs/icons/index.gif
new file mode 100644
index 00000000000..162478fb3a7
Binary files /dev/null and b/docs/icons/index.gif differ
diff --git a/docs/icons/layout.gif b/docs/icons/layout.gif
new file mode 100644
index 00000000000..c96338a1522
Binary files /dev/null and b/docs/icons/layout.gif differ
diff --git a/docs/icons/left.gif b/docs/icons/left.gif
new file mode 100644
index 00000000000..279e6710d49
Binary files /dev/null and b/docs/icons/left.gif differ
diff --git a/docs/icons/link.gif b/docs/icons/link.gif
new file mode 100644
index 00000000000..c5b6889a76d
Binary files /dev/null and b/docs/icons/link.gif differ
diff --git a/docs/icons/movie.gif b/docs/icons/movie.gif
new file mode 100644
index 00000000000..00351837741
Binary files /dev/null and b/docs/icons/movie.gif differ
diff --git a/docs/icons/p.gif b/docs/icons/p.gif
new file mode 100644
index 00000000000..7b917b4e91e
Binary files /dev/null and b/docs/icons/p.gif differ
diff --git a/docs/icons/patch.gif b/docs/icons/patch.gif
new file mode 100644
index 00000000000..39bc90e7953
Binary files /dev/null and b/docs/icons/patch.gif differ
diff --git a/docs/icons/pdf.gif b/docs/icons/pdf.gif
new file mode 100644
index 00000000000..c88fd777c4b
Binary files /dev/null and b/docs/icons/pdf.gif differ
diff --git a/docs/icons/pie0.gif b/docs/icons/pie0.gif
new file mode 100644
index 00000000000..6f7a0ae7a70
Binary files /dev/null and b/docs/icons/pie0.gif differ
diff --git a/docs/icons/pie1.gif b/docs/icons/pie1.gif
new file mode 100644
index 00000000000..03aa6be71eb
Binary files /dev/null and b/docs/icons/pie1.gif differ
diff --git a/docs/icons/pie2.gif b/docs/icons/pie2.gif
new file mode 100644
index 00000000000..b04c5e09086
Binary files /dev/null and b/docs/icons/pie2.gif differ
diff --git a/docs/icons/pie3.gif b/docs/icons/pie3.gif
new file mode 100644
index 00000000000..4db9d023eda
Binary files /dev/null and b/docs/icons/pie3.gif differ
diff --git a/docs/icons/pie4.gif b/docs/icons/pie4.gif
new file mode 100644
index 00000000000..93471fdd885
Binary files /dev/null and b/docs/icons/pie4.gif differ
diff --git a/docs/icons/pie5.gif b/docs/icons/pie5.gif
new file mode 100644
index 00000000000..57aee93f070
Binary files /dev/null and b/docs/icons/pie5.gif differ
diff --git a/docs/icons/pie6.gif b/docs/icons/pie6.gif
new file mode 100644
index 00000000000..0dc327b5697
Binary files /dev/null and b/docs/icons/pie6.gif differ
diff --git a/docs/icons/pie7.gif b/docs/icons/pie7.gif
new file mode 100644
index 00000000000..8661337f067
Binary files /dev/null and b/docs/icons/pie7.gif differ
diff --git a/docs/icons/pie8.gif b/docs/icons/pie8.gif
new file mode 100644
index 00000000000..59ddb34ce0f
Binary files /dev/null and b/docs/icons/pie8.gif differ
diff --git a/docs/icons/portal.gif b/docs/icons/portal.gif
new file mode 100644
index 00000000000..0e6e506e004
Binary files /dev/null and b/docs/icons/portal.gif differ
diff --git a/docs/icons/ps.gif b/docs/icons/ps.gif
new file mode 100644
index 00000000000..0f565bc1db7
Binary files /dev/null and b/docs/icons/ps.gif differ
diff --git a/docs/icons/quill.gif b/docs/icons/quill.gif
new file mode 100644
index 00000000000..818a5cdc7e0
Binary files /dev/null and b/docs/icons/quill.gif differ
diff --git a/docs/icons/right.gif b/docs/icons/right.gif
new file mode 100644
index 00000000000..b256e5f75fb
Binary files /dev/null and b/docs/icons/right.gif differ
diff --git a/docs/icons/screw1.gif b/docs/icons/screw1.gif
new file mode 100644
index 00000000000..af6ba2b097b
Binary files /dev/null and b/docs/icons/screw1.gif differ
diff --git a/docs/icons/screw2.gif b/docs/icons/screw2.gif
new file mode 100644
index 00000000000..06dccb3e44c
Binary files /dev/null and b/docs/icons/screw2.gif differ
diff --git a/docs/icons/script.gif b/docs/icons/script.gif
new file mode 100644
index 00000000000..d8a853bc582
Binary files /dev/null and b/docs/icons/script.gif differ
diff --git a/docs/icons/small/README.txt b/docs/icons/small/README.txt
new file mode 100644
index 00000000000..deb96702b76
--- /dev/null
+++ b/docs/icons/small/README.txt
@@ -0,0 +1,6 @@
+
+These icons are provided as an alternative to the standard Apache
+icon graphics. All graphics in this directory, with the exception
+of rainbow.gif, are 16x16 pixels in size, rather than the 20x22
+dimension icons which are the normal defaults for Apache and are
+in the parent directory of this one.
diff --git a/docs/icons/small/back.gif b/docs/icons/small/back.gif
new file mode 100644
index 00000000000..e331454726b
Binary files /dev/null and b/docs/icons/small/back.gif differ
diff --git a/docs/icons/small/binary.gif b/docs/icons/small/binary.gif
new file mode 100644
index 00000000000..995f79b9b10
Binary files /dev/null and b/docs/icons/small/binary.gif differ
diff --git a/docs/icons/small/binhex.gif b/docs/icons/small/binhex.gif
new file mode 100644
index 00000000000..3d54a5458e6
Binary files /dev/null and b/docs/icons/small/binhex.gif differ
diff --git a/docs/icons/small/blank.gif b/docs/icons/small/blank.gif
new file mode 100644
index 00000000000..606787a8399
Binary files /dev/null and b/docs/icons/small/blank.gif differ
diff --git a/docs/icons/small/broken.gif b/docs/icons/small/broken.gif
new file mode 100644
index 00000000000..1bcc57f25c5
Binary files /dev/null and b/docs/icons/small/broken.gif differ
diff --git a/docs/icons/small/burst.gif b/docs/icons/small/burst.gif
new file mode 100644
index 00000000000..d882ceba9cb
Binary files /dev/null and b/docs/icons/small/burst.gif differ
diff --git a/docs/icons/small/comp1.gif b/docs/icons/small/comp1.gif
new file mode 100644
index 00000000000..712f36afdb2
Binary files /dev/null and b/docs/icons/small/comp1.gif differ
diff --git a/docs/icons/small/comp2.gif b/docs/icons/small/comp2.gif
new file mode 100644
index 00000000000..7759eb11f95
Binary files /dev/null and b/docs/icons/small/comp2.gif differ
diff --git a/docs/icons/small/compressed.gif b/docs/icons/small/compressed.gif
new file mode 100644
index 00000000000..d3b156072ac
Binary files /dev/null and b/docs/icons/small/compressed.gif differ
diff --git a/docs/icons/small/continued.gif b/docs/icons/small/continued.gif
new file mode 100644
index 00000000000..e1c9f2cfa68
Binary files /dev/null and b/docs/icons/small/continued.gif differ
diff --git a/docs/icons/small/dir.gif b/docs/icons/small/dir.gif
new file mode 100644
index 00000000000..7b37b099177
Binary files /dev/null and b/docs/icons/small/dir.gif differ
diff --git a/docs/icons/small/dir2.gif b/docs/icons/small/dir2.gif
new file mode 100644
index 00000000000..425d6e4b77c
Binary files /dev/null and b/docs/icons/small/dir2.gif differ
diff --git a/docs/icons/small/doc.gif b/docs/icons/small/doc.gif
new file mode 100644
index 00000000000..0fcf18db2a8
Binary files /dev/null and b/docs/icons/small/doc.gif differ
diff --git a/docs/icons/small/forward.gif b/docs/icons/small/forward.gif
new file mode 100644
index 00000000000..2997466eb4d
Binary files /dev/null and b/docs/icons/small/forward.gif differ
diff --git a/docs/icons/small/generic.gif b/docs/icons/small/generic.gif
new file mode 100644
index 00000000000..f8da6ff92c3
Binary files /dev/null and b/docs/icons/small/generic.gif differ
diff --git a/docs/icons/small/generic2.gif b/docs/icons/small/generic2.gif
new file mode 100644
index 00000000000..992f13331bb
Binary files /dev/null and b/docs/icons/small/generic2.gif differ
diff --git a/docs/icons/small/generic3.gif b/docs/icons/small/generic3.gif
new file mode 100644
index 00000000000..85aa275e25a
Binary files /dev/null and b/docs/icons/small/generic3.gif differ
diff --git a/docs/icons/small/image.gif b/docs/icons/small/image.gif
new file mode 100644
index 00000000000..dc3d95ced76
Binary files /dev/null and b/docs/icons/small/image.gif differ
diff --git a/docs/icons/small/image2.gif b/docs/icons/small/image2.gif
new file mode 100644
index 00000000000..a5c40f15508
Binary files /dev/null and b/docs/icons/small/image2.gif differ
diff --git a/docs/icons/small/index.gif b/docs/icons/small/index.gif
new file mode 100644
index 00000000000..526df6b0645
Binary files /dev/null and b/docs/icons/small/index.gif differ
diff --git a/docs/icons/small/key.gif b/docs/icons/small/key.gif
new file mode 100644
index 00000000000..8dfd6c09de3
Binary files /dev/null and b/docs/icons/small/key.gif differ
diff --git a/docs/icons/small/movie.gif b/docs/icons/small/movie.gif
new file mode 100644
index 00000000000..7b4a42e7a0e
Binary files /dev/null and b/docs/icons/small/movie.gif differ
diff --git a/docs/icons/small/patch.gif b/docs/icons/small/patch.gif
new file mode 100644
index 00000000000..100484e5982
Binary files /dev/null and b/docs/icons/small/patch.gif differ
diff --git a/docs/icons/small/ps.gif b/docs/icons/small/ps.gif
new file mode 100644
index 00000000000..fa4bcfce30f
Binary files /dev/null and b/docs/icons/small/ps.gif differ
diff --git a/docs/icons/small/rainbow.gif b/docs/icons/small/rainbow.gif
new file mode 100644
index 00000000000..8216b89bade
Binary files /dev/null and b/docs/icons/small/rainbow.gif differ
diff --git a/docs/icons/small/sound.gif b/docs/icons/small/sound.gif
new file mode 100644
index 00000000000..a7a89ffd9ed
Binary files /dev/null and b/docs/icons/small/sound.gif differ
diff --git a/docs/icons/small/sound2.gif b/docs/icons/small/sound2.gif
new file mode 100644
index 00000000000..07706e07b86
Binary files /dev/null and b/docs/icons/small/sound2.gif differ
diff --git a/docs/icons/small/tar.gif b/docs/icons/small/tar.gif
new file mode 100644
index 00000000000..59c3ffb9a5f
Binary files /dev/null and b/docs/icons/small/tar.gif differ
diff --git a/docs/icons/small/text.gif b/docs/icons/small/text.gif
new file mode 100644
index 00000000000..66ceefbc8c4
Binary files /dev/null and b/docs/icons/small/text.gif differ
diff --git a/docs/icons/small/transfer.gif b/docs/icons/small/transfer.gif
new file mode 100644
index 00000000000..d460d3fffe6
Binary files /dev/null and b/docs/icons/small/transfer.gif differ
diff --git a/docs/icons/small/unknown.gif b/docs/icons/small/unknown.gif
new file mode 100644
index 00000000000..7bf0bbc10a6
Binary files /dev/null and b/docs/icons/small/unknown.gif differ
diff --git a/docs/icons/small/uu.gif b/docs/icons/small/uu.gif
new file mode 100644
index 00000000000..8c793f8a7f9
Binary files /dev/null and b/docs/icons/small/uu.gif differ
diff --git a/docs/icons/sound1.gif b/docs/icons/sound1.gif
new file mode 100644
index 00000000000..8efb49f55d6
Binary files /dev/null and b/docs/icons/sound1.gif differ
diff --git a/docs/icons/sound2.gif b/docs/icons/sound2.gif
new file mode 100644
index 00000000000..48e6a7fb2fa
Binary files /dev/null and b/docs/icons/sound2.gif differ
diff --git a/docs/icons/sphere1.gif b/docs/icons/sphere1.gif
new file mode 100644
index 00000000000..7067070da27
Binary files /dev/null and b/docs/icons/sphere1.gif differ
diff --git a/docs/icons/sphere2.gif b/docs/icons/sphere2.gif
new file mode 100644
index 00000000000..a9e462a377c
Binary files /dev/null and b/docs/icons/sphere2.gif differ
diff --git a/docs/icons/tar.gif b/docs/icons/tar.gif
new file mode 100644
index 00000000000..4032c1bd3d4
Binary files /dev/null and b/docs/icons/tar.gif differ
diff --git a/docs/icons/tex.gif b/docs/icons/tex.gif
new file mode 100644
index 00000000000..45e43233b84
Binary files /dev/null and b/docs/icons/tex.gif differ
diff --git a/docs/icons/text.gif b/docs/icons/text.gif
new file mode 100644
index 00000000000..4c623909fbf
Binary files /dev/null and b/docs/icons/text.gif differ
diff --git a/docs/icons/transfer.gif b/docs/icons/transfer.gif
new file mode 100644
index 00000000000..33697dbb667
Binary files /dev/null and b/docs/icons/transfer.gif differ
diff --git a/docs/icons/unknown.gif b/docs/icons/unknown.gif
new file mode 100644
index 00000000000..32b1ea23fb6
Binary files /dev/null and b/docs/icons/unknown.gif differ
diff --git a/docs/icons/up.gif b/docs/icons/up.gif
new file mode 100644
index 00000000000..6d6d6d1ebf8
Binary files /dev/null and b/docs/icons/up.gif differ
diff --git a/docs/icons/uu.gif b/docs/icons/uu.gif
new file mode 100644
index 00000000000..4387d529f69
Binary files /dev/null and b/docs/icons/uu.gif differ
diff --git a/docs/icons/uuencoded.gif b/docs/icons/uuencoded.gif
new file mode 100644
index 00000000000..4387d529f69
Binary files /dev/null and b/docs/icons/uuencoded.gif differ
diff --git a/docs/icons/world1.gif b/docs/icons/world1.gif
new file mode 100644
index 00000000000..05b4ec20588
Binary files /dev/null and b/docs/icons/world1.gif differ
diff --git a/docs/icons/world2.gif b/docs/icons/world2.gif
new file mode 100644
index 00000000000..e3203f7a881
Binary files /dev/null and b/docs/icons/world2.gif differ
diff --git a/docs/man/ab.8 b/docs/man/ab.8
new file mode 100644
index 00000000000..5a06f360557
--- /dev/null
+++ b/docs/man/ab.8
@@ -0,0 +1,210 @@
+.TH ab 1 "March 1998"
+.\" $Id: ab.8,v 1.1 1999/08/24 06:45:53 fielding Exp $
+.\" Copyright (c) 1998-1999 The Apache Group. All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in
+.\" the documentation and/or other materials provided with the
+.\" distribution.
+.\"
+.\" 3. All advertising materials mentioning features or use of this
+.\" software must display the following acknowledgment:
+.\" "This product includes software developed by the Apache Group
+.\" for use in the Apache HTTP server project (http://www.apache.org/)."
+.\"
+.\" 4. The names "Apache Server" and "Apache Group" must not be used to
+.\" endorse or promote products derived from this software without
+.\" prior written permission.
+.\"
+.\" 5. Products derived from this software may not be called "Apache"
+.\" nor may "Apache" appear in their names without prior written
+.\" permission of the Apache Group.
+.\"
+.\" 6. Redistributions of any form whatsoever must retain the following
+.\" acknowledgment:
+.\" "This product includes software developed by the Apache Group
+.\" for use in the Apache HTTP server project (http://www.apache.org/)."
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+.\" EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+.\" PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+.\" ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+.\" SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+.\" NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+.\" LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+.\" STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+.\" OF THE POSSIBILITY OF SUCH DAMAGE.
+.\" ====================================================================
+.\"
+.\" This software consists of voluntary contributions made by many
+.\" individuals on behalf of the Apache Group and was originally based
+.\" on public domain software written at the National Center for
+.\" Supercomputing Applications, University of Illinois, Urbana-Champaign.
+.\" For more information on the Apache Group and the Apache HTTP server
+.\" project, please see .
+.SH NAME
+ab \- Apache HTTP server benchmarking tool
+.SH SYNOPSIS
+.B ab
+[
+.B \-k
+] [
+.BI \-n " requests"
+] [
+.BI \-t " timelimit"
+] [
+.BI \-c " concurrency"
+] [
+.BI \-p " POST file"
+] [
+.BI \-A " Authenticate username:password"
+] [
+.BI \-P " Proxy Authenticate username:password"
+] [
+.BI \-H " Custom header"
+] [
+.BI \-C " Cookie name=value"
+] [
+.BI \-T " content-type"
+] [
+.BI \-v " verbosity"
+]
+] [
+.BI \-w " output HTML"
+]
+] [
+.BI \-x " attributes"
+]
+] [
+.BI \-y " attributes"
+]
+] [
+.BI \-z " attributes"
+]
+.I [http://]hostname[:port]/path
+
+.B ab
+[
+.B \-V
+] [
+.B \-h
+]
+.PP
+.SH DESCRIPTION
+.B ab
+is a tool for benchmarking your Apache HyperText Transfer Protocol (HTTP)
+server. It is designed to give you an impression on how performant is your
+current Apache installation. This especially shows you how much requests per
+time your Apache installation is capable to serve.
+.PP
+.SH OPTIONS
+.TP 12
+.B \-k
+Enable the HTTP KeepAlive feature, i.e. perform multiple requests within one
+HTTP session instead. Default is no KeepAlive.
+.TP 12
+.BI \-n " requests"
+Number of requests to perform for the benchmarking session. The default is to
+just perform one single request which usually leads to not very representative
+benchmarking results.
+.TP 12
+.BI \-t " timelimit"
+Seconds to max. spend for benchmarking. This implies
+a
+.B \-n
+.B 50000
+internally. Use this to benchmark the server within a fixed total amount of
+time. Per default there is no timelimit.
+.TP 12
+.BI \-c " concurrency"
+Number of multiple requests per time to perform.
+Default is one request per time.
+
+.TP 12
+.BI \-p " POST file"
+File containing data to POST.
+
+.TP 12
+.BI \-A " Authorization username:password"
+Supply BASIC Authentification credentials to the server. The username
+and password are separated by a single ':' and send on the wire uuencoded.
+The string is send regardless of wether the server needs it; (i.e. has
+send an 401. Authentifcation needed).
+
+.TP 12
+.BI \-p " Proxy-Authorization username:password"
+Supply BASIC Authentification credentials to a proxy en-route. The username
+and password are separated by a single ':' and send on the wire uuencoded.
+The string is send regardless of wether the proxy needs it; (i.e. has
+send an 407 Proxy authentifcation needed).
+
+.TP 12
+.BI \-C " Cookie name=value"
+Add a 'Cookie:' line to the request. The argument is typically in the form
+of a 'name=value' pair. This field is repeatable.
+
+.TP 12
+.BI \-p " Header string"
+Postfix extra headers to the request. The argument is typically in the form
+of a valid header line; containing a colon separated field value pair. (i.e.
+'Accept-Encoding: zip/zop;8bit').
+
+.TP 12
+.BI \-T " content-type"
+Content-type header to use for POST data.
+
+.TP 12
+.B \-v
+Set verbosity level - 4 and above prints information on headers, 3 and
+above prints response codes (404, 200, etc.), 2 and above prints
+warnings and info.
+
+.TP 12
+.BI \-w
+Print out results in HTML tables. Default table is two columns wide,
+with a white background.
+.TP 12
+.BI \-x " attributes"
+String to use as attributes for . Attributes are inserted
+
+.TP 12
+.BI \-y " attributes"
+String to use as attributes for .
+.TP 12
+.BI \-z " attributes"
+String to use as attributes for .
+.TP 12
+.B \-V
+Display version number and exit.
+.TP 12
+.B \-h
+Display usage information.
+.PD
+.SH BUGS
+There are various statically declared buffers of fixed length. Combined
+with the lazy parsing of the command line arguments, the response headers
+from the server and other external inputs this might bite you.
+.P
+It does not implement HTTP/1.x fully; only accepts some 'expected' forms
+of responses. The rather heavy use of
+.BR strstr(3)
+shows up top in profile,
+which might indicate a performance problem; i.e. you would measure the
+.BR ab
+performance rather than the server's.
+
+.SH SEE ALSO
+.BR httpd(8)
+.
diff --git a/docs/man/apachectl.8 b/docs/man/apachectl.8
new file mode 100644
index 00000000000..72300eb98b2
--- /dev/null
+++ b/docs/man/apachectl.8
@@ -0,0 +1,133 @@
+.TH apachectl 1 "September 1997"
+.\" Copyright (c) 1997-1999 The Apache Group. All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in
+.\" the documentation and/or other materials provided with the
+.\" distribution.
+.\"
+.\" 3. All advertising materials mentioning features or use of this
+.\" software must display the following acknowledgment:
+.\" "This product includes software developed by the Apache Group
+.\" for use in the Apache HTTP server project (http://www.apache.org/)."
+.\"
+.\" 4. The names "Apache Server" and "Apache Group" must not be used to
+.\" endorse or promote products derived from this software without
+.\" prior written permission.
+.\"
+.\" 5. Products derived from this software may not be called "Apache"
+.\" nor may "Apache" appear in their names without prior written
+.\" permission of the Apache Group.
+.\"
+.\" 6. Redistributions of any form whatsoever must retain the following
+.\" acknowledgment:
+.\" "This product includes software developed by the Apache Group
+.\" for use in the Apache HTTP server project (http://www.apache.org/)."
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+.\" EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+.\" PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+.\" ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+.\" SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+.\" NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+.\" LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+.\" STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+.\" OF THE POSSIBILITY OF SUCH DAMAGE.
+.\" ====================================================================
+.\"
+.\" This software consists of voluntary contributions made by many
+.\" individuals on behalf of the Apache Group and was originally based
+.\" on public domain software written at the National Center for
+.\" Supercomputing Applications, University of Illinois, Urbana-Champaign.
+.\" For more information on the Apache Group and the Apache HTTP server
+.\" project, please see .
+.SH NAME
+apachectl \- Apache HTTP server control interface
+.SH SYNOPSIS
+.B apachectl
+\fIcommand\fP [...]
+.SH DESCRIPTION
+.B apachectl
+is a front end to the Apache HyperText Transfer Protocol (HTTP)
+server. It is designed to help the administrator control the
+functioning of the Apache
+.B httpd
+daemon.
+.PP
+.B NOTE:
+If your Apache installation uses non-standard paths, you will need to
+edit the
+.B apachectl
+script to set the appropriate paths to your PID file and your
+.B httpd
+binary. See the comments in the script for details.
+.PP
+The
+.B apachectl
+script returns a 0 exit value on success, and >0 if an error
+occurs. For more details, view the comments in the script.
+.PP
+Full documentation for Apache is available at
+.B http://www.apache.org/
+.
+.SH OPTIONS
+The \fIcommand\fP can be any one or more of the following options:
+.TP 12
+.BI start
+Start the Apache daemon. Gives an error if it is already running.
+.TP
+.BI stop
+Stops the Apache daemon.
+.TP
+.BI restart
+Restarts the Apache daemon by sending it a SIGHUP. If the daemon
+is not running, it is started.
+This command automatically checks the configuration files via
+.BI configtest
+before initiating the restart to make sure Apache doesn't die.
+.TP
+.BI fullstatus
+Displays a full status report from
+.B mod_status.
+For this to work, you need to have mod_status enabled on your server
+and a text-based browser such as \fIlynx\fP available on your system. The
+URL used to access the status report can be set by editing the
+.B STATUSURL
+variable in the script.
+.TP
+.BI status
+Displays a brief status report. Similar to the fullstatus option,
+except that the list of requests currently being served is omitted.
+.TP
+.BI graceful
+Gracefully restarts the Apache daemon by sending it a SIGUSR1. If
+the daemon is not running, it is started. This differs from a
+normal restart in that currently open connections are not aborted.
+A side effect is that old log files will not be closed immediately.
+This means that if used in a log rotation script, a substantial delay may be
+necessary to ensure that the old log files are closed before processing them.
+This command automatically checks the configuration files via
+.BI configtest
+before initiating the restart to make sure Apache doesn't die.
+.TP
+.BI configtest
+Run a configuration file syntax test. It parses the configuration
+files and either reports
+.B "Syntax Ok"
+or detailed information about the particular syntax error.
+.TP
+.BI help
+Displays a short help message.
+.SH SEE ALSO
+.BR httpd(8)
+.
diff --git a/docs/man/apxs.8 b/docs/man/apxs.8
new file mode 100644
index 00000000000..464766c75fe
--- /dev/null
+++ b/docs/man/apxs.8
@@ -0,0 +1,459 @@
+.TH apxs 8 "April 1998"
+.\" Copyright (c) 1998-1999 The Apache Group. All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in
+.\" the documentation and/or other materials provided with the
+.\" distribution.
+.\"
+.\" 3. All advertising materials mentioning features or use of this
+.\" software must display the following acknowledgment:
+.\" "This product includes software developed by the Apache Group
+.\" for use in the Apache HTTP server project (http://www.apache.org/)."
+.\"
+.\" 4. The names "Apache Server" and "Apache Group" must not be used to
+.\" endorse or promote products derived from this software without
+.\" prior written permission.
+.\"
+.\" 5. Products derived from this software may not be called "Apache"
+.\" nor may "Apache" appear in their names without prior written
+.\" permission of the Apache Group.
+.\"
+.\" 6. Redistributions of any form whatsoever must retain the following
+.\" acknowledgment:
+.\" "This product includes software developed by the Apache Group
+.\" for use in the Apache HTTP server project (http://www.apache.org/)."
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+.\" EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+.\" PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+.\" ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+.\" SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+.\" NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+.\" LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+.\" STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+.\" OF THE POSSIBILITY OF SUCH DAMAGE.
+.\" ====================================================================
+.\"
+.\" This software consists of voluntary contributions made by many
+.\" individuals on behalf of the Apache Group and was originally based
+.\" on public domain software written at the National Center for
+.\" Supercomputing Applications, University of Illinois, Urbana-Champaign.
+.\" For more information on the Apache Group and the Apache HTTP server
+.\" project, please see .
+.SH NAME
+apxs \- APache eXtenSion tool
+.SH SYNOPSIS
+.B apxs
+.B \-g
+[
+.BI \-S " name=value
+]
+.BI \-n " modname"
+
+.B apxs
+.B \-q
+[
+.BI \-S " name=value
+]
+.IR query " ..."
+
+.B apxs
+.B \-c
+[
+.BI \-S " name=value
+]
+[
+.BI \-o " dsofile"
+]
+[
+.BI \-I " incdir"
+]
+[
+.BI \-D " name=value"
+]
+[
+.BI \-L " libdir"
+]
+[
+.BI \-l " libname"
+]
+[
+.BI \-Wc, "compiler-flags"
+]
+[
+.BI \-Wl, "linker-flags"
+]
+.IR files " ..."
+
+.B apxs
+.B \-i
+[
+.BI \-S " name=value
+]
+[
+.BI \-n " modname"
+]
+[
+.B \-a
+]
+[
+.B \-A
+]
+.IR dsofile " ..."
+
+.B apxs
+.B \-e
+[
+.BI \-S " name=value
+]
+[
+.BI \-n " modname"
+]
+[
+.B \-a
+]
+[
+.B \-A
+]
+.IR dsofile " ..."
+.PP
+.SH DESCRIPTION
+.B apxs
+is a tool for building and installing extension modules for the Apache
+HyperText Transfer Protocol (HTTP) server. This is achieved by building a
+dynamic shared object (DSO) from one or more source or object
+.I files
+which then can be loaded into
+the Apache server under runtime via the
+.B LoadModule
+directive from
+.BR mod_so.
+
+So to use this extension mechanism your platform has
+to support the DSO feature and your
+Apache
+.B httpd
+binary has to be built with the
+.B mod_so
+module.
+The
+.B apxs
+tool automatically complains if this is not the case.
+You can check this yourself by manually running the command
+
+.nf
+ $ httpd -l
+.fi
+
+The module
+.B mod_so
+should be part of the displayed list.
+If these requirements are fulfilled you can easily extend
+your Apache server's functionality by installing your own
+modules with the DSO mechanism by the help of this
+.B apxs
+tool:
+
+.nf
+ $ apxs -i -a -c mod_foo.c
+ gcc -fpic -DSHARED_MODULE -I/path/to/apache/include -c mod_foo.c
+ ld -Bshareable -o mod_foo.so mod_foo.o
+ cp mod_foo.so /path/to/apache/libexec/mod_foo.so
+ chmod 755 /path/to/apache/libexec/mod_foo.so
+ [activating module `foo' in /path/to/apache/etc/httpd.conf]
+ $ apachectl restart
+ /path/to/apache/sbin/apachectl restart: httpd not running, trying to start
+ [Tue Mar 31 11:27:55 1998] [debug] mod_so.c(303): loaded module foo_module
+ /path/to/apache/sbin/apachectl restart: httpd started
+ $ _
+.fi
+
+The arguments
+.I files
+can be any C source file (.c), a object file (.o) or
+even a library archive (.a). The
+.B apxs
+tool automatically recognizes these extensions and automtaically used the C
+source files for compilation while just using the object and archive files for
+the linking phase. But when using such pre-compiled objects make sure they are
+compiled for position independend code (PIC) to be able to use them for a
+dynamically loaded shared object.
+For instance with GCC you always just have to use
+.BR -fpic .
+For other
+C compilers consult its manual
+page or at watch for the flags
+.B apxs
+uses to compile the object files.
+
+For more details about DSO support in Apache read the documentation
+of
+.B mod_so
+or perhaps even read the
+.B src/modules/standard/mod_so.c
+source file.
+
+.PP
+.SH OPTIONS
+Common options:
+.TP 12
+.BI \-n " modname"
+This explicitly sets the module name for the
+.B \-i
+(install)
+and
+.B \-g
+(template generation) option. Use this to explicitly specify the module name.
+For option
+.B \-g
+this is required, for option
+.B \-i
+the
+.B apxs
+tool tries to determine the name from the source or (as a fallback) at least
+by guessing it from the filename.
+.PP
+Query options:
+.TP 12
+.B \-q
+Performs a query for
+.BR apxs 's
+knowledge about certain settings. The
+.I query
+parameters can be one or more of the following strings:
+.nf
+ CC TARGET
+ CFLAGS SBINDIR
+ CFLAGS_SHLIB INCLUDEDIR
+ LD_SHLIB LIBEXECDIR
+ LDFLAGS_SHLIB SYSCONFDIR
+ LIBS_SHLIB
+.fi
+Use this for manually determining settings. For instance use
+.nf
+ INC=-I`apxs -q INCLUDEDIR`
+.fi
+inside your own Makefiles if you need manual access
+to Apache's C header files.
+.PP
+Configuration options:
+.TP 12
+.BI \-S " name=value"
+This option changes the apxs settings described above.
+.PP
+Template Generation options:
+.TP 12
+.B \-g
+This generates a subdirectory
+.I name
+(see option
+.BR \-n ")"
+and there two files: A sample module source file named
+.BI mod_ name.c
+which can be used as a template for creating your own modules or
+as a quick start for playing with the APXS mechanism.
+And a corresponding
+.B Makefile
+for even easier build and installing of this module.
+.PP
+DSO compilation options:
+.TP 12
+.B \-c
+This indicates the compilation operation. It first compiles the C source
+files (.c) of
+.I files
+into corresponding object files (.o) and then builds a dynamically shared object in
+.I dsofile
+by linking these object files plus the remaining
+object files (.o and .a) of
+.I files
+If no
+.B \-o
+option is specified
+the output file is guessed from the first filename in
+.I files
+and thus usually defaults to
+.BI mod_ name.so
+.TP 12
+.BI \-o " dsofile"
+Explicitly specifies the filename of the created dynamically shared object. If
+not specified and the name cannot be guessed from the
+.I files
+list, the fallback name
+.B mod_unknown.so
+is used.
+.TP 12
+.BI \-D " name=value"
+This option is directly passed through to the compilation command(s).
+Use this to add your own defines to the build process.
+.TP 12
+.BI \-I " incdir"
+This option is directly passed through to the compilation command(s).
+Use this to add your own include directories to search to the build process.
+.TP 12
+.BI \-L " libdir"
+This option is directly passed through to the linker command.
+Use this to add your own library directories to search to the build process.
+.TP 12
+.BI \-l " libname"
+This option is directly passed through to the linker command.
+Use this to add your own libraries to search to the build process.
+.TP 12
+.BI \-Wc, "compiler-flags"
+This option passes
+.I compiler-flags
+as additional flags to the compiler command.
+Use this to add local compiler-specific options.
+.TP 12
+.BI \-Wl, "linker-flags"
+This option passes
+.I linker-flags
+as additional flags to the linker command.
+Use this to add local linker-specific options.
+.PP
+DSO installation and configuration options:
+.TP 12
+.B \-i
+This indicates the installation operation and installs one or more
+dynamically shared objects into the
+server's
+.I libexec
+directory.
+.TP 12
+.B \-a
+This activates the module by automatically adding a corresponding
+.B LoadModule
+line to Apache's
+.B httpd.conf
+configuration file, or by enabling it if it already exists.
+.TP 12
+.B \-A
+Same as option
+.B \-a
+but the created
+.B LoadModule
+directive is prefixed with a hash sign (#), i.e. the module is
+just prepared for later activation but initially disabled.
+.TP 12
+.B \-e
+This indicates the editing operation, which can be used with the
+.B \-a
+and
+.B \-A
+options similarly to the
+.B \-i
+operation to edit Apache's
+.B httpd.conf
+configuration file without attempting to install the module.
+.PD
+.SH EXAMPLES
+Assume you have an Apache module named mod_foo.c available which should extend
+Apache's server functionality. To accomplish this you first have to compile
+the C source into a shared object suitable for loading into the Apache server
+under runtime via the following command:
+
+.nf
+ $ apxs -c mod_foo.c
+ gcc -fpic -DSHARED_MODULE -I/path/to/apache/include -c mod_foo.c
+ ld -Bshareable -o mod_foo.so mod_foo.o
+ $ _
+.fi
+
+Then you have to update the Apache configuration by making sure a
+.B LoadModule
+directive is present to load this shared object. To simplify this
+step
+.B apxs
+provides an automatic way to install the shared object in its
+"libexec" directory and updating the
+.B httpd.conf
+file accordingly. This can be achieved by running:
+
+.nf
+ $ apxs -i -a mod_foo.c
+ cp mod_foo.so /path/to/apache/libexec/mod_foo.so
+ chmod 755 /path/to/apache/libexec/mod_foo.so
+ [activating module `foo' in /path/to/apache/etc/httpd.conf]
+ $ _
+.fi
+
+This way a line named
+
+.nf
+ LoadModule foo_module libexec/mod_foo.so
+.fi
+
+is added to the configuration file if still not present.
+If you want to have this this disabled per default use the
+.B \-A
+option, i.e.
+
+.nf
+ $ apxs -i -A mod_foo.c
+.fi
+
+For a quick test of the APXS mechanism you can create a sample Apache module
+template plus a corresponding Makefile via:
+
+.nf
+ $ apxs -g -n foo
+ Creating [DIR] foo
+ Creating [FILE] foo/Makefile
+ Creating [FILE] foo/mod_foo.c
+ $ _
+.fi
+
+Then you can immediately compile this sample module into a shared object and
+load it into the Apache server:
+
+.nf
+ $ cd foo
+ $ make all reload
+ apxs -c mod_foo.c
+ gcc -fpic -DSHARED_MODULE -I/path/to/apache/include -c mod_foo.c
+ ld -Bshareable -o mod_foo.so mod_foo.o
+ apxs -i -a -n "foo" mod_foo.so
+ cp mod_foo.so /path/to/apache/libexec/mod_foo.so
+ chmod 755 /path/to/apache/libexec/mod_foo.so
+ [activating module `foo' in /path/to/apache/etc/httpd.conf]
+ apachectl restart
+ /path/to/apache/sbin/apachectl restart: httpd not running, trying to start
+ [Tue Mar 31 11:27:55 1998] [debug] mod_so.c(303): loaded module foo_module
+ /path/to/apache/sbin/apachectl restart: httpd started
+ $ _
+.fi
+
+You can even use
+.B apxs
+to compile complex modules outside the Apache source tree, like PHP3:
+
+.nf
+ $ cd php3
+ $ ./configure --with-shared-apache=../apache-1.3
+ $ apxs -c -o libphp3.so mod_php3.c libmodphp3-so.a
+ gcc -fpic -DSHARED_MODULE -I/tmp/apache/include -c mod_php3.c
+ ld -Bshareable -o libphp3.so mod_php3.o libmodphp3-so.a
+ $ _
+.fi
+
+because
+.B apxs
+automatically recognized C source files and object files. Only C source files
+are compiled while remaining object files are used for the linking phase.
+
+.PD
+.SH SEE ALSO
+.BR apachectl(1),
+.BR httpd(8).
+.
diff --git a/docs/man/dbmmanage.1 b/docs/man/dbmmanage.1
new file mode 100644
index 00000000000..06380ff0f59
--- /dev/null
+++ b/docs/man/dbmmanage.1
@@ -0,0 +1,171 @@
+.TH dbmmanage 1 "March 1998"
+.\" Copyright (c) 1998-1999 The Apache Group. All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in
+.\" the documentation and/or other materials provided with the
+.\" distribution.
+.\"
+.\" 3. All advertising materials mentioning features or use of this
+.\" software must display the following acknowledgment:
+.\" "This product includes software developed by the Apache Group
+.\" for use in the Apache HTTP server project (http://www.apache.org/)."
+.\"
+.\" 4. The names "Apache Server" and "Apache Group" must not be used to
+.\" endorse or promote products derived from this software without
+.\" prior written permission.
+.\"
+.\" 5. Products derived from this software may not be called "Apache"
+.\" nor may "Apache" appear in their names without prior written
+.\" permission of the Apache Group.
+.\"
+.\" 6. Redistributions of any form whatsoever must retain the following
+.\" acknowledgment:
+.\" "This product includes software developed by the Apache Group
+.\" for use in the Apache HTTP server project (http://www.apache.org/)."
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+.\" EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+.\" PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+.\" ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+.\" SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+.\" NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+.\" LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+.\" STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+.\" OF THE POSSIBILITY OF SUCH DAMAGE.
+.\" ====================================================================
+.\"
+.\" This software consists of voluntary contributions made by many
+.\" individuals on behalf of the Apache Group and was originally based
+.\" on public domain software written at the National Center for
+.\" Supercomputing Applications, University of Illinois, Urbana-Champaign.
+.\" For more information on the Apache Group and the Apache HTTP server
+.\" project, please see .
+.SH NAME
+dbmmanage \- Create and update user authentication files in DBM format
+.SH SYNOPSIS
+.B dbmmanage
+.I filename
+[
+.I command
+] [
+.I username
+[
+.I encpasswd
+] ]
+.PP
+.SH DESCRIPTION
+.B dbmmanage
+is used to create and update the DBM format files used to store
+usernames and password for basic authentication of HTTP users.
+Resources available from the
+.B httpd
+Apache web server can be restricted to just the users listed
+in the files created by
+.B dbmmanage.
+This program can only be used
+when the usernames are stored in a DBM file. To use a
+flat-file database see
+\fBhtpasswd\fP.
+.PP
+This manual page only lists the command line arguments. For details of
+the directives necessary to configure user authentication in
+.B httpd
+see
+the Apache manual, which is part of the Apache distribution or can be
+found at http://www.apache.org/.
+.SH OPTIONS
+.IP \fB\fIfilename\fP
+The filename of the DBM format file. Usually without the
+extension .db, .pag, or .dir.
+.IP \fB\fIcommand\fP
+This selects the operation to perform:
+.TP 12
+.B add
+Adds an entry for \fIusername\fP to \fIfilename\fP using the encrypted
+password \fIencpassword\fP.
+.TP 12
+.B adduser
+Asks for a password and then adds an entry for \fIusername\fP to
+\fIfilename\fP .
+.TP 12
+.B check
+Asks for a password and then checks if
+\fIusername\fP is in \fIfilename\fP and if it's password matches
+the specified one.
+.TP 12
+.B delete
+Deletes the \fIusername\fP entry from \fIfilename\fP.
+.TP 12
+.B import
+Reads username:password entries (one per line) from STDIN and adds them to
+\fIfilename\fP. The passwords already has to be crypted.
+.TP 12
+.B update
+Same as the "adduser" command, except that it makes sure \fIusername\fP
+already exists in \fIfilename\fP.
+.TP 12
+.B view
+Just displays the complete contents of the DBM file.
+.IP \fB\fIusername\fP
+The user for which the update operation is performed.
+.PD
+.SH BUGS
+.PP
+One should be aware that there are a number of different DBM file
+formats in existance, and with all likelihood, libraries for more than
+one format may exist on your system. The three primary examples are
+NDBM, the GNU project's GDBM, and Berkeley DB 2. Unfortunately, all
+these libraries use different file formats, and you must make sure
+that the file format used by
+.I filename
+is the same format that
+.B dbmmanage
+expects to see.
+.B dbmmanage
+currently has no way of determining what type of DBM file it is
+looking at. If used against the wrong format,
+.dbmmanage
+will simply return nothing, or may create a different DBM file with a
+different name, or at worst, it may corrupt the DBM file if you were
+attempting to write to it.
+.PP
+.B dbmmanage
+has a list of DBM format preferences, defined by the
+.B @AnyDBM::ISA
+array near the beginning of the program. Since we prefer the Berkeley
+DB 2 file format, the order in which
+.B dbmmanage
+will look for system libraries is Berkeley DB 2, then NDBM, and then
+GDBM. The first library found will be the library
+.B dbmmanage
+will attempt to use for all DBM file transactions. This ordering is
+slightly different than the standard
+.B @AnyDBM::ISA
+ordering in perl, as well as the ordering used by the simple dbmopen()
+call in Perl, so if you use any other utilities to manage your DBM
+files, they must also follow this preference ordering. Similar care
+must be taken if using programs in other languages, like C, to
+access these files.
+.PP
+Apache's
+.B mod_auth_db.c
+module corresponds to Berkeley DB 2 library, while
+.B mod_auth_dbm.c
+corresponds to the NDBM library. Also, one can usually use the
+.B file
+program supplied with most Unix systems to see what format a DBM file is in.
+.PD
+.SH SEE ALSO
+.BR httpd(8)
+.
diff --git a/docs/man/htdigest.1 b/docs/man/htdigest.1
new file mode 100644
index 00000000000..c719e456ce9
--- /dev/null
+++ b/docs/man/htdigest.1
@@ -0,0 +1,97 @@
+.TH htdigest 1 "March 1998"
+.\" Copyright (c) 1997-1999 The Apache Group. All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in
+.\" the documentation and/or other materials provided with the
+.\" distribution.
+.\"
+.\" 3. All advertising materials mentioning features or use of this
+.\" software must display the following acknowledgment:
+.\" "This product includes software developed by the Apache Group
+.\" for use in the Apache HTTP server project (http://www.apache.org/)."
+.\"
+.\" 4. The names "Apache Server" and "Apache Group" must not be used to
+.\" endorse or promote products derived from this software without
+.\" prior written permission. For written permission, please contact
+.\" apache@apache.org.
+.\"
+.\" 5. Products derived from this software may not be called "Apache"
+.\" nor may "Apache" appear in their names without prior written
+.\" permission of the Apache Group.
+.\"
+.\" 6. Redistributions of any form whatsoever must retain the following
+.\" acknowledgment:
+.\" "This product includes software developed by the Apache Group
+.\" for use in the Apache HTTP server project (http://www.apache.org/)."
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+.\" EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+.\" PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+.\" ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+.\" SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+.\" NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+.\" LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+.\" STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+.\" OF THE POSSIBILITY OF SUCH DAMAGE.
+.\" ====================================================================
+.\"
+.\" This software consists of voluntary contributions made by many
+.\" individuals on behalf of the Apache Group and was originally based
+.\" on public domain software written at the National Center for
+.\" Supercomputing Applications, University of Illinois, Urbana-Champaign.
+.\" For more information on the Apache Group and the Apache HTTP server
+.\" project, please see .
+.SH NAME
+htdigest \- Create and update user authentication files
+.SH SYNOPSIS
+.B htdigest
+[
+.B \-c
+]
+.I passwdfile
+.I realm
+.I username
+.SH DESCRIPTION
+.B htdigest
+is used to create and update the flat-files used to store
+usernames, realm and password for digest authentication of HTTP users.
+Resources available from the
+.B httpd
+Apache web server can be restricted to just the users listed
+in the files created by
+.B htdigest.
+.PP
+This manual page only lists the command line arguments. For details of
+the directives necessary to configure digest authentication in
+.B httpd
+see
+the Apache manual, which is part of the Apache distribution or can be
+found at http://www.apache.org/.
+.SH OPTIONS
+.IP \-c
+Create the \fIpasswdfile\fP. If \fIpasswdfile\fP already exists, it
+is deleted first.
+.IP \fB\fIpasswdfile\fP
+Name of the file to contain the username, realm and password. If \-c
+is given, this file is created if it does not already exist,
+or deleted and recreated if it does exist.
+.IP \fB\fIrealm\fP
+The realm name to which the user name belongs to.
+.IP \fB\fIusername\fP
+The user name to create or update in \fBpasswdfile\fP. If
+\fIusername\fP does not exist is this file, an entry is added. If it
+does exist, the password is changed.
+.SH SEE ALSO
+.BR httpd(8)
+.
diff --git a/docs/man/htpasswd.1 b/docs/man/htpasswd.1
new file mode 100644
index 00000000000..1687cde41c2
--- /dev/null
+++ b/docs/man/htpasswd.1
@@ -0,0 +1,213 @@
+.TH htpasswd 1 "February 1997"
+.\" Copyright (c) 1997-1999 The Apache Group. All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in
+.\" the documentation and/or other materials provided with the
+.\" distribution.
+.\"
+.\" 3. All advertising materials mentioning features or use of this
+.\" software must display the following acknowledgment:
+.\" "This product includes software developed by the Apache Group
+.\" for use in the Apache HTTP server project (http://www.apache.org/)."
+.\"
+.\" 4. The names "Apache Server" and "Apache Group" must not be used to
+.\" endorse or promote products derived from this software without
+.\" prior written permission. For written permission, please contact
+.\" apache@apache.org.
+.\"
+.\" 5. Products derived from this software may not be called "Apache"
+.\" nor may "Apache" appear in their names without prior written
+.\" permission of the Apache Group.
+.\"
+.\" 6. Redistributions of any form whatsoever must retain the following
+.\" acknowledgment:
+.\" "This product includes software developed by the Apache Group
+.\" for use in the Apache HTTP server project (http://www.apache.org/)."
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+.\" EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+.\" PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+.\" ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+.\" SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+.\" NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+.\" LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+.\" STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+.\" OF THE POSSIBILITY OF SUCH DAMAGE.
+.\" ====================================================================
+.\"
+.\" This software consists of voluntary contributions made by many
+.\" individuals on behalf of the Apache Group and was originally based
+.\" on public domain software written at the National Center for
+.\" Supercomputing Applications, University of Illinois, Urbana-Champaign.
+.\" For more information on the Apache Group and the Apache HTTP server
+.\" project, please see .
+.SH NAME
+htpasswd \- Create and update user authentication files
+.SH SYNOPSIS
+.B htpasswd
+[
+.B \-c
+]
+[
+.B \-m
+]
+.I passwdfile
+.I username
+.br
+.B htpasswd
+.B \-b
+[
+.B \-c
+]
+[
+.B \-m
+.B \-d
+.B \-p
+.B \-s
+]
+.I passwdfile
+.I username
+.I password
+.SH DESCRIPTION
+.B htpasswd
+is used to create and update the flat-files used to store
+usernames and password for basic authentication of HTTP users.
+If
+.B htpasswd
+cannot access a file, such as not being able to write to the output
+file or not being able to read the file in order to update it,
+it returns an error status and makes no changes.
+.PP
+Resources available from the
+.B httpd
+Apache web server can be restricted to just the users listed
+in the files created by
+.B htpasswd.
+This program can only be used
+when the usernames are stored in a flat-file. To use a
+DBM database see
+\fBdbmmanage\fP.
+.PP
+.B htpasswd
+encrypts passwords using either a version of MD5 modified for Apache,
+or the system's \fIcrypt()\fP routine. Files managed by
+.B htpasswd
+may contain both types of passwords; some user records may have
+MD5-encrypted passwords while others in the same file may have passwords
+encrypted with \fIcrypt()\fP.
+.PP
+This manual page only lists the command line arguments. For details of
+the directives necessary to configure user authentication in
+.B httpd
+see
+the Apache manual, which is part of the Apache distribution or can be
+found at .
+.SH OPTIONS
+.IP \-b
+Use batch mode; \fIi.e.\fP, get the password from the command line
+rather than prompting for it. \fBThis option should be used with
+extreme care, since the password is clearly visible on the command
+line.\fP
+.IP \-c
+Create the \fIpasswdfile\fP. If \fIpasswdfile\fP already exists, it
+is rewritten and truncated.
+.IP \-m
+Use MD5 encryption for passwords. On Windows and TPF, this is the default.
+.IP \-d
+Use crypt() encryption for passwords. The default on all platforms but
+Windows and TPF. Though possibly supported by
+.B htpasswd
+onm all platforms, it is not supported by the
+.B httpd
+server on Windows and TPF.
+.IP \-s
+Use SHA encryption for passwords. Faciliates migration from/to Netscape
+servers using the LDAP Directory Interchange Format (ldif).
+.IP \-p
+Use plaintext passwords. Though
+.B htpasswd
+will support creation on all platofrms, the
+.B httpd
+deamon will only accept plain text passwords on Windows and TPF.
+.IP \fB\fIpasswdfile\fP
+Name of the file to contain the user name and password. If \-c
+is given, this file is created if it does not already exist,
+or rewritten and truncated if it does exist.
+.IP \fB\fIusername\fP
+The username to create or update in \fBpasswdfile\fP. If
+\fIusername\fP does not exist in this file, an entry is added. If it
+does exist, the password is changed.
+.IP \fB\fIpassword\fP
+The plaintext password to be encrypted and stored in the file. Only used
+with the \fI-b\fP flag.
+.SH EXIT STATUS
+.B htpasswd
+returns a zero status ("true") if the username and password have
+been successfully added or updated in the \fIpasswdfile\fP.
+.B htpasswd
+returns 1 if it encounters some problem accessing files, 2 if there
+was a syntax problem with the command line, 3 if the password was
+entered interactively and the verification entry didn't match, 4 if
+its operation was interrupted, 5 if a value is too long (username,
+filename, password, or final computed record), and 6 if the username
+contains illegal characters (see the \fBRESTRICTIONS\fP section).
+.SH EXAMPLES
+\fBhtpasswd /usr/local/etc/apache/.htpasswd-users jsmith\fP
+.IP
+Adds or modifies the password for user \fIjsmith\fP.
+The user is prompted for the password. If executed
+on a Windows system, the password will be encrypted using the
+modified Apache MD5 algorithm; otherwise, the system's
+\fIcrypt()\fP routine will be used. If the file does not
+exist,
+.B htpasswd
+will do nothing except return an error.
+.LP
+\fBhtpasswd -c /home/doe/public_html/.htpasswd jane\fP
+.IP
+Creates a new file and stores a record in it for user \fIjane\fP.
+The user is prompted for the password.
+If the file exists and cannot be read, or cannot be written,
+it is not altered and
+.B htpasswd
+will display a message and return an error status.
+.LP
+\fBhtpasswd -mb /usr/web/.htpasswd-all jones Pwd4Steve\fP
+.IP
+Encrypts the password from the command line (\fIPwd4Steve\fP) using
+the MD5 algorithm, and stores it in the specified file.
+.LP
+.SH SECURITY CONSIDERATIONS
+Web password files such as those managed by
+.B htpasswd
+should \fBnot\fP be within the Web server's URI space -- that is,
+they should not be fetchable with a browser.
+.PP
+The use of the \fI-b\fP option is discouraged, since when it is
+used the unencrypted password appears on the command line.
+.SH RESTRICTIONS
+On the Windows and MPE platforms, passwords encrypted with
+.B htpasswd
+are limited to no more than 255 characters in length. Longer
+passwords will be truncated to 255 characters.
+.PP
+The MD5 algorithm used by
+.B htpasswd
+is specific to the Apache software; passwords encrypted using it will not be
+usable with other Web servers.
+.PP
+Usernames are limited to 255 bytes and may not include the character ':'.
+.SH SEE ALSO
+.BR httpd(8)
+and the scripts in support/SHA1 which come with the distribution.
diff --git a/docs/man/httpd.8 b/docs/man/httpd.8
new file mode 100644
index 00000000000..ae320bad2ad
--- /dev/null
+++ b/docs/man/httpd.8
@@ -0,0 +1,211 @@
+.TH httpd 8 "February 1997"
+.\" Copyright (c) 1995-1997 David Robinson. All rights reserved.
+.\" Copyright (c) 1997-1999 The Apache Group. All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in
+.\" the documentation and/or other materials provided with the
+.\" distribution.
+.\"
+.\" 3. All advertising materials mentioning features or use of this
+.\" software must display the following acknowledgment:
+.\" "This product includes software developed by the Apache Group
+.\" for use in the Apache HTTP server project (http://www.apache.org/)."
+.\"
+.\" 4. The names "Apache Server" and "Apache Group" must not be used to
+.\" endorse or promote products derived from this software without
+.\" prior written permission. For written permission, please contact
+.\" apache@apache.org.
+.\"
+.\" 5. Products derived from this software may not be called "Apache"
+.\" nor may "Apache" appear in their names without prior written
+.\" permission of the Apache Group.
+.\"
+.\" 6. Redistributions of any form whatsoever must retain the following
+.\" acknowledgment:
+.\" "This product includes software developed by the Apache Group
+.\" for use in the Apache HTTP server project (http://www.apache.org/)."
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+.\" EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+.\" PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+.\" ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+.\" SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+.\" NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+.\" LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+.\" STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+.\" OF THE POSSIBILITY OF SUCH DAMAGE.
+.\" ====================================================================
+.\"
+.\" This software consists of voluntary contributions made by many
+.\" individuals on behalf of the Apache Group and was originally based
+.\" on public domain software written at the National Center for
+.\" Supercomputing Applications, University of Illinois, Urbana-Champaign.
+.\" For more information on the Apache Group and the Apache HTTP server
+.\" project, please see .
+.SH NAME
+httpd \- Apache hypertext transfer protocol server
+.SH SYNOPSIS
+.B httpd
+[
+.B \-X
+] [
+.BI \-R " libexecdir"
+] [
+.BI \-d " serverroot"
+] [
+.BI \-f " config"
+] [
+.BI \-C " directive"
+] [
+.BI \-c " directive"
+] [
+.BI \-D " parameter"
+]
+
+.B httpd
+[
+.B \-h
+]
+[
+.B \-l
+]
+[
+.B \-L
+]
+[
+.B \-v
+]
+[
+.B \-V
+]
+[
+.B \-S
+]
+[
+.B \-t
+]
+[
+.B \-T
+]
+
+.SH DESCRIPTION
+.B httpd
+is the Apache HyperText Transfer Protocol (HTTP) server program. It is
+designed to be run as a standalone daemon process. When used like this
+it will create a pool of child processes to handle requests. To stop
+it, send a TERM signal to the initial (parent) process. The PID of
+this process is written to a file as given in the configuration file.
+Alternatively
+.B httpd
+may be invoked by the Internet daemon inetd(8) each
+time a connection to the HTTP service is made.
+.PP
+This manual page only lists the command line arguments. For details
+of the directives necessary to configure
+.B httpd
+see the Apache manual,
+which is part of the Apache distribution or can be found at
+http://www.apache.org/. Paths in this manual may not reflect those
+compiled into
+.B httpd.
+.SH OPTIONS
+.TP 12
+.BI \-R " libexecdir"
+This option is only available if Apache was built with
+the
+.I SHARED_CORE
+rule enabled which forces the Apache core code to be
+placed into a dynamic shared object (DSO) file. This file
+is searched in a hardcoded path under ServerRoot per default. Use this
+option if you want to override it.
+.TP 12
+.BI \-d " serverroot"
+Set the initial value for the ServerRoot directive to \fIserverroot\fP. This
+can be overridden by the ServerRoot command in the configuration file. The
+default is \fB/usr/local/apache\fP.
+.TP
+.BI \-f " config"
+Execute the commands in the file \fIconfig\fP on startup. If \fIconfig\fP
+does not begin with a /, then it is taken to be a path relative to
+the ServerRoot. The default is \fBconf/httpd.conf\fP.
+.TP
+.BI \-C " directive"
+Process the configuration \fIdirective\fP before reading config files.
+.TP
+.BI \-c " directive"
+Process the configuration \fIdirective\fP after reading config files.
+.TP
+.BI \-D " parameter"
+Sets a configuration \fIparameter\fP which can be used with
+... sections in the configuration files
+to conditionally skip or process commands.
+.TP
+.B \-h
+Output a short summary of available command line options.
+.TP
+.B \-l
+Output a list of modules compiled into the server.
+.TP
+.B \-L
+Output a list of directives together with expected arguments and
+places where the directive is valid.
+.TP
+.B \-S
+Show the settings as parsed from the config file (currently only shows the
+virtualhost settings).
+.TP
+.B \-t
+Run syntax tests for configuration files only. The program immediately exits
+after these syntax parsing with either a return code of 0 (Syntax OK) or
+return code not equal to 0 (Syntax Error).
+.TP
+.B \-T
+Same as option
+.B \-t
+but does not check the configured document roots.
+.TP
+.B \-X
+Run in single-process mode, for internal debugging purposes only; the daemon
+does not detach from the terminal or fork any children. Do NOT use this mode
+to provide ordinary web service.
+.TP
+.B \-v
+Print the version of
+.B httpd
+, and then exit.
+.TP
+.B \-V
+Print the version and build parameters of
+.B httpd
+, and then exit.
+.SH FILES
+.PD 0
+.B /usr/local/apache/conf/httpd.conf
+.br
+.B /usr/local/apache/conf/srm.conf
+.br
+.B /usr/local/apache/conf/access.conf
+.br
+.B /usr/local/apache/conf/mime.types
+.br
+.B /usr/local/apache/conf/magic
+.br
+.B /usr/local/apache/logs/error_log
+.br
+.B /usr/local/apache/logs/access_log
+.br
+.B /usr/local/apache/logs/httpd.pid
+.PD
+.SH SEE ALSO
+.BR inetd (8).
diff --git a/docs/man/logresolve.8 b/docs/man/logresolve.8
new file mode 100644
index 00000000000..4851269ad61
--- /dev/null
+++ b/docs/man/logresolve.8
@@ -0,0 +1,87 @@
+.TH logresolve 8 "March 1998"
+.\" Copyright (c) 1998-1999 The Apache Group. All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in
+.\" the documentation and/or other materials provided with the
+.\" distribution.
+.\"
+.\" 3. All advertising materials mentioning features or use of this
+.\" software must display the following acknowledgment:
+.\" "This product includes software developed by the Apache Group
+.\" for use in the Apache HTTP server project (http://www.apache.org/)."
+.\"
+.\" 4. The names "Apache Server" and "Apache Group" must not be used to
+.\" endorse or promote products derived from this software without
+.\" prior written permission.
+.\"
+.\" 5. Products derived from this software may not be called "Apache"
+.\" nor may "Apache" appear in their names without prior written
+.\" permission of the Apache Group.
+.\"
+.\" 6. Redistributions of any form whatsoever must retain the following
+.\" acknowledgment:
+.\" "This product includes software developed by the Apache Group
+.\" for use in the Apache HTTP server project (http://www.apache.org/)."
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+.\" EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+.\" PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+.\" ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+.\" SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+.\" NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+.\" LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+.\" STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+.\" OF THE POSSIBILITY OF SUCH DAMAGE.
+.\" ====================================================================
+.\"
+.\" This software consists of voluntary contributions made by many
+.\" individuals on behalf of the Apache Group and was originally based
+.\" on public domain software written at the National Center for
+.\" Supercomputing Applications, University of Illinois, Urbana-Champaign.
+.\" For more information on the Apache Group and the Apache HTTP server
+.\" project, please see .
+.SH NAME
+logresolve \- resolve hostnames for IP-adresses in Apache logfiles
+.SH SYNOPSIS
+.B logresolve
+[
+.BI \-s " filename"
+] [
+.B \-c
+] <
+.I access_log
+>
+.I access_log.new
+.PP
+.SH DESCRIPTION
+.B logresolve
+is a post-processing program to resolve IP-adresses in Apache's access
+logfiles. To minimize impact on your nameserver, logresolve has its very own
+internal hash-table cache. This means that each IP number will only be looked
+up the first time it is found in the log file.
+.SH OPTIONS
+.TP 12
+.BI \-s " filename"
+Specifies a filename to record statistics.
+.TP 12
+.B \-c
+This causes
+.B logresolve
+to apply some DNS checks: after finding the hostname from the IP address, it
+looks up the IP addresses for the hostname and checks that one of these
+matches the original address.
+.PD
+.SH SEE ALSO
+.BR httpd(8)
+.
diff --git a/docs/man/rotatelogs.8 b/docs/man/rotatelogs.8
new file mode 100644
index 00000000000..aee02e11ecd
--- /dev/null
+++ b/docs/man/rotatelogs.8
@@ -0,0 +1,83 @@
+.TH rotatelogs 8 "March 1998"
+.\" Copyright (c) 1998-1999 The Apache Group. All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in
+.\" the documentation and/or other materials provided with the
+.\" distribution.
+.\"
+.\" 3. All advertising materials mentioning features or use of this
+.\" software must display the following acknowledgment:
+.\" "This product includes software developed by the Apache Group
+.\" for use in the Apache HTTP server project (http://www.apache.org/)."
+.\"
+.\" 4. The names "Apache Server" and "Apache Group" must not be used to
+.\" endorse or promote products derived from this software without
+.\" prior written permission.
+.\"
+.\" 5. Products derived from this software may not be called "Apache"
+.\" nor may "Apache" appear in their names without prior written
+.\" permission of the Apache Group.
+.\"
+.\" 6. Redistributions of any form whatsoever must retain the following
+.\" acknowledgment:
+.\" "This product includes software developed by the Apache Group
+.\" for use in the Apache HTTP server project (http://www.apache.org/)."
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+.\" EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+.\" PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+.\" ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+.\" SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+.\" NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+.\" LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+.\" STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+.\" OF THE POSSIBILITY OF SUCH DAMAGE.
+.\" ====================================================================
+.\"
+.\" This software consists of voluntary contributions made by many
+.\" individuals on behalf of the Apache Group and was originally based
+.\" on public domain software written at the National Center for
+.\" Supercomputing Applications, University of Illinois, Urbana-Champaign.
+.\" For more information on the Apache Group and the Apache HTTP server
+.\" project, please see .
+.SH NAME
+rotatelogs \- rotate Apache logs without having to kill the server
+.SH SYNOPSIS
+.B rotatelogs
+.I logfile
+.I rotationtime
+.PP
+.SH DESCRIPTION
+.B rotatelogs
+is a simple program for use in conjunction with Apache's piped logfile
+feature which can be used like this:
+
+.fi
+ TransferLog "|rotatelogs /path/to/logs/access_log 86400"
+.mf
+
+This creates the files /path/to/logs/access_log.nnnn where nnnn is the system
+time at which the log nominally starts (this time will always be a multiple of
+the rotation time, so you can synchronize cron scripts with it). At the end
+of each rotation time (here after 24 hours) a new log is started.
+.SH OPTIONS
+.IP \fB\fIlogfile\fP
+The path plus basename of the logfile. The suffix .nnnn is automatically
+added.
+.IP \fB\fIrotationtime\fP
+The rotation time in seconds.
+.PD
+.SH SEE ALSO
+.BR httpd(8)
+.
diff --git a/docs/man/suexec.8 b/docs/man/suexec.8
new file mode 100644
index 00000000000..801d7abce91
--- /dev/null
+++ b/docs/man/suexec.8
@@ -0,0 +1,70 @@
+.TH suexec 8 "March 1998"
+.\" Copyright (c) 1998-1999 The Apache Group. All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in
+.\" the documentation and/or other materials provided with the
+.\" distribution.
+.\"
+.\" 3. All advertising materials mentioning features or use of this
+.\" software must display the following acknowledgment:
+.\" "This product includes software developed by the Apache Group
+.\" for use in the Apache HTTP server project (http://www.apache.org/)."
+.\"
+.\" 4. The names "Apache Server" and "Apache Group" must not be used to
+.\" endorse or promote products derived from this software without
+.\" prior written permission.
+.\"
+.\" 5. Products derived from this software may not be called "Apache"
+.\" nor may "Apache" appear in their names without prior written
+.\" permission of the Apache Group.
+.\"
+.\" 6. Redistributions of any form whatsoever must retain the following
+.\" acknowledgment:
+.\" "This product includes software developed by the Apache Group
+.\" for use in the Apache HTTP server project (http://www.apache.org/)."
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+.\" EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+.\" PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+.\" ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+.\" SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+.\" NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+.\" LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+.\" STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+.\" OF THE POSSIBILITY OF SUCH DAMAGE.
+.\" ====================================================================
+.\"
+.\" This software consists of voluntary contributions made by many
+.\" individuals on behalf of the Apache Group and was originally based
+.\" on public domain software written at the National Center for
+.\" Supercomputing Applications, University of Illinois, Urbana-Champaign.
+.\" For more information on the Apache Group and the Apache HTTP server
+.\" project, please see .
+.SH NAME
+suexec \- Switch User For Exec
+.SH SYNOPSIS
+No synopsis for usage, because this program
+is used internally by Apache only.
+.PP
+.SH DESCRIPTION
+.B suexec
+is the "wrapper" support program for the suEXEC behaviour for Apache.
+It is run from within Apache automatically to switch the user when
+an external program has to be run under a different user. For more
+information about suEXEC see the document `Apache suEXEC Support'
+under http://www.apache.org/docs/suexec.html .
+.PD
+.SH SEE ALSO
+.BR httpd(8)
+.
diff --git a/docs/manual/developer/hooks.html b/docs/manual/developer/hooks.html
new file mode 100644
index 00000000000..39f4e8bad17
--- /dev/null
+++ b/docs/manual/developer/hooks.html
@@ -0,0 +1,202 @@
+
+
+
+Apache 2.0 Hook Functions
+
+
+
+
+
+Apache Hook Functions
+
+In general, a hook function is one that Apache will call at some
+point during the processing of a request. Modules can provide
+functions that are called, and specify when they get called in
+comparison to other modules.
+
+Creating a hook function
+
+In order to create a new hook, four things need to be done:
+
+Declare the hook function
+
+Use the DECLARE_HOOK macro, which needs to be given the name of the
+hook, the return type of the hook function and the arguments. For
+example, if the hook returns an int and takes a
+request_rec * and an int and is called
+"do_something", then declare it like this:
+
+DECLARE_HOOK(int,do_something,(request_rec *r,int n))
+
+This should go in a header which modules will include if they want
+to use the hook.
+
+Create the hook structure
+
+Each source file that exports a hook has a private structure which
+is used to record the module functions that use the hook. This is
+declared as follows:
+
+
+HOOK_STRUCT(
+ HOOK_LINK(do_something)
+ ...
+ )
+
+
+Implement the hook caller
+
+The source file that exports the hook has to implement a function
+that will call the hook. There are currently three possible ways to do
+this. In all cases, the calling function is called
+ap_run_hookname().
+
+Void hooks
+
+If the return value of a hook is void, then all the hooks are
+called, and the caller is implemented like this:
+
+IMPLEMENT_HOOK_VOID(do_something,(request_rec *r,int
+n),(r,n))
+
+The second and third arguments are the dummy argument declaration and
+the dummy arguments as they will be used when calling the hook. In
+other words, this macro expands to something like this:
+
+
+void ap_run_do_something(request_rec *r,int n)
+{
+ ...
+ do_something(r,n);
+}
+
+
+Hooks that return a value
+
+If the hook returns a value, then it can either be run until the first
+hook that does something interesting, like so:
+
+IMPLEMENT_HOOK_RUN_FIRST(int,do_something,(request_rec *r,int n),(r,n),DECLINED)
+
+The first hook that doesn't return DECLINED stops
+the loop and its return value is returned from the hook caller. Note
+that DECLINED is the tradition Apache hook return meaning "I
+didn't do anything", but it can be whatever suits you.
+
+Alternatively, all hooks can be run until an error occurs. This
+boils down to permitting two return values, one of which means
+"I did something, and it was OK" and the other meaning "I did
+nothing". The first function that returns a value other than one of
+those two stops the loop, and its return is the return value. Declare
+these like so:
+
+IMPLEMENT_HOOK_RUN_ALL(int,do_something,(request_rec *r,int
+n),(r,n),OK,DECLINED)
+
+Again, OK and DECLINED are the traditional
+values. You can use what you want.
+
+Call the hook callers
+
+At appropriate moments in the code, call the hook caller, like
+so:
+
+
+ int n,ret;
+ request_rec *r;
+
+ ret=ap_run_do_something(r,n);
+
+
+Hooking the hook
+
+A module that wants a hook to be called needs to do two
+things.
+
+Implement the hook function
+
+Include the appropriate header, and define a static function of the
+correct type:
+
+
+static int my_something_doer(request_rec *r,int n)
+{
+ ...
+ return OK;
+}
+
+
+Add a hook registering function
+
+During initialisation, Apache will call each modules hook
+registering function, which is included in the module structure:
+
+
+static void my_register_hooks()
+{
+ ap_hook_do_something(my_something_doer,NULL,NULL,HOOK_MIDDLE);
+}
+
+mode MODULE_VAR_EXPORT my_module =
+{
+ ...
+ my_register_hooks /* register hooks */
+};
+
+
+Controlling hook calling order
+
+In the example above, we didn't use the three arguments in the hook
+registration function that control calling order. There are two
+mechanisms for doing this. The first, rather crude, method, allows us
+to specify roughly where the hook is run relative to other
+modules. The final argument control this. There are three possible
+values:
+
+
+HOOK_FIRST
+HOOK_MIDDLE
+HOOK_LAST
+
+
+All modules using any particular value may be run in any order
+relative to each other, but, of course, all modules using
+HOOK_FIRST will be run before HOOK_MIDDLE which are
+before HOOK_LAST. Modules that don't care when they are run
+should use HOOK_MIDDLE. (I spaced these out so people
+could do stuff like HOOK_FIRST-2 to get in slightly earlier,
+but is this wise? - Ben)
+
+Note that there are two more values, HOOK_REALLY_FIRST and
+HOOK_REALLY_LAST. These should only be used by the hook
+exporter.
+
+The other method allows finer control. When a module knows that it
+must be run before (or after) some other modules, it can specify them
+by name. The second (third) argument is a NULL-terminated array of
+strings consisting of the names of modules that must be run before
+(after) the current module. For example, suppose we want "mod_xyz.c"
+and "mod_abc.c" to run before we do, then we'd hook as follows:
+
+
+static void register_hooks()
+{
+ static const char * const aszPre[]={ "mod_xyz.c", "mod_abc.c", NULL };
+
+ ap_hook_do_something(my_something_doer,aszPre,NULL,HOOK_MIDDLE);
+}
+
+
+Note that the sort used to achieve this is stable, so ordering set
+by HOOK_ORDER is preserved, as far as is
+possible.
+
+Ben Laurie, 15th August 1999
+
+
diff --git a/docs/manual/developer/index.html b/docs/manual/developer/index.html
new file mode 100644
index 00000000000..a72dd44b212
--- /dev/null
+++ b/docs/manual/developer/index.html
@@ -0,0 +1,19 @@
+
+
+
+Apache-2.0 Developer Documentation
+
+
+
+Developer Documentation for Apache-2.0
+Apache Hook Functions
+Converting Apache 1.3 Modules to Apache 2.0
+MPM listing
+
+
diff --git a/docs/manual/developer/modules.html b/docs/manual/developer/modules.html
new file mode 100644
index 00000000000..b066223466f
--- /dev/null
+++ b/docs/manual/developer/modules.html
@@ -0,0 +1,200 @@
+
+
+
+Converting Modules from Apache 1.3 to Apache 2.0
+
+
+
+
+
+From Apache 1.3 to Apache 2.0 Modules
+
+
+This is a first attempt at writing the lessons I learned when trying to convert the mod_mmap_static module to Apache 2.0. It's by no means definitive and probably won't even be correct in some ways, but it's a start.
+
+
+The easier changes...
+
+
+Cleanup Routines
+
+These now need to be of type ap_status_t and return a value of that type. Normally the return value will be APR_SUCCESS unless there is some need to signal an error in the cleanup. Be aware that even though you signal an error not all code yet checks and acts upon the error.
+
+
+Initialisation Routines
+
+
+These should now be renamed to better signify where they sit in the overall process. So the name gets a small change from mmap_init to mmap_post_config. The arguments passed have undergone a radical change and now look like
+
+
+- ap_context_t *p,
+- ap_context_t *plog,
+- ap_context_t *ptemp,
+- server_rec *s
+
+
+Throughout Apache the old pools have been replced by the ap_context_t, though their use remains remarkably similar.
+
+
+Data Types
+
+A lot of the data types have been moved into the APR. This means that some have had a name change, such as the one shown above. The following is a brief list of some of the changes that you are likely to have to make.
+
+- pool becomes ap_context_t
+- table becomes ap_table_t
+
+
+
+
+The messier changes...
+
+Register Hooks
+
+The new architecture uses a series of hooks to provide for calling your functions. These you'll need to add to your module by way of a new function, static void register_hooks(void). The function is really reasonably straightforward once you understand what needs to be done. Each function that needs calling at some stage in the processing of a request needs to be registered, handlers do not. There are a number of phases where functions can be added, and for each you can specify with a high degree of control the relative order that the function will be called in.
+
+
+This is the code that was added to mod_mmap_static
+
+
+static void register_hooks(void)
+{
+ static const char * const aszPre[]={ "http_core.c",NULL };
+ ap_hook_post_config(mmap_post_config,NULL,NULL,HOOK_MIDDLE);
+ ap_hook_translate_name(mmap_static_xlat,aszPre,NULL,HOOK_LAST);
+};
+
+
+This registers 2 functions that need to be called, one in the post_config stage (virtually every module will need this one) and one for the translate_name phase. note that while there are different function names the format of each is identical. So what is the format?
+
+
+ap_hook_[phase_name](function_name, predecessors, successors, position);
+
+
+There are 3 hook positions defined...
+
+
+- HOOK_FIRST
+- HOOK_MIDDLE
+- HOOK_LAST
+
+
+To define the position you use the position and then modify it with the predecessors and successors. each of the modifiers can be a list of functions that should be called, either before the function is run (predecessors) or after the function has run (successors).
+
+
+In the mod_mmap_static case I didn't care about the post_config stage, but the mmap_static_xlat MUST be called after the core module had done it's name translation, hence the use of the aszPre to define a modifier to the position HOOK_LAST.
+
+Module Definition
+
+
+There are now a lot fewer stages to worry about when creating your module definition. The old defintion looked like
+
+
+module MODULE_VAR_EXPORT [module_name]_module =
+{
+ STANDARD_MODULE_STUFF,
+ /* initializer */
+ /* dir config creater */
+ /* dir merger --- default is to override */
+ /* server config */
+ /* merge server config */
+ /* command handlers */
+ /* handlers */
+ /* filename translation */
+ /* check_user_id */
+ /* check auth */
+ /* check access */
+ /* type_checker */
+ /* fixups */
+ /* logger */
+ /* header parser */
+ /* child_init */
+ /* child_exit */
+ /* post read-request */
+};
+
+
+The new structure is a great deal simpler...
+
+
+module MODULE_VAR_EXPORT [module_name]_module =
+{
+ STANDARD20_MODULE_STUFF,
+ /* create per-directory config structures */
+ /* merge per-directory config structures */
+ /* create per-server config structures */
+ /* merge per-server config structures */
+ /* command handlers */
+ /* handlers */
+ /* register hooks */
+ };
+
+
+Some of these read directly across, some don't. I'll try to summarise what should be done below.
+
+
+The stages that read directly across :
+
+
+-
+/* dir config creater */ ==> /* create per-directory config structures */
+
+-
+/* server config */ ==> /* create per-server config structures */
+
+-
+/* dir merger */ ==> /* merge per-directory config structures */
+
+-
+/* merge server config */ ==> /* merge per-server config structures */
+
+-
+/* command table */ ==> /* command ap_table_t */
+
+-
+/* handlers */ ==> /* handlers */
+
+
+
+The remainder of the old functions should be registered as hooks. There are the following hook stages defined so far...
+
+
+
+-
+ap_hook_post_config (this is where the old _init routines get registered)
+
+-
+ap_hook_http_method
+
+-
+ap_hook_open_logs
+
+-
+ap_hook_auth_checker
+
+-
+ap_hook_default_port
+
+-
+ap_hook_access_checker
+
+-
+ap_hook_process_connection
+
+-
+ap_hook_child_init_hook
+
+
+
+
+
+
+
+
+
+
diff --git a/docs/manual/developer/modules.html.en b/docs/manual/developer/modules.html.en
new file mode 100644
index 00000000000..b066223466f
--- /dev/null
+++ b/docs/manual/developer/modules.html.en
@@ -0,0 +1,200 @@
+
+
+
+Converting Modules from Apache 1.3 to Apache 2.0
+
+
+
+
+
+From Apache 1.3 to Apache 2.0 Modules
+
+
+This is a first attempt at writing the lessons I learned when trying to convert the mod_mmap_static module to Apache 2.0. It's by no means definitive and probably won't even be correct in some ways, but it's a start.
+
+
+The easier changes...
+
+
+Cleanup Routines
+
+These now need to be of type ap_status_t and return a value of that type. Normally the return value will be APR_SUCCESS unless there is some need to signal an error in the cleanup. Be aware that even though you signal an error not all code yet checks and acts upon the error.
+
+
+Initialisation Routines
+
+
+These should now be renamed to better signify where they sit in the overall process. So the name gets a small change from mmap_init to mmap_post_config. The arguments passed have undergone a radical change and now look like
+
+
+- ap_context_t *p,
+- ap_context_t *plog,
+- ap_context_t *ptemp,
+- server_rec *s
+
+
+Throughout Apache the old pools have been replced by the ap_context_t, though their use remains remarkably similar.
+
+
+Data Types
+
+A lot of the data types have been moved into the APR. This means that some have had a name change, such as the one shown above. The following is a brief list of some of the changes that you are likely to have to make.
+
+- pool becomes ap_context_t
+- table becomes ap_table_t
+
+
+
+
+The messier changes...
+
+Register Hooks
+
+The new architecture uses a series of hooks to provide for calling your functions. These you'll need to add to your module by way of a new function, static void register_hooks(void). The function is really reasonably straightforward once you understand what needs to be done. Each function that needs calling at some stage in the processing of a request needs to be registered, handlers do not. There are a number of phases where functions can be added, and for each you can specify with a high degree of control the relative order that the function will be called in.
+
+
+This is the code that was added to mod_mmap_static
+
+
+static void register_hooks(void)
+{
+ static const char * const aszPre[]={ "http_core.c",NULL };
+ ap_hook_post_config(mmap_post_config,NULL,NULL,HOOK_MIDDLE);
+ ap_hook_translate_name(mmap_static_xlat,aszPre,NULL,HOOK_LAST);
+};
+
+
+This registers 2 functions that need to be called, one in the post_config stage (virtually every module will need this one) and one for the translate_name phase. note that while there are different function names the format of each is identical. So what is the format?
+
+
+ap_hook_[phase_name](function_name, predecessors, successors, position);
+
+
+There are 3 hook positions defined...
+
+
+- HOOK_FIRST
+- HOOK_MIDDLE
+- HOOK_LAST
+
+
+To define the position you use the position and then modify it with the predecessors and successors. each of the modifiers can be a list of functions that should be called, either before the function is run (predecessors) or after the function has run (successors).
+
+
+In the mod_mmap_static case I didn't care about the post_config stage, but the mmap_static_xlat MUST be called after the core module had done it's name translation, hence the use of the aszPre to define a modifier to the position HOOK_LAST.
+
+Module Definition
+
+
+There are now a lot fewer stages to worry about when creating your module definition. The old defintion looked like
+
+
+module MODULE_VAR_EXPORT [module_name]_module =
+{
+ STANDARD_MODULE_STUFF,
+ /* initializer */
+ /* dir config creater */
+ /* dir merger --- default is to override */
+ /* server config */
+ /* merge server config */
+ /* command handlers */
+ /* handlers */
+ /* filename translation */
+ /* check_user_id */
+ /* check auth */
+ /* check access */
+ /* type_checker */
+ /* fixups */
+ /* logger */
+ /* header parser */
+ /* child_init */
+ /* child_exit */
+ /* post read-request */
+};
+
+
+The new structure is a great deal simpler...
+
+
+module MODULE_VAR_EXPORT [module_name]_module =
+{
+ STANDARD20_MODULE_STUFF,
+ /* create per-directory config structures */
+ /* merge per-directory config structures */
+ /* create per-server config structures */
+ /* merge per-server config structures */
+ /* command handlers */
+ /* handlers */
+ /* register hooks */
+ };
+
+
+Some of these read directly across, some don't. I'll try to summarise what should be done below.
+
+
+The stages that read directly across :
+
+
+-
+/* dir config creater */ ==> /* create per-directory config structures */
+
+-
+/* server config */ ==> /* create per-server config structures */
+
+-
+/* dir merger */ ==> /* merge per-directory config structures */
+
+-
+/* merge server config */ ==> /* merge per-server config structures */
+
+-
+/* command table */ ==> /* command ap_table_t */
+
+-
+/* handlers */ ==> /* handlers */
+
+
+
+The remainder of the old functions should be registered as hooks. There are the following hook stages defined so far...
+
+
+
+-
+ap_hook_post_config (this is where the old _init routines get registered)
+
+-
+ap_hook_http_method
+
+-
+ap_hook_open_logs
+
+-
+ap_hook_auth_checker
+
+-
+ap_hook_default_port
+
+-
+ap_hook_access_checker
+
+-
+ap_hook_process_connection
+
+-
+ap_hook_child_init_hook
+
+
+
+
+
+
+
+
+
+
diff --git a/docs/manual/index.html b/docs/manual/index.html
new file mode 100644
index 00000000000..5bfef758c07
--- /dev/null
+++ b/docs/manual/index.html
@@ -0,0 +1,31 @@
+
+
+
+Apache-2.0 Documentation
+
+
+
+Manual Index for Apache-2.0
+The documentation has been split into 2 sections. One is for people installing and configuring an Apache server, the other is for those who are developing the server.
+Where do you want to go today?
+
+
+David Reid, 15th January 2000
+
+
+
diff --git a/docs/manual/index.html.en b/docs/manual/index.html.en
new file mode 100644
index 00000000000..5bfef758c07
--- /dev/null
+++ b/docs/manual/index.html.en
@@ -0,0 +1,31 @@
+
+
+
+Apache-2.0 Documentation
+
+
+
+Manual Index for Apache-2.0
+The documentation has been split into 2 sections. One is for people installing and configuring an Apache server, the other is for those who are developing the server.
+Where do you want to go today?
+
+
+David Reid, 15th January 2000
+
+
+
diff --git a/docs/manual/misc/rewriteguide.html b/docs/manual/misc/rewriteguide.html
new file mode 100644
index 00000000000..b9c10e2aacc
--- /dev/null
+++ b/docs/manual/misc/rewriteguide.html
@@ -0,0 +1,1905 @@
+
+
+Apache 1.3 URL Rewriting Guide
+
+
+
+
+
+
+
+
+
+
+Apache 1.3
+URL Rewriting Guide
+
+
+ Originally written by
+Ralf S. Engelschall <rse@apache.org>
+December 1997
+
+
+
+
+This document supplements the mod_rewrite reference documentation. It describes
+how one can use Apache's mod_rewrite to solve typical URL-based problems
+webmasters are usually confronted with in practice. I give detailed
+descriptions on how to solve each problem by configuring URL rewriting
+rulesets.
+
+
+
+The Apache module mod_rewrite is a killer one, i.e. it is a really
+sophisticated module which provides a powerful way to do URL manipulations.
+With it you can nearly do all types of URL manipulations you ever dreamed
+about. The price you have to pay is to accept complexity, because
+mod_rewrite's major drawback is that it is not easy to understand and use for
+the beginner. And even Apache experts sometimes discover new aspects where
+mod_rewrite can help.
+
+In other words: With mod_rewrite you either shoot yourself in the foot the
+first time and never use it again or love it for the rest of your life because
+of its power. This paper tries to give you a few initial success events to
+avoid the first case by presenting already invented solutions to you.
+
+
+
+Here come a lot of practical solutions I've either invented myself or
+collected from other peoples solutions in the past. Feel free to learn the
+black magic of URL rewriting from these examples.
+
+
+ATTENTION: Depending on your server-configuration it can be necessary to
+slightly change the examples for your situation, e.g. adding the [PT] flag
+when additionally using mod_alias and mod_userdir, etc. Or rewriting a ruleset
+to fit in .htaccess context instead of per-server context. Always try
+to understand what a particular ruleset really does before you use it. It
+avoid problems.
+
+ URL Layout
+
+
+ Canonical URLs
+
+
+
+- Description:
+
-
+On some webservers there are more than one URL for a resource. Usually there
+are canonical URLs (which should be actually used and distributed) and those
+which are just shortcuts, internal ones, etc. Independed which URL the user
+supplied with the request he should finally see the canonical one only.
+
+
+ - Solution:
+
-
+We do an external HTTP redirect for all non-canonical URLs to fix them in the
+location view of the Browser and for all subsequent requests. In the example
+ruleset below we replace /~user by the canonical /u/user and
+fix a missing trailing slash for /u/user.
+
+
+RewriteRule ^/~([^/]+)/?(.*) /u/$1/$2 [R]
+RewriteRule ^/([uge])/([^/]+)$ /$1/$2/ [R]
+ |
+
+
+
+
+ Canonical Hostnames
+
+
+
+- Description:
+
-
+...
+
+
+ - Solution:
+
-
+
+
+RewriteCond %{HTTP_HOST} !^fully\.qualified\.domain\.name [NC]
+RewriteCond %{HTTP_HOST} !^$
+RewriteCond %{SERVER_PORT} !^80$
+RewriteRule ^/(.*) http://fully.qualified.domain.name:%{SERVER_PORT}/$1 [L,R]
+RewriteCond %{HTTP_HOST} !^fully\.qualified\.domain\.name [NC]
+RewriteCond %{HTTP_HOST} !^$
+RewriteRule ^/(.*) http://fully.qualified.domain.name/$1 [L,R]
+ |
+
+
+
+
+ Moved DocumentRoot
+
+
+
+- Description:
+
-
+Usually the DocumentRoot of the webserver directly relates to the URL
+``/''. But often this data is not really of top-level priority, it is
+perhaps just one entity of a lot of data pools. For instance at our Intranet
+sites there are /e/www/ (the homepage for WWW), /e/sww/ (the
+homepage for the Intranet) etc. Now because the data of the DocumentRoot stays
+at /e/www/ we had to make sure that all inlined images and other
+stuff inside this data pool work for subsequent requests.
+
+
+ - Solution:
+
-
+We just redirect the URL / to /e/www/. While is seems
+trivial it is actually trivial with mod_rewrite, only. Because the typical
+old mechanisms of URL Aliases (as provides by mod_alias and friends)
+only used prefix matching. With this you cannot do such a redirection
+because the DocumentRoot is a prefix of all URLs. With mod_rewrite it is
+really trivial:
+
+
+RewriteEngine on
+RewriteRule ^/$ /e/www/ [R]
+ |
+
+
+
+
+ Trailing Slash Problem
+
+
+
+- Description:
+
-
+Every webmaster can sing a song about the problem of the trailing slash on
+URLs referencing directories. If they are missing, the server dumps an error,
+because if you say /~quux/foo instead of
+/~quux/foo/ then the server searches for a file named
+foo. And because this file is a directory it complains. Actually
+is tries to fix it themself in most of the cases, but sometimes this mechanism
+need to be emulated by you. For instance after you have done a lot of
+complicated URL rewritings to CGI scripts etc.
+
+
+ - Solution:
+
-
+The solution to this subtle problem is to let the server add the trailing
+slash automatically. To do this correctly we have to use an external redirect,
+so the browser correctly requests subsequent images etc. If we only did a
+internal rewrite, this would only work for the directory page, but would go
+wrong when any images are included into this page with relative URLs, because
+the browser would request an in-lined object. For instance, a request for
+image.gif in /~quux/foo/index.html would become
+/~quux/image.gif without the external redirect!
+
+So, to do this trick we write:
+
+
+RewriteEngine on
+RewriteBase /~quux/
+RewriteRule ^foo$ foo/ [R]
+ |
+
+
+The crazy and lazy can even do the following in the top-level
+.htaccess file of their homedir. But notice that this creates some
+processing overhead.
+
+
+RewriteEngine on
+RewriteBase /~quux/
+RewriteCond %{REQUEST_FILENAME} -d
+RewriteRule ^(.+[^/])$ $1/ [R]
+ |
+
+
+
+
+ Webcluster through Homogeneous URL Layout
+
+
+
+- Description:
+
-
+We want to create a homogenous and consistent URL layout over all WWW servers
+on a Intranet webcluster, i.e. all URLs (per definition server local and thus
+server dependent!) become actually server independed! What we want is
+to give the WWW namespace a consistent server-independend layout: no URL
+should have to include any physically correct target server. The cluster
+itself should drive us automatically to the physical target host.
+
+
+ - Solution:
+
-
+First, the knowledge of the target servers come from (distributed) external
+maps which contain information where our users, groups and entities stay.
+The have the form
+
+
+user1 server_of_user1
+user2 server_of_user2
+: :
+
+
+We put them into files map.xxx-to-host. Second we need to instruct
+all servers to redirect URLs of the forms
+
+
+/u/user/anypath
+/g/group/anypath
+/e/entity/anypath
+
+
+to
+
+
+http://physical-host/u/user/anypath
+http://physical-host/g/group/anypath
+http://physical-host/e/entity/anypath
+
+
+when the URL is not locally valid to a server. The following ruleset does
+this for us by the help of the map files (assuming that server0 is a default
+server which will be used if a user has no entry in the map):
+
+
+RewriteEngine on
+
+RewriteMap user-to-host txt:/path/to/map.user-to-host
+RewriteMap group-to-host txt:/path/to/map.group-to-host
+RewriteMap entity-to-host txt:/path/to/map.entity-to-host
+
+RewriteRule ^/u/([^/]+)/?(.*) http://${user-to-host:$1|server0}/u/$1/$2
+RewriteRule ^/g/([^/]+)/?(.*) http://${group-to-host:$1|server0}/g/$1/$2
+RewriteRule ^/e/([^/]+)/?(.*) http://${entity-to-host:$1|server0}/e/$1/$2
+
+RewriteRule ^/([uge])/([^/]+)/?$ /$1/$2/.www/
+RewriteRule ^/([uge])/([^/]+)/([^.]+.+) /$1/$2/.www/$3\
+ |
+
+
+
+
+ Move Homedirs to Different Webserver
+
+
+
+- Description:
+
-
+A lot of webmaster aksed for a solution to the following situation: They
+wanted to redirect just all homedirs on a webserver to another webserver.
+They usually need such things when establishing a newer webserver which will
+replace the old one over time.
+
+
+ - Solution:
+
-
+The solution is trivial with mod_rewrite. On the old webserver we just
+redirect all /~user/anypath URLs to
+http://newserver/~user/anypath.
+
+
+RewriteEngine on
+RewriteRule ^/~(.+) http://newserver/~$1 [R,L]
+ |
+
+
+
+
+ Structured Homedirs
+
+
+
+- Description:
+
-
+Some sites with thousend of users usually use a structured homedir layout,
+i.e. each homedir is in a subdirectory which begins for instance with the
+first character of the username. So, /~foo/anypath is
+/home/f/foo/.www/anypath while /~bar/anypath is
+/home/b/bar/.www/anypath.
+
+
+ - Solution:
+
-
+We use the following ruleset to expand the tilde URLs into exactly the above
+layout.
+
+
+RewriteEngine on
+RewriteRule ^/~(([a-z])[a-z0-9]+)(.*) /home/$2/$1/.www$3
+ |
+
+
+
+
+ Filesystem Reorganisation
+
+
+
+- Description:
+
-
+This really is a hardcore example: a killer application which heavily uses
+per-directory RewriteRules to get a smooth look and feel on the Web
+while its data structure is never touched or adjusted.
+
+Background: net.sw is my archive of freely available Unix
+software packages, which I started to collect in 1992. It is both my hobby and
+job to to this, because while I'm studying computer science I have also worked
+for many years as a system and network administrator in my spare time. Every
+week I need some sort of software so I created a deep hierarchy of
+directories where I stored the packages:
+
+
+drwxrwxr-x 2 netsw users 512 Aug 3 18:39 Audio/
+drwxrwxr-x 2 netsw users 512 Jul 9 14:37 Benchmark/
+drwxrwxr-x 12 netsw users 512 Jul 9 00:34 Crypto/
+drwxrwxr-x 5 netsw users 512 Jul 9 00:41 Database/
+drwxrwxr-x 4 netsw users 512 Jul 30 19:25 Dicts/
+drwxrwxr-x 10 netsw users 512 Jul 9 01:54 Graphic/
+drwxrwxr-x 5 netsw users 512 Jul 9 01:58 Hackers/
+drwxrwxr-x 8 netsw users 512 Jul 9 03:19 InfoSys/
+drwxrwxr-x 3 netsw users 512 Jul 9 03:21 Math/
+drwxrwxr-x 3 netsw users 512 Jul 9 03:24 Misc/
+drwxrwxr-x 9 netsw users 512 Aug 1 16:33 Network/
+drwxrwxr-x 2 netsw users 512 Jul 9 05:53 Office/
+drwxrwxr-x 7 netsw users 512 Jul 9 09:24 SoftEng/
+drwxrwxr-x 7 netsw users 512 Jul 9 12:17 System/
+drwxrwxr-x 12 netsw users 512 Aug 3 20:15 Typesetting/
+drwxrwxr-x 10 netsw users 512 Jul 9 14:08 X11/
+
+
+In July 1996 I decided to make this 350 MB archive public to the world via a
+nice Web interface (
+http://net.sw.engelschall.com/net.sw/). "Nice" means that I wanted to
+offer a interface where you can browse directly through the archive hierarchy.
+And "nice" means that I didn't wanted to change anything inside this hierarchy
+- not even by putting some CGI scripts at the top of it. Why? Because the
+above structure should be later accessible via FTP as well, and I didn't
+want any Web or CGI stuuf to be there.
+
+
+ - Solution:
+
-
+The solution has two parts: The first is a set of CGI scripts which create all
+the pages at all directory levels on-the-fly. I put them under
+/e/netsw/.www/ as follows:
+
+
+-rw-r--r-- 1 netsw users 1318 Aug 1 18:10 .wwwacl
+drwxr-xr-x 18 netsw users 512 Aug 5 15:51 DATA/
+-rw-rw-rw- 1 netsw users 372982 Aug 5 16:35 LOGFILE
+-rw-r--r-- 1 netsw users 659 Aug 4 09:27 TODO
+-rw-r--r-- 1 netsw users 5697 Aug 1 18:01 netsw-about.html
+-rwxr-xr-x 1 netsw users 579 Aug 2 10:33 netsw-access.pl
+-rwxr-xr-x 1 netsw users 1532 Aug 1 17:35 netsw-changes.cgi
+-rwxr-xr-x 1 netsw users 2866 Aug 5 14:49 netsw-home.cgi
+drwxr-xr-x 2 netsw users 512 Jul 8 23:47 netsw-img/
+-rwxr-xr-x 1 netsw users 24050 Aug 5 15:49 netsw-lsdir.cgi
+-rwxr-xr-x 1 netsw users 1589 Aug 3 18:43 netsw-search.cgi
+-rwxr-xr-x 1 netsw users 1885 Aug 1 17:41 netsw-tree.cgi
+-rw-r--r-- 1 netsw users 234 Jul 30 16:35 netsw-unlimit.lst
+
+
+The DATA/ subdirectory holds the above directory structure, i.e. the
+real net.sw stuff and gets automatically updated via
+rdist from time to time.
+
+ The second part of the problem remains: how to link these two structures
+together into one smooth-looking URL tree? We want to hide the DATA/
+directory from the user while running the appropriate CGI scripts for the
+various URLs.
+
+Here is the solution: first I put the following into the per-directory
+configuration file in the Document Root of the server to rewrite the announced
+URL /net.sw/ to the internal path /e/netsw:
+
+
+RewriteRule ^net.sw$ net.sw/ [R]
+RewriteRule ^net.sw/(.*)$ e/netsw/$1
+ |
+
+
+The first rule is for requests which miss the trailing slash! The second rule
+does the real thing. And then comes the killer configuration which stays in
+the per-directory config file /e/netsw/.www/.wwwacl:
+
+
+Options ExecCGI FollowSymLinks Includes MultiViews
+
+RewriteEngine on
+
+# we are reached via /net.sw/ prefix
+RewriteBase /net.sw/
+
+# first we rewrite the root dir to
+# the handling cgi script
+RewriteRule ^$ netsw-home.cgi [L]
+RewriteRule ^index\.html$ netsw-home.cgi [L]
+
+# strip out the subdirs when
+# the browser requests us from perdir pages
+RewriteRule ^.+/(netsw-[^/]+/.+)$ $1 [L]
+
+# and now break the rewriting for local files
+RewriteRule ^netsw-home\.cgi.* - [L]
+RewriteRule ^netsw-changes\.cgi.* - [L]
+RewriteRule ^netsw-search\.cgi.* - [L]
+RewriteRule ^netsw-tree\.cgi$ - [L]
+RewriteRule ^netsw-about\.html$ - [L]
+RewriteRule ^netsw-img/.*$ - [L]
+
+# anything else is a subdir which gets handled
+# by another cgi script
+RewriteRule !^netsw-lsdir\.cgi.* - [C]
+RewriteRule (.*) netsw-lsdir.cgi/$1
+ |
+
+
+Some hints for interpretation:
+
+ - Notice the L (last) flag and no substitution field ('-') in the
+ forth part
+
- Notice the ! (not) character and the C (chain) flag
+ at the first rule in the last part
+
- Notice the catch-all pattern in the last rule
+
+
+
+
+
+ NCSA imagemap to Apache mod_imap
+
+
+
+- Description:
+
-
+When switching from the NCSA webserver to the more modern Apache webserver a
+lot of people want a smooth transition. So they want pages which use their old
+NCSA imagemap program to work under Apache with the modern
+mod_imap. The problem is that there are a lot of
+hyperlinks around which reference the imagemap program via
+/cgi-bin/imagemap/path/to/page.map. Under Apache this
+has to read just /path/to/page.map.
+
+
+ - Solution:
+
-
+We use a global rule to remove the prefix on-the-fly for all requests:
+
+
+RewriteEngine on
+RewriteRule ^/cgi-bin/imagemap(.*) $1 [PT]
+ |
+
+
+
+
+ Search pages in more than one directory
+
+
+
+- Description:
+
-
+Sometimes it is neccessary to let the webserver search for pages in more than
+one directory. Here MultiViews or other techniques cannot help.
+
+
+ - Solution:
+
-
+We program a explicit ruleset which searches for the files in the directories.
+
+
+RewriteEngine on
+
+# first try to find it in custom/...
+# ...and if found stop and be happy:
+RewriteCond /your/docroot/dir1/%{REQUEST_FILENAME} -f
+RewriteRule ^(.+) /your/docroot/dir1/$1 [L]
+
+# second try to find it in pub/...
+# ...and if found stop and be happy:
+RewriteCond /your/docroot/dir2/%{REQUEST_FILENAME} -f
+RewriteRule ^(.+) /your/docroot/dir2/$1 [L]
+
+# else go on for other Alias or ScriptAlias directives,
+# etc.
+RewriteRule ^(.+) - [PT]
+ |
+
+
+
+
+ Set Environment Variables According To URL Parts
+
+
+
+- Description:
+
-
+Perhaps you want to keep status information between requests and use the URL
+to encode it. But you don't want to use a CGI wrapper for all pages just to
+strip out this information.
+
+
+ - Solution:
+
-
+We use a rewrite rule to strip out the status information and remember it via
+an environment variable which can be later dereferenced from within XSSI or
+CGI. This way a URL /foo/S=java/bar/ gets translated to
+/foo/bar/ and the environment variable named STATUS is set
+to the value "java".
+
+
+RewriteEngine on
+RewriteRule ^(.*)/S=([^/]+)/(.*) $1/$3 [E=STATUS:$2]
+ |
+
+
+
+
+ Virtual User Hosts
+
+
+
+- Description:
+
-
+Assume that you want to provide www.username.host.domain.com
+for the homepage of username via just DNS A records to the same machine and
+without any virtualhosts on this machine.
+
+
+ - Solution:
+
-
+For HTTP/1.0 requests there is no solution, but for HTTP/1.1 requests which
+contain a Host: HTTP header we can use the following ruleset to rewrite
+http://www.username.host.com/anypath internally to
+/home/username/anypath:
+
+
+RewriteEngine on
+RewriteCond %{HTTP_HOST} ^www\.[^.]+\.host\.com$
+RewriteRule ^(.+) %{HTTP_HOST}$1 [C]
+RewriteRule ^www\.([^.]+)\.host\.com(.*) /home/$1$2
+ |
+
+
+
+
+ Redirect Homedirs For Foreigners
+
+
+
+- Description:
+
-
+We want to redirect homedir URLs to another webserver
+www.somewhere.com when the requesting user does not stay in the local
+domain ourdomain.com. This is sometimes used in virtual host
+contexts.
+
+
+ - Solution:
+
-
+Just a rewrite condition:
+
+
+RewriteEngine on
+RewriteCond %{REMOTE_HOST} !^.+\.ourdomain\.com$
+RewriteRule ^(/~.+) http://www.somewhere.com/$1 [R,L]
+ |
+
+
+
+
+ Redirect Failing URLs To Other Webserver
+
+
+
+- Description:
+
-
+A typical FAQ about URL rewriting is how to redirect failing requests on
+webserver A to webserver B. Usually this is done via ErrorDocument
+CGI-scripts in Perl, but there is also a mod_rewrite solution. But notice that
+this is less performant than using a ErrorDocument CGI-script!
+
+
+ - Solution:
+
-
+The first solution has the best performance but less flexibility and is less
+error safe:
+
+
+RewriteEngine on
+RewriteCond /your/docroot/%{REQUEST_FILENAME} !-f
+RewriteRule ^(.+) http://webserverB.dom/$1
+ |
+
+
+The problem here is that this will only work for pages inside the
+DocumentRoot. While you can add more Conditions (for instance to also handle
+homedirs, etc.) there is better variant:
+
+
+RewriteEngine on
+RewriteCond %{REQUEST_URI} !-U
+RewriteRule ^(.+) http://webserverB.dom/$1
+ |
+
+
+This uses the URL look-ahead feature of mod_rewrite. The result is that this
+will work for all types of URLs and is a safe way. But it does a performance
+impact on the webserver, because for every request there is one more internal
+subrequest. So, if your webserver runs on a powerful CPU, use this one. If it
+is a slow machine, use the first approach or better a ErrorDocument
+CGI-script.
+
+
+
+
+ Extended Redirection
+
+
+
+- Description:
+
-
+Sometimes we need more control (concerning the character escaping mechanism)
+of URLs on redirects. Usually the Apache kernels URL escape function also
+escapes anchors, i.e. URLs like "url#anchor". You cannot use this directly on
+redirects with mod_rewrite because the uri_escape() function of Apache would
+also escape the hash character. How can we redirect to such a URL?
+
+
+ - Solution:
+
-
+We have to use a kludge by the use of a NPH-CGI script which does the redirect
+itself. Because here no escaping is done (NPH=non-parseable headers). First
+we introduce a new URL scheme xredirect: by the following per-server
+config-line (should be one of the last rewrite rules):
+
+
+RewriteRule ^xredirect:(.+) /path/to/nph-xredirect.cgi/$1 \
+ [T=application/x-httpd-cgi,L]
+ |
+
+
+This forces all URLs prefixed with xredirect: to be piped through the
+nph-xredirect.cgi program. And this program just looks like:
+
+
+
+#!/path/to/perl
+##
+## nph-xredirect.cgi -- NPH/CGI script for extended redirects
+## Copyright (c) 1997 Ralf S. Engelschall, All Rights Reserved.
+##
+
+$| = 1;
+$url = $ENV{'PATH_INFO'};
+
+print "HTTP/1.0 302 Moved Temporarily\n";
+print "Server: $ENV{'SERVER_SOFTWARE'}\n";
+print "Location: $url\n";
+print "Content-type: text/html\n";
+print "\n";
+print "<html>\n";
+print "<head>\n";
+print "<title>302 Moved Temporarily (EXTENDED)</title>\n";
+print "</head>\n";
+print "<body>\n";
+print "<h1>Moved Temporarily (EXTENDED)</h1>\n";
+print "The document has moved <a href=\"$url\">here</a>.<p>\n";
+print "</body>\n";
+print "</html>\n";
+
+##EOF##
+
+ |
+
+
+This provides you with the functionality to do redirects to all URL schemes,
+i.e. including the one which are not directly accepted by mod_rewrite. For
+instance you can now also redirect to news:newsgroup via
+
+
+RewriteRule ^anyurl xredirect:news:newsgroup
+ |
+
+
+Notice: You have not to put [R] or [R,L] to the above rule because the
+xredirect: need to be expanded later by our special "pipe through"
+rule above.
+
+
+
+
+ Archive Access Multiplexer
+
+
+
+- Description:
+
-
+Do you know the great CPAN (Comprehensive Perl Archive Network) under http://www.perl.com/CPAN? This does a
+redirect to one of several FTP servers around the world which carry a CPAN
+mirror and is approximately near the location of the requesting client.
+Actually this can be called an FTP access multiplexing service. While CPAN
+runs via CGI scripts, how can a similar approach implemented via mod_rewrite?
+
+
+ - Solution:
+
-
+First we notice that from version 3.0.0 mod_rewrite can also use the "ftp:"
+scheme on redirects. And second, the location approximation can be done by a
+rewritemap over the top-level domain of the client. With a tricky chained
+ruleset we can use this top-level domain as a key to our multiplexing map.
+
+
+RewriteEngine on
+RewriteMap multiplex txt:/path/to/map.cxan
+RewriteRule ^/CxAN/(.*) %{REMOTE_HOST}::$1 [C]
+RewriteRule ^.+\.([a-zA-Z]+)::(.*)$ ${multiplex:$1|ftp.default.dom}$2 [R,L]
+ |
+
+
+##
+## map.cxan -- Multiplexing Map for CxAN
+##
+
+de ftp://ftp.cxan.de/CxAN/
+uk ftp://ftp.cxan.uk/CxAN/
+com ftp://ftp.cxan.com/CxAN/
+ :
+##EOF##
+ |
+
+
+
+
+ Time-Dependend Rewriting
+
+
+
+- Description:
+
-
+When tricks like time-dependend content should happen a lot of webmasters
+still use CGI scripts which do for instance redirects to specialized pages.
+How can it be done via mod_rewrite?
+
+
+ - Solution:
+
-
+There are a lot of variables named TIME_xxx for rewrite conditions.
+In conjunction with the special lexicographic comparison patterns <STRING,
+>STRING and =STRING we can do time-dependend redirects:
+
+
+RewriteEngine on
+RewriteCond %{TIME_HOUR}%{TIME_MIN} >0700
+RewriteCond %{TIME_HOUR}%{TIME_MIN} <1900
+RewriteRule ^foo\.html$ foo.day.html
+RewriteRule ^foo\.html$ foo.night.html
+ |
+
+
+This provides the content of foo.day.html under the URL
+foo.html from 07:00-19:00 and at the remaining time the contents of
+foo.night.html. Just a nice feature for a homepage...
+
+
+
+
+ Backward Compatibility for YYYY to XXXX migration
+
+
+
+- Description:
+
-
+How can we make URLs backward compatible (still existing virtually) after
+migrating document.YYYY to document.XXXX, e.g. after translating a bunch of
+.html files to .phtml?
+
+
+ - Solution:
+
-
+We just rewrite the name to its basename and test for existence of the new
+extension. If it exists, we take that name, else we rewrite the URL to its
+original state.
+
+
+# backward compatibility ruleset for
+# rewriting document.html to document.phtml
+# when and only when document.phtml exists
+# but no longer document.html
+RewriteEngine on
+RewriteBase /~quux/
+# parse out basename, but remember the fact
+RewriteRule ^(.*)\.html$ $1 [C,E=WasHTML:yes]
+# rewrite to document.phtml if exists
+RewriteCond %{REQUEST_FILENAME}.phtml -f
+RewriteRule ^(.*)$ $1.phtml [S=1]
+# else reverse the previous basename cutout
+RewriteCond %{ENV:WasHTML} ^yes$
+RewriteRule ^(.*)$ $1.html
+ |
+
+
+
+Content Handling
+
+
+ From Old to New (intern)
+
+
+
+- Description:
+
-
+Assume we have recently renamed the page bar.html to
+foo.html and now want to provide the old URL for backward
+compatibility. Actually we want that users of the old URL even not recognize
+that the pages was renamed.
+
+
+ - Solution:
+
-
+We rewrite the old URL to the new one internally via the following rule:
+
+
+RewriteEngine on
+RewriteBase /~quux/
+RewriteRule ^foo\.html$ bar.html
+ |
+
+
+
+
+ From Old to New (extern)
+
+
+
+- Description:
+
-
+Assume again that we have recently renamed the page bar.html to
+foo.html and now want to provide the old URL for backward
+compatibility. But this time we want that the users of the old URL get hinted
+to the new one, i.e. their browsers Location field should change, too.
+
+
+ - Solution:
+
-
+We force a HTTP redirect to the new URL which leads to a change of the
+browsers and thus the users view:
+
+
+RewriteEngine on
+RewriteBase /~quux/
+RewriteRule ^foo\.html$ bar.html [R]
+ |
+
+
+
+
+ Browser Dependend Content
+
+
+
+- Description:
+
-
+At least for important top-level pages it is sometimes necesarry to provide
+the optimum of browser dependend content, i.e. one has to provide a maximum
+version for the latest Netscape variants, a minimum version for the Lynx
+browsers and a average feature version for all others.
+
+
+ - Solution:
+
-
+We cannot use content negotiation because the browsers do not provide their
+type in that form. Instead we have to act on the HTTP header "User-Agent".
+The following condig does the following: If the HTTP header "User-Agent"
+begins with "Mozilla/3", the page foo.html is rewritten to
+foo.NS.html and and the rewriting stops. If the browser is "Lynx" or
+"Mozilla" of version 1 or 2 the URL becomes foo.20.html. All other
+browsers receive page foo.32.html. This is done by the following
+ruleset:
+
+
+RewriteCond %{HTTP_USER_AGENT} ^Mozilla/3.*
+RewriteRule ^foo\.html$ foo.NS.html [L]
+
+RewriteCond %{HTTP_USER_AGENT} ^Lynx/.* [OR]
+RewriteCond %{HTTP_USER_AGENT} ^Mozilla/[12].*
+RewriteRule ^foo\.html$ foo.20.html [L]
+
+RewriteRule ^foo\.html$ foo.32.html [L]
+ |
+
+
+
+
+ Dynamic Mirror
+
+
+
+- Description:
+
-
+Assume there are nice webpages on remote hosts we want to bring into our
+namespace. For FTP servers we would use the mirror program which
+actually maintains an explicit up-to-date copy of the remote data on the local
+machine. For a webserver we could use the program webcopy which acts
+similar via HTTP. But both techniques have one major drawback: The local copy
+is always just as up-to-date as often we run the program. It would be much
+better if the mirror is not a static one we have to establish explicitly.
+Instead we want a dynamic mirror with data which gets updated automatically
+when there is need (updated data on the remote host).
+
+
+ - Solution:
+
-
+To provide this feature we map the remote webpage or even the complete remote
+webarea to our namespace by the use of the Proxy Throughput feature
+(flag [P]):
+
+
+RewriteEngine on
+RewriteBase /~quux/
+RewriteRule ^hotsheet/(.*)$ http://www.tstimpreso.com/hotsheet/$1 [P]
+ |
+
+
+RewriteEngine on
+RewriteBase /~quux/
+RewriteRule ^usa-news\.html$ http://www.quux-corp.com/news/index.html [P]
+ |
+
+
+
+
+ Reverse Dynamic Mirror
+
+
+
+- Description:
+
-
+...
+
+
+ - Solution:
+
-
+
+
+RewriteEngine on
+RewriteCond /mirror/of/remotesite/$1 -U
+RewriteRule ^http://www\.remotesite\.com/(.*)$ /mirror/of/remotesite/$1
+ |
+
+
+
+
+ Retrieve Missing Data from Intranet
+
+
+
+- Description:
+
-
+This is a tricky way of virtually running a corporates (external) Internet
+webserver (www.quux-corp.dom), while actually keeping and maintaining
+its data on a (internal) Intranet webserver
+(www2.quux-corp.dom) which is protected by a firewall. The
+trick is that on the external webserver we retrieve the requested data
+on-the-fly from the internal one.
+
+
+ - Solution:
+
-
+First, we have to make sure that our firewall still protects the internal
+webserver and that only the external webserver is allowed to retrieve data
+from it. For a packet-filtering firewall we could for instance configure a
+firewall ruleset like the following:
+
+
+ALLOW Host www.quux-corp.dom Port >1024 --> Host www2.quux-corp.dom Port 80
+DENY Host * Port * --> Host www2.quux-corp.dom Port 80
+ |
+
+
+Just adjust it to your actual configuration syntax. Now we can establish the
+mod_rewrite rules which request the missing data in the background through the
+proxy throughput feature:
+
+
+RewriteRule ^/~([^/]+)/?(.*) /home/$1/.www/$2
+RewriteCond %{REQUEST_FILENAME} !-f
+RewriteCond %{REQUEST_FILENAME} !-d
+RewriteRule ^/home/([^/]+)/.www/?(.*) http://www2.quux-corp.dom/~$1/pub/$2 [P]
+ |
+
+
+
+
+ Load Balancing
+
+
+
+- Description:
+
-
+Suppose we want to load balance the traffic to www.foo.com over
+www[0-5].foo.com (a total of 6 servers). How can this be done?
+
+
+ - Solution:
+
-
+There are a lot of possible solutions for this problem. We will discuss first
+a commonly known DNS-based variant and then the special one with mod_rewrite:
+
+
+- DNS Round-Robin
+
+
+The simplest method for load-balancing is to use the DNS round-robin feature
+of BIND. Here you just configure www[0-9].foo.com as usual in your
+DNS with A(address) records, e.g.
+
+
+www0 IN A 1.2.3.1
+www1 IN A 1.2.3.2
+www2 IN A 1.2.3.3
+www3 IN A 1.2.3.4
+www4 IN A 1.2.3.5
+www5 IN A 1.2.3.6
+ |
+
+
+Then you additionally add the following entry:
+
+
+www IN CNAME www0.foo.com.
+ IN CNAME www1.foo.com.
+ IN CNAME www2.foo.com.
+ IN CNAME www3.foo.com.
+ IN CNAME www4.foo.com.
+ IN CNAME www5.foo.com.
+ IN CNAME www6.foo.com.
+ |
+
+
+Notice that this seems wrong, but is actually an intended feature of BIND and
+can be used in this way. However, now when www.foo.com gets resolved,
+BIND gives out www0-www6 - but in a slightly permutated/rotated order
+every time. This way the clients are spread over the various servers.
+
+But notice that this not a perfect load balancing scheme, because DNS resolve
+information gets cached by the other nameservers on the net, so once a client
+has resolved www.foo.com to a particular wwwN.foo.com, all
+subsequent requests also go to this particular name wwwN.foo.com. But
+the final result is ok, because the total sum of the requests are really
+spread over the various webservers.
+
+
+ - DNS Load-Balancing
+
+
+A sophisticated DNS-based method for load-balancing is to use the program
+lbnamed which can be found at http://www.stanford.edu/~schemers/docs/lbnamed/lbnamed.html.
+It is a Perl 5 program in conjunction with auxilliary tools which provides a
+real load-balancing for DNS.
+
+
+ - Proxy Throughput Round-Robin
+
+
+In this variant we use mod_rewrite and its proxy throughput feature. First we
+dedicate www0.foo.com to be actually www.foo.com by using a
+single
+
+
+www IN CNAME www0.foo.com.
+ |
+
+
+entry in the DNS. Then we convert www0.foo.com to a proxy-only
+server, i.e. we configure this machine so all arriving URLs are just pushed
+through the internal proxy to one of the 5 other servers (www1-www5).
+To accomplish this we first establish a ruleset which contacts a load
+balancing script lb.pl for all URLs.
+
+
+RewriteEngine on
+RewriteMap lb prg:/path/to/lb.pl
+RewriteRule ^/(.+)$ ${lb:$1} [P,L]
+ |
+
+
+Then we write lb.pl:
+
+
+#!/path/to/perl
+##
+## lb.pl -- load balancing script
+##
+
+$| = 1;
+
+$name = "www"; # the hostname base
+$first = 1; # the first server (not 0 here, because 0 is myself)
+$last = 5; # the last server in the round-robin
+$domain = "foo.dom"; # the domainname
+
+$cnt = 0;
+while (<STDIN>) {
+ $cnt = (($cnt+1) % ($last+1-$first));
+ $server = sprintf("%s%d.%s", $name, $cnt+$first, $domain);
+ print "http://$server/$_";
+}
+
+##EOF##
+ |
+
+
+A last notice: Why is this useful? Seems like www0.foo.com still is
+overloaded? The answer is yes, it is overloaded, but with plain proxy
+throughput requests, only! All SSI, CGI, ePerl, etc. processing is completely
+done on the other machines. This is the essential point.
+
+
+ - Hardware/TCP Round-Robin
+
+
+There is a hardware solution available, too. Cisco has a beast called
+LocalDirector which does a load balancing at the TCP/IP level. Actually this
+is some sort of a circuit level gateway in front of a webcluster. If you have
+enough money and really need a solution with high performance, use this one.
+
+
+
+
+
+
+ Reverse Proxy
+
+
+
+- Description:
+
-
+...
+
+
+ - Solution:
+
-
+
+
+##
+## apache-rproxy.conf -- Apache configuration for Reverse Proxy Usage
+##
+
+# server type
+ServerType standalone
+Port 8000
+MinSpareServers 16
+StartServers 16
+MaxSpareServers 16
+MaxClients 16
+MaxRequestsPerChild 100
+
+# server operation parameters
+KeepAlive on
+MaxKeepAliveRequests 100
+KeepAliveTimeout 15
+Timeout 400
+IdentityCheck off
+HostnameLookups off
+
+# paths to runtime files
+PidFile /path/to/apache-rproxy.pid
+LockFile /path/to/apache-rproxy.lock
+ErrorLog /path/to/apache-rproxy.elog
+CustomLog /path/to/apache-rproxy.dlog "%{%v/%T}t %h -> %{SERVER}e URL: %U"
+
+# unused paths
+ServerRoot /tmp
+DocumentRoot /tmp
+CacheRoot /tmp
+RewriteLog /dev/null
+TransferLog /dev/null
+TypesConfig /dev/null
+AccessConfig /dev/null
+ResourceConfig /dev/null
+
+# speed up and secure processing
+<Directory />
+Options -FollowSymLinks -SymLinksIfOwnerMatch
+AllowOverwrite None
+</Directory>
+
+# the status page for monitoring the reverse proxy
+<Location /rproxy-status>
+SetHandler server-status
+</Location>
+
+# enable the URL rewriting engine
+RewriteEngine on
+RewriteLogLevel 0
+
+# define a rewriting map with value-lists where
+# mod_rewrite randomly chooses a particular value
+RewriteMap server rnd:/path/to/apache-rproxy.conf-servers
+
+# make sure the status page is handled locally
+# and make sure no one uses our proxy except ourself
+RewriteRule ^/apache-rproxy-status.* - [L]
+RewriteRule ^(http|ftp)://.* - [F]
+
+# now choose the possible servers for particular URL types
+RewriteRule ^/(.*\.(cgi|shtml))$ to://${server:dynamic}/$1 [S=1]
+RewriteRule ^/(.*)$ to://${server:static}/$1
+
+# and delegate the generated URL by passing it
+# through the proxy module
+RewriteRule ^to://([^/]+)/(.*) http://$1/$2 [E=SERVER:$1,P,L]
+
+# and make really sure all other stuff is forbidden
+# when it should survive the above rules...
+RewriteRule .* - [F]
+
+# enable the Proxy module without caching
+ProxyRequests on
+NoCache *
+
+# setup URL reverse mapping for redirect reponses
+ProxyPassReverse / http://www1.foo.dom/
+ProxyPassReverse / http://www2.foo.dom/
+ProxyPassReverse / http://www3.foo.dom/
+ProxyPassReverse / http://www4.foo.dom/
+ProxyPassReverse / http://www5.foo.dom/
+ProxyPassReverse / http://www6.foo.dom/
+ |
+
+
+##
+## apache-rproxy.conf-servers -- Apache/mod_rewrite selection table
+##
+
+# list of backend servers which serve static
+# pages (HTML files and Images, etc.)
+static www1.foo.dom|www2.foo.dom|www3.foo.dom|www4.foo.dom
+
+# list of backend servers which serve dynamically
+# generated page (CGI programs or mod_perl scripts)
+dynamic www5.foo.dom|www6.foo.dom
+ |
+
+
+
+
+ New MIME-type, New Service
+
+
+
+- Description:
+
-
+On the net there are a lot of nifty CGI programs. But their usage is usually
+boring, so a lot of webmaster don't use them. Even Apache's Action handler
+feature for MIME-types is only appropriate when the CGI programs don't need
+special URLs (actually PATH_INFO and QUERY_STRINGS) as their input.
+
+First, let us configure a new file type with extension .scgi
+(for secure CGI) which will be processed by the popular cgiwrap
+program. The problem here is that for instance we use a Homogeneous URL Layout
+(see above) a file inside the user homedirs has the URL
+/u/user/foo/bar.scgi. But cgiwrap needs the URL in the form
+/~user/foo/bar.scgi/. The following rule solves the problem:
+
+
+RewriteRule ^/[uge]/([^/]+)/\.www/(.+)\.scgi(.*) ...
+... /internal/cgi/user/cgiwrap/~$1/$2.scgi$3 [NS,T=application/x-http-cgi]
+ |
+
+
+Or assume we have some more nifty programs:
+wwwlog (which displays the access.log for a URL subtree and
+wwwidx (which runs Glimpse on a URL subtree). We have to
+provide the URL area to these programs so they know on which area
+they have to act on. But usually this ugly, because they are all the
+times still requested from that areas, i.e. typically we would run
+the swwidx program from within /u/user/foo/ via
+hyperlink to
+
+
+/internal/cgi/user/swwidx?i=/u/user/foo/
+
+
+which is ugly. Because we have to hard-code both the location of the
+area and the location of the CGI inside the hyperlink. When we have to
+reorganise or area, we spend a lot of time changing the various hyperlinks.
+
+
+ - Solution:
+
-
+The solution here is to provide a special new URL format which automatically
+leads to the proper CGI invocation. We configure the following:
+
+
+RewriteRule ^/([uge])/([^/]+)(/?.*)/\* /internal/cgi/user/wwwidx?i=/$1/$2$3/
+RewriteRule ^/([uge])/([^/]+)(/?.*):log /internal/cgi/user/wwwlog?f=/$1/$2$3
+ |
+
+
+Now the hyperlink to search at /u/user/foo/ reads only
+
+
+href="*"
+
+
+which internally gets automatically transformed to
+
+
+/internal/cgi/user/wwwidx?i=/u/user/foo/
+
+
+The same approach leads to an invocation for the access log CGI
+program when the hyperlink :log gets used.
+
+
+
+
+ From Static to Dynamic
+
+
+
+- Description:
+
-
+How can we transform a static page foo.html into a dynamic variant
+foo.cgi in a seemless way, i.e. without notice by the browser/user.
+
+
+ - Solution:
+
-
+We just rewrite the URL to the CGI-script and force the correct MIME-type so
+it gets really run as a CGI-script. This way a request to
+/~quux/foo.html internally leads to the invokation of
+/~quux/foo.cgi.
+
+
+RewriteEngine on
+RewriteBase /~quux/
+RewriteRule ^foo\.html$ foo.cgi [T=application/x-httpd-cgi]
+ |
+
+
+
+
+ On-the-fly Content-Regeneration
+
+
+
+- Description:
+
-
+Here comes a really esoteric feature: Dynamically generated but statically
+served pages, i.e. pages should be delivered as pur static pages (read from
+the filesystem and just passed through), but they have to be generated
+dynamically by the webserver if missing. This way you can have CGI-generated
+pages which are statically unless one (or a cronjob) removes the static
+contents. Then the contents gets refreshed.
+
+
+ - Solution:
+
-
+This is done via the following ruleset:
+
+
+RewriteCond %{REQUEST_FILENAME} !-s
+RewriteCond ^page\.html$ page.cgi [T=application/x-httpd-cgi,L]
+ |
+
+
+Here a request to page.html leads to a internal run of a
+corresponding page.cgi if page.html is still missing or has
+filesize null. The trick here is that page.cgi is a usual CGI script
+which (additionally to its STDOUT) writes its output to the file
+page.html. Once it was run, the server sends out the data of
+page.html. When the webmaster wants to force a refresh the contents,
+he just removes page.html (usually done by a cronjob).
+
+
+
+
+ Document With Autorefresh
+
+
+
+- Description:
+
-
+Wouldn't it be nice while creating a complex webpage if the webbrowser would
+automatically refresh the page every time we write a new version from within
+our editor? Impossible?
+
+
+ - Solution:
+
-
+No! We just combine the MIME multipart feature, the webserver NPH feature and
+the URL manipulation power of mod_rewrite. First, we establish a new URL
+feature: Adding just :refresh to any URL causes this to be refreshed
+every time it gets updated on the filesystem.
+
+
+RewriteRule ^(/[uge]/[^/]+/?.*):refresh /internal/cgi/apache/nph-refresh?f=$1
+ |
+
+
+Now when we reference the URL
+
+
+/u/foo/bar/page.html:refresh
+
+
+this leads to the internal invocation of the URL
+
+
+/internal/cgi/apache/nph-refresh?f=/u/foo/bar/page.html
+
+
+The only missing part is the NPH-CGI script. Although one would usually say
+"left as an exercise to the reader" ;-) I will provide this, too.
+
+
+#!/sw/bin/perl
+##
+## nph-refresh -- NPH/CGI script for auto refreshing pages
+## Copyright (c) 1997 Ralf S. Engelschall, All Rights Reserved.
+##
+$| = 1;
+
+# split the QUERY_STRING variable
+@pairs = split(/&/, $ENV{'QUERY_STRING'});
+foreach $pair (@pairs) {
+ ($name, $value) = split(/=/, $pair);
+ $name =~ tr/A-Z/a-z/;
+ $name = 'QS_' . $name;
+ $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
+ eval "\$$name = \"$value\"";
+}
+$QS_s = 1 if ($QS_s eq '');
+$QS_n = 3600 if ($QS_n eq '');
+if ($QS_f eq '') {
+ print "HTTP/1.0 200 OK\n";
+ print "Content-type: text/html\n\n";
+ print "<b>ERROR</b>: No file given\n";
+ exit(0);
+}
+if (! -f $QS_f) {
+ print "HTTP/1.0 200 OK\n";
+ print "Content-type: text/html\n\n";
+ print "<b>ERROR</b>: File $QS_f not found\n";
+ exit(0);
+}
+
+sub print_http_headers_multipart_begin {
+ print "HTTP/1.0 200 OK\n";
+ $bound = "ThisRandomString12345";
+ print "Content-type: multipart/x-mixed-replace;boundary=$bound\n";
+ &print_http_headers_multipart_next;
+}
+
+sub print_http_headers_multipart_next {
+ print "\n--$bound\n";
+}
+
+sub print_http_headers_multipart_end {
+ print "\n--$bound--\n";
+}
+
+sub displayhtml {
+ local($buffer) = @_;
+ $len = length($buffer);
+ print "Content-type: text/html\n";
+ print "Content-length: $len\n\n";
+ print $buffer;
+}
+
+sub readfile {
+ local($file) = @_;
+ local(*FP, $size, $buffer, $bytes);
+ ($x, $x, $x, $x, $x, $x, $x, $size) = stat($file);
+ $size = sprintf("%d", $size);
+ open(FP, "<$file");
+ $bytes = sysread(FP, $buffer, $size);
+ close(FP);
+ return $buffer;
+}
+
+$buffer = &readfile($QS_f);
+&print_http_headers_multipart_begin;
+&displayhtml($buffer);
+
+sub mystat {
+ local($file) = $_[0];
+ local($time);
+
+ ($x, $x, $x, $x, $x, $x, $x, $x, $x, $mtime) = stat($file);
+ return $mtime;
+}
+
+$mtimeL = &mystat($QS_f);
+$mtime = $mtime;
+for ($n = 0; $n < $QS_n; $n++) {
+ while (1) {
+ $mtime = &mystat($QS_f);
+ if ($mtime ne $mtimeL) {
+ $mtimeL = $mtime;
+ sleep(2);
+ $buffer = &readfile($QS_f);
+ &print_http_headers_multipart_next;
+ &displayhtml($buffer);
+ sleep(5);
+ $mtimeL = &mystat($QS_f);
+ last;
+ }
+ sleep($QS_s);
+ }
+}
+
+&print_http_headers_multipart_end;
+
+exit(0);
+
+##EOF##
+
+
+
+
+
+ Mass Virtual Hosting
+
+
+
+- Description:
+
-
+The <VirtualHost> feature of Apache is nice and works great
+when you just have a few dozens virtual hosts. But when you are an ISP and
+have hundreds of virtual hosts to provide this feature is not the best choice.
+
+
+ - Solution:
+
-
+To provide this feature we map the remote webpage or even the complete remote
+webarea to our namespace by the use of the Proxy Throughput feature
+(flag [P]):
+
+
+##
+## vhost.map
+##
+www.vhost1.dom:80 /path/to/docroot/vhost1
+www.vhost2.dom:80 /path/to/docroot/vhost2
+ :
+www.vhostN.dom:80 /path/to/docroot/vhostN
+ |
+
+
+##
+## httpd.conf
+##
+ :
+# use the canonical hostname on redirects, etc.
+UseCanonicalName on
+
+ :
+# add the virtual host in front of the CLF-format
+CustomLog /path/to/access_log "%{VHOST}e %h %l %u %t \"%r\" %>s %b"
+ :
+
+# enable the rewriting engine in the main server
+RewriteEngine on
+
+# define two maps: one for fixing the URL and one which defines
+# the available virtual hosts with their corresponding
+# DocumentRoot.
+RewriteMap lowercase int:tolower
+RewriteMap vhost txt:/path/to/vhost.map
+
+# Now do the actual virtual host mapping
+# via a huge and complicated single rule:
+#
+# 1. make sure we don't map for common locations
+RewriteCond %{REQUEST_URL} !^/commonurl1/.*
+RewriteCond %{REQUEST_URL} !^/commonurl2/.*
+ :
+RewriteCond %{REQUEST_URL} !^/commonurlN/.*
+#
+# 2. make sure we have a Host header, because
+# currently our approach only supports
+# virtual hosting through this header
+RewriteCond %{HTTP_HOST} !^$
+#
+# 3. lowercase the hostname
+RewriteCond ${lowercase:%{HTTP_HOST}|NONE} ^(.+)$
+#
+# 4. lookup this hostname in vhost.map and
+# remember it only when it is a path
+# (and not "NONE" from above)
+RewriteCond ${vhost:%1} ^(/.*)$
+#
+# 5. finally we can map the URL to its docroot location
+# and remember the virtual host for logging puposes
+RewriteRule ^/(.*)$ %1/$1 [E=VHOST:${lowercase:%{HTTP_HOST}}]
+ :
+ |
+
+
+
+Access Restriction
+
+
+ Blocking of Robots
+
+
+
+- Description:
+
-
+How can we block a really annoying robot from retrieving pages of a specific
+webarea? A /robots.txt file containing entries of the "Robot
+Exclusion Protocol" is typically not enough to get rid of such a robot.
+
+
+ - Solution:
+
-
+We use a ruleset which forbids the URLs of the webarea
+/~quux/foo/arc/ (perhaps a very deep directory indexed area where the
+robot traversal would create big server load). We have to make sure that we
+forbid access only to the particular robot, i.e. just forbidding the host
+where the robot runs is not enough. This would block users from this host,
+too. We accomplish this by also matching the User-Agent HTTP header
+information.
+
+
+RewriteCond %{HTTP_USER_AGENT} ^NameOfBadRobot.*
+RewriteCond %{REMOTE_ADDR} ^123\.45\.67\.[8-9]$
+RewriteRule ^/~quux/foo/arc/.+ - [F]
+ |
+
+
+
+
+ Blocked Inline-Images
+
+
+
+- Description:
+
-
+Assume we have under http://www.quux-corp.de/~quux/ some pages with inlined
+GIF graphics. These graphics are nice, so others directly incorporate them via
+hyperlinks to their pages. We don't like this practice because it adds useless
+traffic to our server.
+
+
+ - Solution:
+
-
+While we cannot 100% protect the images from inclusion, we
+can at least restrict the cases where the browser sends
+a HTTP Referer header.
+
+
+RewriteCond %{HTTP_REFERER} !^$
+RewriteCond %{HTTP_REFERER} !^http://www.quux-corp.de/~quux/.*$ [NC]
+RewriteRule .*\.gif$ - [F]
+ |
+
+
+RewriteCond %{HTTP_REFERER} !^$
+RewriteCond %{HTTP_REFERER} !.*/foo-with-gif\.html$
+RewriteRule ^inlined-in-foo\.gif$ - [F]
+ |
+
+
+
+
+ Host Deny
+
+
+
+- Description:
+
-
+How can we forbid a list of externally configured hosts from using our server?
+
+
+ - Solution:
+
-
+
+For Apache >= 1.3b6:
+
+
+RewriteEngine on
+RewriteMap hosts-deny txt:/path/to/hosts.deny
+RewriteCond ${hosts-deny:%{REMOTE_HOST}|NOT-FOUND} !=NOT-FOUND [OR]
+RewriteCond ${hosts-deny:%{REMOTE_ADDR}|NOT-FOUND} !=NOT-FOUND
+RewriteRule ^/.* - [F]
+ |
+
+For Apache <= 1.3b6:
+
+
+RewriteEngine on
+RewriteMap hosts-deny txt:/path/to/hosts.deny
+RewriteRule ^/(.*)$ ${hosts-deny:%{REMOTE_HOST}|NOT-FOUND}/$1
+RewriteRule !^NOT-FOUND/.* - [F]
+RewriteRule ^NOT-FOUND/(.*)$ ${hosts-deny:%{REMOTE_ADDR}|NOT-FOUND}/$1
+RewriteRule !^NOT-FOUND/.* - [F]
+RewriteRule ^NOT-FOUND/(.*)$ /$1
+ |
+
+
+##
+## hosts.deny
+##
+## ATTENTION! This is a map, not a list, even when we treat it as such.
+## mod_rewrite parses it for key/value pairs, so at least a
+## dummy value "-" must be present for each entry.
+##
+
+193.102.180.41 -
+bsdti1.sdm.de -
+192.76.162.40 -
+ |
+
+
+
+
+ Proxy Deny
+
+
+
+- Description:
+
-
+How can we forbid a certain host or even a user of a special host from using
+the Apache proxy?
+
+
+ - Solution:
+
-
+We first have to make sure mod_rewrite is below(!) mod_proxy in the
+Configuration file when compiling the Apache webserver. This way it
+gets called _before_ mod_proxy. Then we configure the following for a
+host-dependend deny...
+
+
+RewriteCond %{REMOTE_HOST} ^badhost\.mydomain\.com$
+RewriteRule !^http://[^/.]\.mydomain.com.* - [F]
+ |
+
+...and this one for a user@host-dependend deny:
+
+
+RewriteCond %{REMOTE_IDENT}@%{REMOTE_HOST} ^badguy@badhost\.mydomain\.com$
+RewriteRule !^http://[^/.]\.mydomain.com.* - [F]
+ |
+
+
+
+
+ Special Authentication Variant
+
+
+
+- Description:
+
-
+Sometimes a very special authentication is needed, for instance a
+authentication which checks for a set of explicitly configured users. Only
+these should receive access and without explicit prompting (which would occur
+when using the Basic Auth via mod_access).
+
+
+ - Solution:
+
-
+We use a list of rewrite conditions to exclude all except our friends:
+
+
+RewriteCond %{REMOTE_IDENT}@%{REMOTE_HOST} !^friend1@client1.quux-corp\.com$
+RewriteCond %{REMOTE_IDENT}@%{REMOTE_HOST} !^friend2@client2.quux-corp\.com$
+RewriteCond %{REMOTE_IDENT}@%{REMOTE_HOST} !^friend3@client3.quux-corp\.com$
+RewriteRule ^/~quux/only-for-friends/ - [F]
+ |
+
+
+
+
+ Referer-based Deflector
+
+
+
+- Description:
+
-
+How can we program a flexible URL Deflector which acts on the "Referer" HTTP
+header and can be configured with as many referring pages as we like?
+
+
+ - Solution:
+
-
+Use the following really tricky ruleset...
+
+
+RewriteMap deflector txt:/path/to/deflector.map
+
+RewriteCond %{HTTP_REFERER} !=""
+RewriteCond ${deflector:%{HTTP_REFERER}} ^-$
+RewriteRule ^.* %{HTTP_REFERER} [R,L]
+
+RewriteCond %{HTTP_REFERER} !=""
+RewriteCond ${deflector:%{HTTP_REFERER}|NOT-FOUND} !=NOT-FOUND
+RewriteRule ^.* ${deflector:%{HTTP_REFERER}} [R,L]
+ |
+
+...
+in conjunction with a corresponding rewrite map:
+
+
+##
+## deflector.map
+##
+
+http://www.badguys.com/bad/index.html -
+http://www.badguys.com/bad/index2.html -
+http://www.badguys.com/bad/index3.html http://somewhere.com/
+ |
+
+
+This automatically redirects the request back to the referring page (when "-"
+is used as the value in the map) or to a specific URL (when an URL is
+specified in the map as the second argument).
+
+
+
+Other
+
+
+ External Rewriting Engine
+
+
+
+- Description:
+
-
+A FAQ: How can we solve the FOO/BAR/QUUX/etc. problem? There seems no solution
+by the use of mod_rewrite...
+
+
+ - Solution:
+
-
+Use an external rewrite map, i.e. a program which acts like a rewrite map. It
+is run once on startup of Apache receives the requested URLs on STDIN and has
+to put the resulting (usually rewritten) URL on STDOUT (same order!).
+
+
+RewriteEngine on
+RewriteMap quux-map prg:/path/to/map.quux.pl
+RewriteRule ^/~quux/(.*)$ /~quux/${quux-map:$1}
+ |
+
+
+#!/path/to/perl
+
+# disable buffered I/O which would lead
+# to deadloops for the Apache server
+$| = 1;
+
+# read URLs one per line from stdin and
+# generate substitution URL on stdout
+while (<>) {
+ s|^foo/|bar/|;
+ print $_;
+}
+ |
+
+
+This is a demonstration-only example and just rewrites all URLs
+/~quux/foo/... to /~quux/bar/.... Actually you can program
+whatever you like. But notice that while such maps can be used also by
+an average user, only the system administrator can define it.
+
+
+
+
+
+
+
diff --git a/docs/manual/mod/mod_auth_digest.html b/docs/manual/mod/mod_auth_digest.html
new file mode 100644
index 00000000000..35c7f0628e1
--- /dev/null
+++ b/docs/manual/mod/mod_auth_digest.html
@@ -0,0 +1,416 @@
+
+
+
+Apache module mod_auth_digest
+
+
+
+
+
+Module mod_auth_digest
+
+This module is contained in the mod_auth_digest.c file, and is
+not compiled in by default. It is only available in Apache 1.3.8 and
+later. It provides for user authentication using MD5 Digest
+Authentication.
+
+Note this is an updated version of mod_digest. However, it has not been
+extensively tested and is therefore marked experimental. If you use this
+module, you must make sure to not use mod_digest (because they
+share some of the same configuration directives).
+
+
+
+
+
+
+
+Syntax: AuthDigestFile filename
+Context: directory, .htaccess
+Override: AuthConfig
+Status: Base
+Module: mod_auth_digest
+
+The AuthDigestFile directive sets the name of a textual file containing
+the list of users and encoded passwords for digest authentication.
+Filename is the absolute path to the user file.
+
+ The digest file uses a special format. Files in this format can be
+created using the "htdigest" utility found in the support/ subdirectory of
+the Apache distribution.
+
+
+
+
+Syntax: AuthDigestGroupFile filename
+Context: directory, .htaccess
+Override: AuthConfig
+Status: Base
+Module: mod_auth_digest
+Compatibility: Available in Apache 1.3.8 and later
+
+The AuthDigestGroupFile directive sets the name of a textual file
+containing the list of groups and their members (user names).
+Filename is the absolute path to the group file.
+
+ Each line of the group file contains a groupname followed by a colon,
+followed by the member usernames separated by spaces. Example:
+ mygroup: bob joe anne
+Note that searching large text files is very inefficient.
+
+Security: make sure that the AuthGroupFile is stored outside the
+document tree of the web-server; do not put it in the directory
+that it protects. Otherwise, clients will be able to download the
+AuthGroupFile.
+
+
+
+
+Syntax: AuthDigestQop none | 1*{ auth | auth-int }
+Default: AuthDigestQop auth
+Context: directory, .htaccess
+Override: AuthConfig
+Status: Base
+Module: mod_auth_digest
+Compatibility: Available in Apache 1.3.8 and later
+
+The AuthDigestQop directive determines the quality-of-protection to use.
+auth will only do authentication (username/password);
+auth-int is authentication plus integrity checking (an MD5 hash
+of the entity is also computed and checked); none will cause the
+module to use the old RFC-2069 digest algorithm (which does not include
+integrity checking). Both auth and auth-int may be
+specified, in which the case the browser will choose which of these to
+use. none should only be used if the browser for some reason
+does not like the challenge it receives otherwise.
+
+ auth-int is not implemented yet.
+
+
+
+
+Syntax: AuthDigestNonceLifetime <time>
+Default: AuthDigestNonceLifetime 300
+Context: directory, .htaccess
+Override: AuthConfig
+Status: Base
+Module: mod_auth_digest
+Compatibility: Available in Apache 1.3.8 and later
+
+The AuthDigestNonceLifetime directive controls how long the server
+nonce is valid. When the client contacts the server using an expired
+nonce the server will send back a 401 with stale=true . If
+<time> is greater than 0 then it specifies the number of
+seconds the nonce is valid; this should probably never be set to less
+than 10 seconds. If <time> is less than 0 then the nonce
+never expires.
+
+
+
+
+
+Syntax: AuthDigestNonceFormat ???
+Default: AuthDigestNonceFormat ???
+Context: directory, .htaccess
+Override: AuthConfig
+Status: Base
+Module: mod_auth_digest
+Compatibility: Available in Apache 1.3.8 and later
+
+Not implemented yet.
+
+
+
+
+Syntax: AuthDigestNcCheck On/Off
+Default: AuthDigestNcCheck Off
+Context: server config
+Override: Not applicable
+Status: Base
+Module: mod_auth_digest
+Compatibility: Available in Apache 1.3.8 and later
+
+Not implemented yet.
+
+
+
+
+Syntax: AuthDigestAlgorithm MD5 | MD5-sess
+Default: AuthDigestAlgorithm MD5
+Context: directory, .htaccess
+Override: AuthConfig
+Status: Base
+Module: mod_auth_digest
+Compatibility: Available in Apache 1.3.8 and later
+
+The AuthDigestAlgorithm directive selects the algorithm used to calculate
+the challenge and response hashes.
+
+ MD5-sess is not correctly implemented yet.
+
+
+
+
+Syntax: AuthDigestDomain URI URI ...
+Context: directory, .htaccess
+Override: AuthConfig
+Status: Base
+Module: mod_auth_digest
+Compatibility: Available in Apache 1.3.8 and later
+
+The AuthDigestDomain directive allows you to specify one or more URIs
+which are in the same protection space (i.e. use the same realm and
+username/password info). The specified URIs are prefixes, i.e. the client
+will assume that all URIs "below" these are also protected by the same
+username/password. The URIs may be either absolute URIs (i.e. inluding a
+scheme, host, port, etc) or relative URIs.
+
+ This directive should always be specified and contain at least
+the (set of) root URI(s) for this space. Omiting to do so will cause the
+client to send the Authorization header for every request sent to
+this server. Apart from increasing the size of the request, it may also
+have a detrimental effect on performance if "AuthDigestNcCheck" is on.
+
+ The URIs specified can also point to different servers, in which case
+clients (which understand this) will then share username/password info
+across multiple servers without prompting the user each time.
+
+
+
+
+
+
+Using MD5 Digest authentication is very simple. Simply set up
+authentication normally, using "AuthType Digest" and "AuthDigestFile"
+instead of the normal "AuthType Basic" and "AuthUserFile"; also,
+replace any "AuthGroupFile" with "AuthDigestGroupFile". Then add a
+"AuthDigestDomain" directive containing at least the root URI(s) for
+this protection space. Example:
+
+
+ <Location /private/>
+ AuthType Digest
+ AuthName "private area"
+ AuthDigestDomain /private/ http://mirror.my.dom/private2/
+ AuthDigestFile /web/auth/.digest_pw
+ require valid-user
+ </Location>
+
+
+Note: MD5 authentication provides a more secure
+password system than Basic authentication, but only works with supporting
+browsers. As of this writing (July 1999), the only major browsers which
+support digest authentication are Internet Exploder 5.0 and
+Amaya. Therefore, we do not
+recommend using this feature on a large Internet site. However, for
+personal and intra-net use, where browser users can be controlled, it is
+ideal.
+
+
+
+
+
diff --git a/docs/manual/mod/mod_vhost_alias.html b/docs/manual/mod/mod_vhost_alias.html
new file mode 100644
index 00000000000..9b86a07143b
--- /dev/null
+++ b/docs/manual/mod/mod_vhost_alias.html
@@ -0,0 +1,311 @@
+
+
+
+Apache module mod_vhost_alias
+
+
+
+
+
+ ![[APACHE DOCUMENTATION]](../images/sub.gif)
+
+ Apache HTTP Server Version 1.3
+
+
+
+Module mod_vhost_alias
+
+
+This module is contained in the mod_vhost_alias.c file
+and is not compiled in by default. It should be mentioned near the
+start of the Configuration file so that it doesn't
+override the behaviour of other modules that do filename translation,
+e.g. mod_userdir and
+mod_alias . It provides
+support for dynamically configured mass
+virtual hosting.
+
+
+Directory Name Interpolation
+
+
+All the directives in this module interpolate a string into a
+pathname. The interpolated string (henceforth called the "name") may
+be either the server name (see the
+UseCanonicalName
+directive for details on how this is determined) or the IP address of
+the virtual host on the server in dotted-quad format. The
+interpolation is controlled by specifiers inspired by
+printf which have a number of formats:
+
+ %%
+ - insert a
%
+ %p
+ - insert the port number of the virtual host
+
%N.M
+ - insert (part of) the name
+
+
+
+
+N and M are used to specify substrings of
+the name. N selects from the dot-separated components of
+the name, and M selects characters within whatever
+N has selected. M is optional and defaults
+to zero if it isn't present; the dot must be present if and only if
+M is present. The interpretation is as follows:
+
+ 0
+ - the whole name
+
1
+ - the first part
+
2
+ - the second part
+
-1
+ - the last part
+
-2
+ - the penultimate part
+
2+
+ - the second and all subsequent parts
+
-2+
+ - the penultimate and all preceding parts
+
1+ and -1+
+ - the same as
0
+
+If N or M is greater than the number of
+parts available a single underscore is interpolated.
+
+
+Examples
+
+
+For simple name-based virtual hosts you might use the following
+directives in your server configuration file:
+
+ UseCanonicalName Off
+ VirtualDocumentRoot /usr/local/apache/vhosts/%0
+
+A request for http://www.example.com/directory/file.html
+will be satisfied by the file
+/usr/local/apache/vhosts/www.example.com/directory/file.html .
+
+
+
+For a very large number of virtual hosts it is a good idea to arrange
+the files to reduce the size of the vhosts directory. To
+do this you might use the following in your configuration file:
+
+ UseCanonicalName Off
+ VirtualDocumentRoot /usr/local/apache/vhosts/%3+/%2.1/%2.2/%2.3/%2
+
+A request for http://www.example.isp.com/directory/file.html
+will be satisfied by the file
+/usr/local/apache/isp.com/e/x/a/example/directory/file.html .
+A more even spread of files can be acheived by hashing from the end of
+the name, for example:
+
+ VirtualDocumentRoot /u/%3+/%2.-1/%2.-2/%2.-3/%2
+
+The example request would come from
+/usr/local/apache/vhosts/isp.com/e/l/p/example/directory/file.html .
+Alternatively you might use:
+
+ VirtualDocumentRoot /usr/local/apache/vhosts/%3+/%2.1/%2.2/%2.3/%2.4+
+
+The example request would come from
+/usr/local/apache/vhosts/isp.com/e/x/a/mple/directory/file.html .
+
+
+
+For IP-based virtual hosting you might use the following in your
+configuration file:
+
+ UseCanonicalName DNS
+ VirtualDocumentRootIP /usr/local/apache/vhost/%1/%2/%3/%4/docs
+ VirtualScriptAliasIP /usr/local/apache/vhost/%1/%2/%3/%4/cgi-bin
+
+A request for http://www.example.isp.com/directory/file.html
+would be satisfied by the file
+/usr/local/apache/10/20/30/40/docs/directory/file.html if
+the IP address of www.example.com were 10.20.30.40.
+A request for http://www.example.isp.com/cgi-bin/script.pl
+would be satisfied by executing the program
+/usr/local/apache/10/20/30/40/cgi-bin/script.pl .
+
+
+
+The LogFormat directives
+%V and %A are useful in conjunction with
+this module.
+
+
+
+
+Directives
+
+
+
+
+
+Syntax: VirtualDocumentRoot interpolated-directory
+Default: None
+Context: server config, virtual host
+Status: Extension
+Module: mod_vhost_alias
+Compatibility: VirtualDocumentRoot is only available in 1.3.5 and later.
+
+The VirtualDocumentRoot directive allows you to determine
+where Apache will find your documents based on the value of the server
+name. The result of expanding interpolated-directory is used
+as the root of the document tree in a similar manner to the
+DocumentRoot
+directive's argument. If interpolated-directory is
+none then VirtaulDocumentRoot is turned off.
+This directive cannot be used in the same context as
+VirtualDocumentRootIP .
+
+
+
+
+
+Syntax: VirtualDocumentRootIP interpolated-directory
+Default: None
+Context: server config, virtual host
+Status: Extension
+Module: mod_vhost_alias
+Compatibility: VirtualDocumentRootIP is only available in 1.3.5 and later.
+
+The VirtualDocumentRootIP directive is like the
+VirtualDocumentRoot directive,
+except that it uses the IP address of the server end of the connection
+instead of the server name.
+
+
+
+
+
+Syntax: VirtualScriptAlias interpolated-directory
+Default: None
+Context: server config, virtual host
+Status: Extension
+Module: mod_vhost_alias
+Compatibility: VirtualScriptAlias is only available in 1.3.5 and later.
+
+The VirtualScriptAlias directive allows you to determine
+where Apache will find CGI scripts in a similar manner to
+VirtualDocumentRoot
+does for other documents. It matches requests for URIs starting
+/cgi-bin/ , much like
+ScriptAlias /cgi-bin/
+would.
+
+
+
+
+
+Syntax: VirtualScriptAliasIP interpolated-directory
+Default: None
+Context: server config, virtual host
+Status: Extension
+Module: mod_vhost_alias
+Compatibility: VirtualScriptAliasIP is only available in 1.3.5 and later.
+
+The VirtualScriptAliasIP directibe is like the
+VirtualScriptAlias directive,
+except that it uses the IP address of the server end of the connection
+instead of the server name.
+
+
+
+
+ Apache HTTP Server Version 1.3
+
+
+
+
+
+
+
diff --git a/docs/manual/mpm.html b/docs/manual/mpm.html
new file mode 100644
index 00000000000..7521751bfe2
--- /dev/null
+++ b/docs/manual/mpm.html
@@ -0,0 +1,96 @@
+
+
+
+Available MPM's for Apache 2.0
+
+
+
+
+Apache 2.0 - Available MPM's
+Dated 15th January 2000
+Apache 2.0 has a new architecture that moves the processing of requests from the code server into a MultiProcessing Module (MPM). By selecting the MPM to use you can alter the way the server behaves. Additionally the introduction of the MPM's has led to platforms developing their own optimised modules. On some platforms there is no choice, whilst on others there are different options, each with differing processing models. This list aims to help you select a suitable MPM for your system.
+
+Platforms
+
+Unix
+
+
+MPM |
+Description |
+Maintainer |
+
+
+prefork |
+The prefork MPM reproduces the behaviour of Apache 1.3. |
+?? |
+
+
+mpmt_pthread |
+This MPM uses a multi-process, multi-threaded model to provide good scability and stability. |
+Manoj? |
+
+
+dexter |
+This is Manoj's plaything. It has a number of hybrid features that Manoj has been looking at to improve performance. |
+Manoj |
+
+
+
+Windows
+
+
+MPM |
+Description |
+Maintainer |
+
+
+winnt |
+The Windows MPM. This is mainly aimed at Windows NT. |
+Bill Stoddard |
+
+
+
+OS/2
+
+
+MPM |
+Description |
+Maintainer |
+
+
+spmt_os2 |
+Single process, multiple thread MPM for OS2. |
+Brian Havard |
+
+
+
+BeOS
+
+
+MPM |
+Description |
+Maintainer |
+
+
+mpmt_beos |
+Multi-threaded MPM for BeOS. This follows the mpmt_pthread model. |
+David Reid |
+
+
+
+
+David Reid, 15th January 2000
+
+
+
diff --git a/docs/manual/mpm.html.en b/docs/manual/mpm.html.en
new file mode 100644
index 00000000000..7521751bfe2
--- /dev/null
+++ b/docs/manual/mpm.html.en
@@ -0,0 +1,96 @@
+
+
+
+Available MPM's for Apache 2.0
+
+
+
+
+Apache 2.0 - Available MPM's
+Dated 15th January 2000
+Apache 2.0 has a new architecture that moves the processing of requests from the code server into a MultiProcessing Module (MPM). By selecting the MPM to use you can alter the way the server behaves. Additionally the introduction of the MPM's has led to platforms developing their own optimised modules. On some platforms there is no choice, whilst on others there are different options, each with differing processing models. This list aims to help you select a suitable MPM for your system.
+
+Platforms
+
+Unix
+
+
+MPM |
+Description |
+Maintainer |
+
+
+prefork |
+The prefork MPM reproduces the behaviour of Apache 1.3. |
+?? |
+
+
+mpmt_pthread |
+This MPM uses a multi-process, multi-threaded model to provide good scability and stability. |
+Manoj? |
+
+
+dexter |
+This is Manoj's plaything. It has a number of hybrid features that Manoj has been looking at to improve performance. |
+Manoj |
+
+
+
+Windows
+
+
+MPM |
+Description |
+Maintainer |
+
+
+winnt |
+The Windows MPM. This is mainly aimed at Windows NT. |
+Bill Stoddard |
+
+
+
+OS/2
+
+
+MPM |
+Description |
+Maintainer |
+
+
+spmt_os2 |
+Single process, multiple thread MPM for OS2. |
+Brian Havard |
+
+
+
+BeOS
+
+
+MPM |
+Description |
+Maintainer |
+
+
+mpmt_beos |
+Multi-threaded MPM for BeOS. This follows the mpmt_pthread model. |
+David Reid |
+
+
+
+
+David Reid, 15th January 2000
+
+
+
diff --git a/docs/manual/new_features_2_0.html b/docs/manual/new_features_2_0.html
new file mode 100644
index 00000000000..325696f453c
--- /dev/null
+++ b/docs/manual/new_features_2_0.html
@@ -0,0 +1,50 @@
+
+
+New features with Apache 2.0
+
+
+
+
+
+Overview of New Features in Apache 2.0
+
+Enhancements: Core |
+
+
+
+
+
+
+- Unix Threading
+
- On Unix systems with POSIX threads support, Apache can now run in a
+ hybrid multiprocess, multithreaded mode. This should improve
+ scalability.
+
+
- New Build System
+
- The build system has been rewritten from scratch to be based on
+ autoconf and libtool. This makes Apache's configuration system more
+ similar to that of other packages.
+
+
- Multiprotocol Support
+
- Apache now has some of the infrastructure in place to support serving
+ multiple protocols. mod_echo has been written as an example.
+
+
- Better support for non-Unix platforms
+
- Apache 2.0 should be faster and more stable on non-Unix platforms such
+ as BeOS, OS/2, and Windows. With the introduction of platform-specific
+ multiprocessing modules and the Apache Portable Runtime, these
+ platforms can now avoid using POSIX-emulation functions that are
+ sometimes buggy and always hurt performance.
+
+
- New API
+
- The API for modules has changed significantly for 2.0. Many of the
+ module-ordering problems from 1.3 should be gone, since 2.0 does much
+ of this automatically now. Also, new calls have been added that should
+ allow modules to do more without requiring patching of the core Apache
+ server.
+
+
+
+
+
diff --git a/docs/manual/new_features_2_0.html.en b/docs/manual/new_features_2_0.html.en
new file mode 100644
index 00000000000..325696f453c
--- /dev/null
+++ b/docs/manual/new_features_2_0.html.en
@@ -0,0 +1,50 @@
+
+
+New features with Apache 2.0
+
+
+
+
+
+
Overview of New Features in Apache 2.0
+
+Enhancements: Core |
+
+
+
+
+
+
+- Unix Threading
+
- On Unix systems with POSIX threads support, Apache can now run in a
+ hybrid multiprocess, multithreaded mode. This should improve
+ scalability.
+
+
- New Build System
+
- The build system has been rewritten from scratch to be based on
+ autoconf and libtool. This makes Apache's configuration system more
+ similar to that of other packages.
+
+
- Multiprotocol Support
+
- Apache now has some of the infrastructure in place to support serving
+ multiple protocols. mod_echo has been written as an example.
+
+
- Better support for non-Unix platforms
+
- Apache 2.0 should be faster and more stable on non-Unix platforms such
+ as BeOS, OS/2, and Windows. With the introduction of platform-specific
+ multiprocessing modules and the Apache Portable Runtime, these
+ platforms can now avoid using POSIX-emulation functions that are
+ sometimes buggy and always hurt performance.
+
+
- New API
+
- The API for modules has changed significantly for 2.0. Many of the
+ module-ordering problems from 1.3 should be gone, since 2.0 does much
+ of this automatically now. Also, new calls have been added that should
+ allow modules to do more without requiring patching of the core Apache
+ server.
+
+
+
+
+
diff --git a/docs/manual/platform/netware.html b/docs/manual/platform/netware.html
new file mode 100644
index 00000000000..8add778b5f1
--- /dev/null
+++ b/docs/manual/platform/netware.html
@@ -0,0 +1,278 @@
+
+
+
+Using Apache with Novell NetWare 5
+
+
+
+
+
+
+
Using Apache With Novell NetWare 5
+
+This document explains how to install, configure and run
+ Apache 1.3 under Novell NetWare 5. Please note that at
+ this time, NetWare support is entirely experimental, and is
+ recommended only for experienced users. The Apache Group does not
+ guarantee that this software will work as documented, or even at
+ all. If you find any bugs, or wish to contribute in other ways, please
+ use our bug reporting
+ page.
+
+Warning: Apache on NetWare has not yet been optimized for performance.
+Apache still performs best, and is most reliable on Unix platforms. Over
+time we will improve NetWare performance. Folks doing comparative reviews
+of webserver performance are asked to compare against Apache
+on a Unix platform such as Solaris, FreeBSD, or Linux.
+
+
+
+Most of this document assumes that you are installing Apache from a
+binary distribution. If you want to compile Apache yourself (possibly
+to help with development, or to track down bugs), see the section on
+Compiling Apache for NetWare below.
+
+
+
+
+
+
+
+
+
+Apache 1.3 is designed to run on NetWare 5.0 and 5.1.
+
+
+If running on NetWare 5.0 you must install Service Pack 4.
+
+
+
+
+Service pack 4 is available here.
+
+
+
+Information on the latest version of Apache can be found on the
+Apache web server at http://www.apache.org/. This will
+list the current release, any more recent alpha or beta-test releases,
+together with details of mirror web and anonymous ftp sites.
+
+
+
+
+There is no Apache install program for NetWare currently. You will need
+to compile apache and copy the files over to the server manually. An
+install program will be posted at a later date.
+
+Follow these steps to install Apache on NetWare (assuming you will install to sys:/apache):
+
+
+ - Create a directory called
Apache on a NetWare volume
+ - Copy Apache.nlm, Apachec.nlm, htdigest.nlm, and htpasswd.nlm to sys:/apache
+
- Create a directory under
sys:/Apache called conf
+ - Copy all the *.conf-dist-nw files to the
sys:/apache/conf directory
+ and rename them all as *.conf files
+ - Copy the mime.types and magic files to sys:/apache/conf directory
+
- Copy all files and subdirectories of \apache-1.3\htdocs to sys:/apache/htdocs and
+ rename the proper index file (index.html.en) to index.html
+
- Copy all files and subdirectories in \apache-1.3\icons to sys:/apache/icons
+
- Create the directory sys:/apache/logs on the server
+
- Create the directory sys:/apache/cgi-bin on the server
+
- Create the directory sys:/apache/modules and copy all nlm modules built into the
+ modules directory
+
- Edit the httpd.conf file setting ServerRoot and ServerName to reflect your correct
+ server settings
+
- Add
sys:/apache to the search path. EXAMPLE: search add sys:\apache
+
+
+Apache may be installed to other volumes besides the default sys volume.
+
+
+
+To start Apache just type apache at the console. This
+will load apache in the OS address space. If you prefer to load
+Apache in a protected address space you may specify the address space
+with the load statement as follows:
+
+
+ load address space = apache apache
+
+
+This will load Apache into an address space called apache. Running multiple instances
+of Apache concurrently on NetWare is possible by loading each instance into its own
+protected address space.
+
+
+After starting Apache it will be listening to port 80 (unless you
+changed the Port, Listen or
+BindAddress directives in the configuration files).
+To connect to the server and access the default page, launch a browser
+and enter the server's name or address.
+
+This should respond with a welcome page, and a link to the Apache
+manual. If nothing happens or you get an error, look in the
+error_log file in the logs directory.
+
+
+
+Once your basic installation is working, you should configure it
+properly by editing the files in the conf directory.
+
+
+To unload Apache running in the OS address space just type the
+following at the console:
+
+ unload apache
+
+If apache is running in a protected address space specify the
+address space in the unload statement:
+
+ unload address space = apache apache
+
+
+
+When working with Apache it is important to know how it will find the
+configuration files. You can specify a configuration file on the command line
+in two ways:
+
+
+- -f specifies a path to a particular configuration file
+
+ apache -f "vol:/my server/conf/my.conf"
+ apache -f test/test.conf
+
+In these cases, the proper ServerRoot should be set in the configuration file.
+
+
+
+If you don't specify a configuration file name with -f, Apache will
+use the file name compiled into the server, usually "conf/httpd.conf". Invoking
+Apache with the -V switch will display this value labeled as SERVER_CONFIG_FILE.
+Apache will then determine its ServerRoot by trying the following, in this order:
+
+
+- A ServerRoot directive via a -C switch.
+
- The -d switch on the command line.
+
- Current working directory
+
- The server root compiled into the server.
+
+
+
+The server root compiled into the server is usually "sys:/apache".
+invoking apache with the -V switch will display this value
+labeled as HTTPD_ROOT.
+
+
+
+Apache is configured by files in the conf
+directory. These are the same as files used to configure the Unix
+version, but there are a few different directives for Apache on
+NetWare. See the Apache documentation for all the
+available directives.
+
+
+
+The main differences in Apache for NetWare are:
+
+
+ Because Apache for NetWare is multithreaded, it does not use a
+ separate process for each request, as Apache does with
+ Unix. Instead there are only threads running: a parent thread, and
+ a child which handles the requests. Within the child each request is
+ handled by a separate thread.
+
+
+ So the "process"-management directives are different:
+ MaxRequestsPerChild
+ - Like the Unix directive, this controls how many requests a
+ process will serve before exiting. However, unlike Unix, a
+ process serves all the requests at once, not just one, so if
+ this is set, it is recommended that a very high number is
+ used. The recommended default, MaxRequestsPerChild
+ 0 , does not cause the process to ever exit.
+ ThreadsPerChild -
+ This directive is new, and tells the server how many threads it
+ should use. This is the maximum number of connections the server
+ can handle at once; be sure and set this number high enough for
+ your site if you get a lot of hits. The recommended default is
+ ThreadsPerChild 50 .
+ ThreadStackSize -
+ This directive tells the server what size of stack to use for
+ the individual threads. The recommended default is
+ ThreadStackSize 65536 .
+
+ The directives that accept filenames as arguments now must use
+ NetWare filenames instead of Unix ones. However, because Apache
+ uses Unix-style names internally, you must use forward slashes, not
+ backslashes. Volumes can be used; if omitted, the drive with the
+ Apache executable will be assumed.
+ Apache for NetWare contains the ability to load modules at runtime,
+ without recompiling the server. If Apache is compiled normally, it
+ will install a number of optional modules in the
+ \Apache\modules directory. To activate these, or other
+ modules, the new LoadModule
+ directive must be used. For example, to active the status module,
+ use the following (in addition to the status-activating directives
+ in access.conf ):
+
+ LoadModule status_module modules/status
+
+ Information on creating loadable
+ modules is also available.
+
+
+
+
+Compiling Apache requires MetroWerks CodeWarrior 5 to be properly
+ installed.
+
+ First, unpack the Apache distribution into an appropriate
+ directory. Then go to the src subdirectory of the Apache
+ distribution and unzip ApacheNW.mcp.gz . You may use a
+ recent version of WinZip to accomplish this or gzip for Windows. The main
+ Metrowerks project file for Apache (ApacheNW.mcp) is now ready
+ to use. Just double click on it from within explorer and it should
+ automatically launch MetroWerks CodeWarrior.
+
+
+All major pieces of Apache may be built using the ApacheNW.mcp project
+ file. This includes modules such as status, info, and proxy. In addition,
+ the following project files have been provided as well:
+
+ /apache-1.3/src/support/htpasswd.mcp.gz
+ /apache-1.3/src/support/htdigest.mcp.gz
+
+
+
+htpasswd.mcp.gz and htdigest.mcp.gz will also need
+to be unzipped before they can be used with MetroWerks CodeWarrior.
+
+Once Apache has been compiled, it needs to be installed in its server
+ root directory. The default is the sys:/Apache
+ directory.
+
+Before running the server you must fill out the conf directory.
+Copy the *.conf-dist-nw from the distribution conf directory
+and rename *.conf. Edit the ServerRoot entries to your
+actual server root (for example "sys:/apache"). Copy over
+the conf/magic and conf/mime.types files as well.
+
+
+
+
+
diff --git a/docs/manual/platform/win_compiling.html b/docs/manual/platform/win_compiling.html
new file mode 100644
index 00000000000..54970ea86d0
--- /dev/null
+++ b/docs/manual/platform/win_compiling.html
@@ -0,0 +1,120 @@
+
+
+
+Compiling Apache for Microsoft Windows
+
+
+
+
+
+
+
+
+
+Using Apache with Microsoft Windows
+
+
+
+
+
+
+Compiling Apache for Microsoft Windows
+
+There are many important points before you begin compiling Apache.
+ See Using Apache with Microsoft Windows
+ before you begin.
+
+Compiling Apache requires Microsoft Visual C++ 5.0 (or later) to be
+ properly installed. It is easiest to compile with the command-line tools
+ (nmake, etc...). Consult the VC++ manual to determine how to install
+ them.
+
+First, unpack the Apache distribution into an appropriate
+ directory. Open a command-line prompt, and change to the
+ src subdirectory of the Apache distribution.
+
+The master Apache makefile instructions are contained in the
+ Makefile.win file. To compile Apache on Windows, simply
+ use one of the following commands:
+
+nmake /f Makefile.win _apacher (release build)
+nmake /f Makefile.win _apached (debug build)
+
+
+These will both compile Apache. The latter will include debugging
+ information in the resulting files, making it easier to find bugs and
+ track down problems.
+
+Apache can also be compiled using VC++'s Visual Studio development
+ environment. Although compiling Apache in this manner is not as
+ simple, it makes it possible to easily modify the Apache source, or
+ to compile Apache if the command-line tools are not installed.
+ Project files (.DSP ) are included for each of the
+ portions of Apache. To build Apache from the these projects files
+ you will need to build the following projects in this order:
+ This needs updating for Apache 2.0
+
+ os\win32\ApacheOS.dsp
+ regex\regex.dsp
+ ap\ap.dsp
+ main\gen_uri_delims.dsp
+ main\gen_test_char.dsp
+ ApacheCore.dsp
+ Apache.dsp
+
+
+ In addition, the src\os\win32 subdirectory contains
+ project files for the optional modules (see below).
+
+Once Apache has been compiled, it needs to be installed in its server
+ root directory. The default is the \Apache
+ directory, on the current hard drive.
+
+To install the files into the \Apache directory
+ automatically, use one the following nmake commands (see above):
+
+nmake /f Makefile.win installr INSTDIR=dir
+ (for release build)
+nmake /f Makefile.win installd INSTDIR=dir
+ (for debug build)
+
+
+The dir argument to INSTDIR gives the installation directory; it can
+be omitted if Apache is to be installed into \Apache.
+
+This will install the following:
+
+
+ dir\Apache.exe - Apache executable
+ dir\ApacheCore.dll - Main Apache shared library
+ dir\modules\ApacheModule*.dll - Optional Apache
+ modules (7 files)
+ dir\conf - Empty configuration directory
+ dir\logs - Empty logging directory
+
+
+If you do not have nmake, or wish to install in a different directory,
+ be sure to use a similar naming scheme.
+
+
+Before running the server you must fill out the conf directory.
+Copy the *.conf-dist-win from the distribution conf directory
+and rename *.conf. Edit the @@ServerRoot@@ entries to your
+actual server root (for example "C:\apache"). Copy over
+the conf/magic and conf/mime.types files as well.
+
+
+
+
diff --git a/emacs-style b/emacs-style
new file mode 100644
index 00000000000..a0f16e2209d
--- /dev/null
+++ b/emacs-style
@@ -0,0 +1,9 @@
+(add-hook 'c-mode-hook
+ (function (lambda ()
+ (c-set-offset 'inclass' ++)
+ (c-set-offset 'defun-block-intro' ++)
+ (c-set-offset 'statement-block-intro' ++)
+ (c-set-offset 'substatement' ++)
+ (c-set-offset 'brace-list-intro' ++)
+ )))
+(setq c++-mode-hook c-mode-hook)
diff --git a/include/.cvsignore b/include/.cvsignore
new file mode 100644
index 00000000000..49eae948bd5
--- /dev/null
+++ b/include/.cvsignore
@@ -0,0 +1 @@
+ap_config_auto.h
diff --git a/include/.indent.pro b/include/.indent.pro
new file mode 100644
index 00000000000..a9fbe9f9a1f
--- /dev/null
+++ b/include/.indent.pro
@@ -0,0 +1,54 @@
+-i4 -npsl -di0 -br -nce -d0 -cli0 -npcs -nfc1
+-TBUFF
+-TFILE
+-TTRANS
+-TUINT4
+-T_trans
+-Tallow_options_t
+-Tapache_sfio
+-Tarray_header
+-Tbool_int
+-Tbuf_area
+-Tbuff_struct
+-Tbuffy
+-Tcmd_how
+-Tcmd_parms
+-Tcommand_rec
+-Tcommand_struct
+-Tconn_rec
+-Tcore_dir_config
+-Tcore_server_config
+-Tdir_maker_func
+-Tevent
+-Tglobals_s
+-Thandler_func
+-Thandler_rec
+-Tjoblist_s
+-Tlisten_rec
+-Tmerger_func
+-Tmode_t
+-Tmodule
+-Tmodule_struct
+-Tmutex
+-Tn_long
+-Tother_child_rec
+-Toverrides_t
+-Tparent_score
+-Tpid_t
+-Tpiped_log
+-Tpool
+-Trequest_rec
+-Trequire_line
+-Trlim_t
+-Tscoreboard
+-Tsemaphore
+-Tserver_addr_rec
+-Tserver_rec
+-Tserver_rec_chain
+-Tshort_score
+-Ttable
+-Ttable_entry
+-Tthread
+-Tu_wide_int
+-Tvtime_t
+-Twide_int
diff --git a/include/ap_config.h b/include/ap_config.h
new file mode 100644
index 00000000000..e7219cf892e
--- /dev/null
+++ b/include/ap_config.h
@@ -0,0 +1,1394 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+#ifndef AP_CONFIG_H
+#define AP_CONFIG_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * ap_config.h: system-dependant #defines and includes...
+ * See PORTING for a listing of what they mean
+ */
+
+#include "ap_mmn.h" /* MODULE_MAGIC_NUMBER_ */
+
+/*
+ * Support for platform dependent autogenerated defines
+ */
+#ifndef WIN32
+#include "ap_config_auto.h"
+#else
+/* not available under WIN32, so provide important entries manually */
+#undef HAVE_UNISTD_H
+#endif
+
+/* Have to include sys/stat.h before ../os/win32/os.h so we can override
+stat() properly */
+#include
+#include
+
+/* So that we can use inline on some critical functions, and use
+ * GNUC attributes (such as to get -Wall warnings for printf-like
+ * functions). Only do this in gcc 2.7 or later ... it may work
+ * on earlier stuff, but why chance it.
+ *
+ * We've since discovered that the gcc shipped with NeXT systems
+ * as "cc" is completely broken. It claims to be __GNUC__ and so
+ * on, but it doesn't implement half of the things that __GNUC__
+ * means. In particular it's missing inline and the __attribute__
+ * stuff. So we hack around it. PR#1613. -djg
+ */
+#if !defined(__GNUC__) || __GNUC__ < 2 || \
+ (__GNUC__ == 2 && __GNUC_MINOR__ < 7) ||\
+ defined(NEXT)
+#define ap_inline
+#define __attribute__(__x)
+#define ENUM_BITFIELD(e,n,w) signed int n : w
+#else
+#define ap_inline __inline__
+#define USE_GNU_INLINE
+#define ENUM_BITFIELD(e,n,w) e n : w
+#endif
+
+#ifdef WIN32
+/* include process.h first so we can override spawn[lv]e* properly */
+#include
+#include "../os/win32/os.h"
+#else
+#include "os.h"
+#endif
+
+#if !defined(QNX) && !defined(MPE) && !defined(WIN32) && !defined(TPF)
+#include
+#endif
+
+/* Define one of these according to your system. */
+#if defined(MINT)
+typedef int rlim_t;
+#define JMP_BUF sigjmp_buf
+#define NO_LONG_DOUBLE
+#define USE_FLOCK_SERIALIZED_ACCEPT
+#define _BSD_SOURCE
+#define EAGAIN EWOULDBLOCK
+int initgroups (char *, int);
+char *crypt (const char *pw, const char *salt);
+int gethostname (char *name, int namelen);
+
+#elif defined(MPE)
+#include
+#define NO_SETSID
+#define NO_KILLPG
+#define NO_WRITEV
+#define HAVE_SHMGET 1
+#define USE_SHMGET_SCOREBOARD
+#define SHM_R 0400 /* Read permission */
+#define SHM_W 0200 /* Write permission */
+#define NEED_INITGROUPS
+#define NEED_STRCASECMP
+#define NEED_STRDUP
+#define NEED_STRNCASECMP
+extern void GETPRIVMODE();
+extern void GETUSERMODE();
+extern char *inet_ntoa();
+#define NO_SLACK
+#define NO_GETTIMEOFDAY
+#define S_IEXEC S_IXUSR
+#define S_IREAD S_IRUSR
+#define S_IWRITE S_IWUSR
+#define PF_INET AF_INET
+
+#elif defined(SUNOS4)
+#define HAVE_GMTOFF 1
+#undef NO_KILLPG
+#undef NO_SETSID
+char *crypt(const char *pw, const char *salt);
+char *mktemp(char *template);
+#define HAVE_MMAP 1
+#define USE_MMAP_SCOREBOARD
+#define USE_MMAP_FILES
+#include
+#define NEED_STRERROR
+typedef int rlim_t;
+#define memmove(a,b,c) bcopy(b,a,c)
+#define NO_LINGCLOSE
+#define USE_FLOCK_SERIALIZED_ACCEPT
+#define NEED_DIFFTIME
+#define HAVE_SYSLOG 1
+
+#elif defined(SOLARIS2)
+#undef HAVE_GMTOFF
+#define NO_KILLPG
+#undef NO_SETSID
+#define bzero(a,b) memset(a,0,b)
+#if !defined(USE_SYSVSEM_SERIALIZED_ACCEPT) && \
+ !defined(USE_PTHREAD_SERIALIZED_ACCEPT)
+#define USE_FCNTL_SERIALIZED_ACCEPT
+#endif
+#define NEED_UNION_SEMUN
+#define HAVE_MMAP 1
+#define USE_MMAP_SCOREBOARD
+#define USE_MMAP_FILES
+int gethostname(char *name, int namelen);
+#define HAVE_SYSLOG 1
+#define SYS_SIGLIST _sys_siglist
+
+#elif defined(IRIX)
+#undef HAVE_GMTOFF
+/* IRIX has killpg, but it's only in _BSD_COMPAT, so don't use it in case
+ * there's some weird conflict with non-BSD signals */
+#define NO_KILLPG
+#undef NO_SETSID
+#if !defined(USE_FLOCK_SERIALIZED_ACCEPT) && \
+ !defined(USE_USLOCK_SERIALIZED_ACCEPT) && \
+ !defined(USE_SYSVSEM_SERIALIZED_ACCEPT)
+#define USE_FCNTL_SERIALIZED_ACCEPT
+#endif
+#define HAVE_SHMGET 1
+#define USE_SHMGET_SCOREBOARD
+#define HAVE_MMAP 1
+#define USE_MMAP_FILES
+#define NO_LONG_DOUBLE
+#define NO_LINGCLOSE
+#define HAVE_SYSLOG 1
+
+#elif defined(HIUX)
+#undef HAVE_GMTOFF
+#define NO_KILLPG
+#undef NO_SETSID
+#ifndef _HIUX_SOURCE
+#define _HIUX_SOURCE
+#endif
+#define HAVE_SHMGET 1
+#define USE_SHMGET_SCOREBOARD
+#define SELECT_NEEDS_CAST
+#define HAVE_SYSLOG 1
+
+#elif defined(HPUX) || defined(HPUX10)
+#undef HAVE_GMTOFF
+#define NO_KILLPG
+#undef NO_SETSID
+#define USE_FCNTL_SERIALIZED_ACCEPT
+#ifndef _HPUX_SOURCE
+#define _HPUX_SOURCE
+#endif
+#define HAVE_SHMGET 1
+#define USE_SHMGET_SCOREBOARD
+#define HAVE_SYSLOG 1
+#ifndef HPUX10
+#define SELECT_NEEDS_CAST
+typedef int rlim_t;
+#endif
+
+#elif defined(HPUX11)
+#ifndef _HPUX_SOURCE
+#define _HPUX_SOURCE
+#endif
+#define HAVE_SHMGET
+#define USE_SHMGET_SCOREBOARD
+#undef HAVE_GMTOFF
+#define USE_FCNTL_SERIALIZED_ACCEPT
+/* feeling brave? want to try using POSIX mutexes? */
+/* #define HAVE_MMAP */
+/* #define USE_MMAP_SCOREBOARD */
+/* #define USE_MMAP_FILES */
+/* #define USE_PTHREAD_SERIALIZED_ACCEPT */
+#define NO_KILLPG
+#undef NO_SETSID
+#define HAVE_SYSLOG
+
+#elif defined(AIX)
+#undef HAVE_GMTOFF
+#undef NO_KILLPG
+#undef NO_SETSID
+#ifndef __ps2__
+#define HAVE_MMAP 1
+#define USE_MMAP_SCOREBOARD
+#define USE_MMAP_FILES
+#define HAVE_SYSLOG 1
+#ifndef DEFAULT_GROUP
+#define DEFAULT_GROUP "nobody"
+#endif
+#endif
+#ifndef DEFAULT_USER
+#define DEFAULT_USER "nobody"
+#endif
+#ifdef NEED_RLIM_T
+typedef int rlim_t;
+#endif
+#define USE_FCNTL_SERIALIZED_ACCEPT
+#ifdef USEBCOPY
+#define memmove(a,b,c) bcopy(b,a,c)
+#endif
+#if AIX >= 42
+#define NET_SIZE_T size_t
+#endif
+
+#elif defined(ULTRIX)
+/* we don't want to use sys/resource.h under
+ Ultrix although this header exists. */
+#undef HAVE_SYS_RESOURCE_H
+#define HAVE_GMTOFF 1
+#undef NO_KILLPG
+#undef NO_SETSID
+#define ULTRIX_BRAIN_DEATH
+#define NEED_STRDUP
+/* If you have Ultrix 4.3, and are using cc, const is broken */
+#ifndef __ultrix__ /* Hack to check for pre-Ultrix 4.4 cc */
+#define const /* Not implemented */
+#endif
+
+#elif defined(OSF1)
+#define HAVE_GMTOFF 1
+#undef NO_KILLPG
+#undef NO_SETSID
+#define HAVE_MMAP 1
+#define USE_MMAP_SCOREBOARD
+#define USE_MMAP_FILES
+#define NO_LONG_DOUBLE
+#define HAVE_SYSLOG 1
+#define USE_FLOCK_SERIALIZED_ACCEPT
+#define SINGLE_LISTEN_UNSERIALIZED_ACCEPT
+
+#elif defined(PARAGON)
+#define HAVE_GMTOFF 1
+#undef NO_KILLPG
+#undef NO_SETSID
+#define HAVE_MMAP 1
+#define USE_MMAP_SCOREBOARD
+#define USE_MMAP_FILES
+#define NO_LONG_DOUBLE
+#define HAVE_SYSLOG 1
+typedef int rlim_t;
+
+#elif defined(SEQUENT)
+#define DEFAULT_USER "nobody"
+#define DEFAULT_GROUP "nobody"
+#define NO_SHMGET 1
+#define HAVE_MMAP 1
+#define HAVE_SYSLOG 1
+#define USE_MMAP_FILES 1
+#define USE_MMAP_SCOREBOARD 1
+#define USE_FCNTL_SERIALIZED_ACCEPT 1
+#define JMP_BUF sigjmp_buf
+#undef NO_SETSID
+#if SEQUENT < 40
+typedef int rlim_t;
+#define NO_GETTIMEOFDAY
+#undef HAVE_SYS_RESOURCE_H /* exists but does not provide *rlimit funcs */
+#include
+#endif
+#if SEQUENT < 42
+#define NEED_STRCASECMP
+#define NEED_STRNCASECMP
+#endif
+#if SEQUENT < 44
+#define NO_KILLPG 1
+#define NET_SIZE_T int
+#endif
+#if SEQUENT >= 44
+#undef NO_KILLPG
+#define NET_SIZE_T size_t
+#endif
+
+#elif defined(NEXT)
+typedef unsigned short mode_t;
+#define HAVE_GMTOFF 1
+#undef NO_KILLPG
+#define NO_SETSID
+#define NEED_STRDUP
+#define NO_LINGCLOSE
+#undef _POSIX_SOURCE
+#ifndef FD_CLOEXEC
+#define FD_CLOEXEC 1
+#endif
+#ifndef S_ISDIR
+#define S_ISDIR(m) (((m)&(S_IFMT)) == (S_IFDIR))
+#endif
+#ifndef S_ISREG
+#define S_ISREG(m) (((m)&(S_IFMT)) == (S_IFREG))
+#endif
+#ifndef S_IXUSR
+#define S_IXUSR 00100
+#endif
+#ifndef S_IRGRP
+#define S_IRGRP 00040
+#endif
+#ifndef S_IXGRP
+#define S_IXGRP 00010
+#endif
+#ifndef S_IROTH
+#define S_IROTH 00004
+#endif
+#ifndef S_IXOTH
+#define S_IXOTH 00001
+#endif
+#ifndef S_IRUSR
+#define S_IRUSR S_IREAD
+#endif
+#ifndef S_IWUSR
+#define S_IWUSR S_IWRITE
+#endif
+#ifndef S_IWGRP
+#define S_IWGRP 000020
+#endif
+#ifndef S_IWOTH
+#define S_IWOTH 000002
+#endif
+
+#define STDIN_FILENO 0
+#define STDOUT_FILENO 1
+#define STDERR_FILENO 2
+
+/* PR#2293 fix */
+#define ap_wait_t union wait
+#define waitpid(a,b,c) wait4((a) == -1 ? 0 : (a),(union wait *)(b),c,NULL)
+#define WEXITSTATUS(status) (int)( WIFEXITED(status) ? ( (status).w_retcode ) : -1)
+#define WTERMSIG(status) (int)( (status).w_termsig )
+
+typedef int pid_t;
+#define USE_LONGJMP
+#define NO_USE_SIGACTION
+#define HAVE_SYSLOG 1
+
+#if defined(__DYNAMIC__)
+#define HAVE_DYLD
+#define DYLD_CANT_UNLOAD
+#endif
+
+#elif defined(MAC_OS) || defined(MAC_OS_X_SERVER) /* Mac OS (>= 10.0) and Mac OS X Server (<= 5.x) */
+#undef PLATFORM
+#ifdef MAC_OS_X_SERVER
+#define PLATFORM "Mac OS X Server"
+#else
+#define PLATFORM "Mac OS"
+#endif
+#define HAVE_DYLD
+#ifdef MAC_OS_X_SERVER
+#define DYLD_CANT_UNLOAD
+#endif /* MAC_OS_X_SERVER */
+#define HAVE_GMTOFF
+#define HAVE_MMAP
+#define USE_MMAP_FILES
+#define USE_MMAP_SCOREBOARD
+#ifdef MAC_OS_X_SERVER
+#define MAP_TMPFILE
+#endif /* MAC_OS_X_SERVER */
+#define HAVE_RESOURCE
+#define HAVE_SNPRINTF
+#define JMP_BUF jmp_buf
+#define USE_LONGJMP
+#define USE_FLOCK_SERIALIZED_ACCEPT
+#define SINGLE_LISTEN_UNSERIALIZED_ACCEPT
+/*
+ * If you are using APACI, (you probably should be on Mac OS) these
+ * values are set at configure time.
+ */
+#ifndef HTTPD_ROOT
+#define HTTPD_ROOT "/Local/Library/WebServer"
+#endif
+#ifndef DOCUMENT_LOCATION
+#define DOCUMENT_LOCATION HTTPD_ROOT "/Documents"
+#endif
+#ifndef DEFAULT_XFERLOG
+#define DEFAULT_XFERLOG "Logs/Access"
+#endif
+#ifndef DEFAULT_ERRORLOG
+#define DEFAULT_ERRORLOG "Logs/Errors"
+#endif
+#ifndef DEFAULT_PIDLOG
+#define DEFAULT_PIDLOG "Logs/Process"
+#endif
+#ifndef DEFAULT_SCOREBOARD
+#define DEFAULT_SCOREBOARD "Logs/Status"
+#endif
+#ifndef DEFAULT_LOCKFILE
+#define DEFAULT_LOCKFILE "Logs/Lock"
+#endif
+#ifndef SERVER_CONFIG_FILE
+#define SERVER_CONFIG_FILE "Configuration/Server"
+#endif
+#ifndef RESOURCE_CONFIG_FILE
+#define RESOURCE_CONFIG_FILE "Configuration/Resources"
+#endif
+#ifndef TYPES_CONFIG_FILE
+#define TYPES_CONFIG_FILE "Configuration/MIME"
+#endif
+#ifndef ACCESS_CONFIG_FILE
+#define ACCESS_CONFIG_FILE "Configuration/Access"
+#endif
+#ifndef DEFAULT_USER_DIR
+#define DEFAULT_USER_DIR "Library/Web Documents"
+#endif
+#ifndef DEFAULT_USER
+#define DEFAULT_USER "www"
+#endif
+#ifndef DEFAULT_GROUP
+#define DEFAULT_GROUP "www"
+#endif
+#ifndef DEFAULT_PATH
+#define DEFAULT_PATH "/bin:/usr/bin:/usr/local/bin"
+#endif
+
+#elif defined(LINUX)
+
+#if LINUX > 1
+#include
+
+/* libc4 systems probably still work, it probably doesn't define
+ * __GNU_LIBRARY__
+ * libc5 systems define __GNU_LIBRARY__ == 1, but don't define __GLIBC__
+ * glibc 2.x and later systems define __GNU_LIBRARY__ == 6, but list it as
+ * "deprecated in favour of __GLIBC__"; the value 6 will never be changed.
+ * glibc 1.x systems (i.e. redhat 4.x on sparc/alpha) should have
+ * __GLIBC__ < 2
+ * all glibc based systems need crypt.h
+ */
+#if defined(__GNU_LIBRARY__) && __GNU_LIBRARY__ > 1
+#include
+#endif
+
+/* glibc 2.0.0 through 2.0.4 need size_t * here, where 2.0.5 needs socklen_t *
+ * there's no way to discern between these two libraries. But using int should
+ * be portable because otherwise these libs would be hopelessly broken with
+ * reams of existing networking code. We'll use socklen_t * for 2.1.x and
+ * later.
+ *
+ * int works for all the earlier libs, and is picked up by default later.
+ */
+#if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 0))
+#define NET_SIZE_T socklen_t
+#endif
+
+#define HAVE_SHMGET 1
+#define USE_SHMGET_SCOREBOARD
+#define HAVE_MMAP 1
+#define USE_MMAP_FILES
+
+/* flock is faster ... but hasn't been tested on 1.x systems */
+/* PR#3531 indicates flock() may not be stable, probably depends on
+ * kernel version. Go back to using fcntl, but provide a way for
+ * folks to tweak their Configuration to get flock.
+ */
+#ifndef USE_FLOCK_SERIALIZED_ACCEPT
+#define USE_FCNTL_SERIALIZED_ACCEPT
+#endif
+
+#define SYS_SIGLIST _sys_siglist
+
+#else
+#define USE_FCNTL_SERIALIZED_ACCEPT
+#endif
+
+#undef HAVE_GMTOFF
+#undef NO_KILLPG
+#undef NO_SETSID
+#undef NEED_STRDUP
+#include
+#define HAVE_SYSLOG 1
+
+/* glibc 2.1 and later finally define rlim_t */
+#if !defined(__GLIBC__) || __GLIBC__ < 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 1)
+typedef int rlim_t;
+#endif
+
+#elif defined(SCO)
+#undef HAVE_GMTOFF
+#undef NO_KILLPG
+#undef NO_SETSID
+#define NEED_INITGROUPS
+#define NO_WRITEV
+#include
+#define HAVE_SYSLOG 1
+#undef HAVE_SYS_RESOURCE_H
+
+#elif defined(SCO5)
+
+#define USE_FCNTL_SERIALIZED_ACCEPT
+#define HAVE_MMAP 1
+#define USE_MMAP_SCOREBOARD
+#define USE_MMAP_FILES
+#define SecureWare
+#define HAVE_SYSLOG 1
+
+/* Although SCO 5 defines these in (note the "s") they don't have
+ consts. Sigh. */
+extern int strcasecmp(const char *, const char *);
+extern int strncasecmp(const char *, const char *, unsigned);
+
+#elif defined(AUX3)
+/* These are to let -Wall compile more cleanly */
+extern int strcasecmp(const char *, const char *);
+extern int strncasecmp(const char *, const char *, unsigned);
+extern int set42sig(), getopt(), getpeername(), bzero();
+extern int listen(), bind(), socket(), getsockname();
+extern int accept(), gethostname(), connect(), lstat();
+extern int select(), killpg(), shutdown();
+extern int initgroups(), setsockopt();
+extern char *shmat();
+extern int shmctl();
+extern int shmget();
+extern char *sbrk();
+extern char *crypt();
+#include
+#undef HAVE_GMTOFF
+#undef NO_KILLPG
+#undef NO_SETSID
+#define NEED_STRDUP
+/* fcntl() locking is expensive with NFS */
+#define USE_FLOCK_SERIALIZED_ACCEPT
+#define SINGLE_LISTEN_UNSERIALIZED_ACCEPT
+#define HAVE_SHMGET 1
+#define USE_SHMGET_SCOREBOARD
+/*
+ * NOTE: If when you run Apache under A/UX and you get a warning
+ * that httpd couldn't move break, then the below value for
+ * MOVEBREAK (64megs) is too large for your setup. Try reducing
+ * to 0x2000000 which is still PLENTY of space. I doubt if
+ * even on heavy systems sbrk() would be called at all...
+ */
+#define MOVEBREAK 0x4000000
+#define NO_LINGCLOSE
+#define NO_SLACK
+#define HAVE_SYSLOG 1
+#undef HAVE_SYS_RESOURCE_H /* exists but does not provide *rlimit funcs */
+
+#elif defined(SVR4)
+#define NO_KILLPG
+#undef NO_SETSID
+#undef NEED_STRDUP
+#ifndef MPRAS
+#define NEED_STRCASECMP
+#ifndef ENCORE
+#define NEED_STRNCASECMP
+#endif /* ENCORE */
+#endif /* MPRAS */
+#define bzero(a,b) memset(a,0,b)
+/* A lot of SVR4 systems need this */
+#ifndef USE_SYSVSEM_SERIALIZED_ACCEPT
+#define USE_FCNTL_SERIALIZED_ACCEPT
+#endif
+#define HAVE_SYSLOG 1
+#define NET_SIZE_T size_t
+#define HAVE_SHMGET 1
+#define USE_SHMGET_SCOREBOARD
+#ifdef _OSD_POSIX /* BS2000-POSIX mainframe needs initgroups */
+#define NEED_HASHBANG_EMUL /* execve() doesn't start shell scripts by default */
+#define _KMEMUSER /* Enable SHM_R/SHM_W defines in */
+#undef NEED_STRCASECMP
+#undef NEED_STRNCASECMP
+#undef bzero
+#endif /*_OSD_POSIX*/
+
+#elif defined(UW)
+#if UW < 700
+#define USE_FCNTL_SERIALIZED_ACCEPT
+#define NO_LINGCLOSE
+#define NO_KILLPG
+#endif
+#undef NO_SETSID
+#undef NEED_STRDUP
+#define NEED_STRCASECMP
+#define NEED_STRNCASECMP
+#define bzero(a,b) memset(a,0,b)
+#define HAVE_MMAP 1
+#define USE_MMAP_SCOREBOARD
+#define USE_MMAP_FILES
+#define HAVE_SHMGET 1
+#undef USE_SHMGET_SCOREBOARD /* force use of mmap() scoreboard */
+#include
+#if UW >= 200
+#define _POSIX_SOURCE
+#endif
+#define NET_SIZE_T size_t
+#define HAVE_SYSLOG 1
+
+#elif defined(DGUX)
+#define NO_KILLPG
+#undef NO_SETSID
+#undef NEED_STRDUP
+#ifdef _IX86_DG
+#undef NEED_STRCASECMP
+#undef NEED_STRNCASECMP
+#else
+#define NEED_STRCASECMP
+#define NEED_STRNCASECMP
+#endif
+#define bzero(a,b) memset(a,0,b)
+/* A lot of SVR4 systems need this */
+#define USE_FCNTL_SERIALIZED_ACCEPT
+#define ap_inet_addr inet_network
+#define HAVE_SYSLOG 1
+
+#elif defined(__NetBSD__) || defined(__OpenBSD__) || defined(NETBSD)
+#define HAVE_GMTOFF 1
+#undef NO_KILLPG
+#undef NO_SETSID
+#define HAVE_SYSLOG 1
+#ifndef DEFAULT_USER
+#define DEFAULT_USER "nobody"
+#endif
+#ifndef DEFAULT_GROUP
+#define DEFAULT_GROUP "nogroup"
+#endif
+#define HAVE_SHMGET 1
+#define HAVE_MMAP 1
+#define USE_MMAP_SCOREBOARD
+#define USE_MMAP_FILES
+#define USE_FLOCK_SERIALIZED_ACCEPT
+#define SINGLE_LISTEN_UNSERIALIZED_ACCEPT
+
+#elif defined(UTS21)
+#undef HAVE_GMTOFF
+#undef NO_KILLPG
+#define NO_SETSID
+#define NEED_WAITPID
+#define STDIN_FILENO 0
+#define STDOUT_FILENO 1
+#define STDERR_FILENO 2
+#define HAVE_SYSLOG 1
+#define USE_LONGJMP
+#define JMP_BUF jmp_buf
+#define NO_USE_SIGACTION
+#define NEED_STRERROR
+#define NEED_STRSTR
+#define NEED_HASHBANG_EMUL
+#define NDELAY_PIPE_RETURNS_ZERO
+#define NO_DATA NO_ADDRESS
+#define ap_wait_t union wait
+#define WEXITSTATUS(status) (int)((status).w_retcode)
+#define WTERMSIG(status) (int)((status).w_termsig)
+#define strftime(buf,bufsize,fmt,tm) ascftime(buf,fmt,tm)
+#undef HAVE_SYS_RESOURCE_H /* exists but does not provide *rlimit funcs */
+#include
+#include
+
+#elif defined(APOLLO)
+#undef HAVE_GMTOFF
+#undef NO_KILLPG
+#undef NO_SETSID
+#define HAVE_SYSLOG 1
+
+#elif defined(__FreeBSD__) || defined(__bsdi__)
+#if defined(__FreeBSD__)
+#include
+#endif
+#define HAVE_GMTOFF 1
+#undef NO_KILLPG
+#undef NO_SETSID
+#define HAVE_MMAP 1
+#define USE_MMAP_SCOREBOARD
+#define USE_MMAP_FILES
+#ifndef DEFAULT_USER
+#define DEFAULT_USER "nobody"
+#endif
+#ifndef DEFAULT_GROUP
+#define DEFAULT_GROUP "nogroup"
+#endif
+#if defined(__bsdi__) || \
+(defined(__FreeBSD_version) && (__FreeBSD_version < 220000))
+typedef quad_t rlim_t;
+#endif
+#define USE_FLOCK_SERIALIZED_ACCEPT
+#define SINGLE_LISTEN_UNSERIALIZED_ACCEPT
+#define HAVE_SYSLOG 1
+#define SYS_SIGLIST sys_siglist
+
+#elif defined(QNX)
+#ifndef crypt
+char *crypt(const char *pw, const char *salt);
+#endif
+#ifndef initgroups
+int initgroups(char *, int);
+#endif
+#ifndef strncasecmp
+#define strncasecmp strnicmp
+#endif
+#undef NO_KILLPG
+#undef NO_SETSID
+#define NEED_INITGROUPS
+#define NEED_SELECT_H
+#define NEED_PROCESS_H
+#include
+#define HAVE_MMAP 1
+#define USE_POSIX_SCOREBOARD
+#define USE_FLOCK_SERIALIZED_ACCEPT
+#define SINGLE_LISTEN_UNSERIALIZED_ACCEPT
+#define HAVE_SYSLOG 1
+
+#elif defined(LYNXOS)
+#undef HAVE_GMTOFF
+#undef USE_MMAP_SCOREBOARD
+#undef USE_SHMGET_SCOREBOARD
+#undef USE_FCNTL_SERIALIZED_ACCEPT
+#undef USE_FLOCK_SERIALIZED_ACCEPT
+#define USE_LONGJMP
+#undef NO_KILLPG
+#undef NO_SETSID
+#undef NO_USE_SIGACTION
+#undef NO_LINGCLOSE
+extern char *crypt(char *pw, char *salt);
+typedef int rlim_t;
+#define HAVE_SYSLOG 1
+
+#elif defined(UXPDS)
+#undef NEED_STRCASECMP
+#undef NEED_STRNCASECMP
+#undef NEED_STRDUP
+#undef HAVE_GMTOFF
+#define NO_KILLPG
+#undef NO_SETSID
+#define bzero(a,b) memset(a,0,b)
+#define USE_FCNTL_SERIALIZED_ACCEPT
+#define HAVE_MMAP 1
+#define USE_MMAP_SCOREBOARD
+#define USE_MMAP_FILES
+#define HAVE_SYSLOG 1
+
+#elif defined(OS2)
+/* Defines required for EMX OS/2 port. */
+#define NO_KILLPG
+#define NEED_STRCASECMP
+#define NEED_STRNCASECMP
+#define NEED_PROCESS_H
+#define NO_SETSID
+#define NO_TIMES
+#define CASE_BLIND_FILESYSTEM
+/* Add some drive name support */
+#define chdir _chdir2
+#include
+#define MAXSOCKETS 2048
+#define USE_OS2_SCOREBOARD
+#define NO_RELIABLE_PIPED_LOGS
+#define USE_OS2SEM_SERIALIZED_ACCEPT
+#define SINGLE_LISTEN_UNSERIALIZED_ACCEPT
+
+#elif defined(__MACHTEN__)
+typedef int rlim_t;
+#undef NO_KILLPG
+#define NO_SETSID
+#define HAVE_GMTOFF 1
+#ifndef __MACHTEN_PPC__
+#ifndef __MACHTEN_68K__
+#define __MACHTEN_68K__
+#endif
+#define USE_FLOCK_SERIALIZED_ACCEPT
+#define NO_USE_SIGACTION
+#define JMP_BUF sigjmp_buf
+#define USE_LONGJMP
+#undef NEED_STRDUP
+#else
+#define HAVE_SHMGET 1
+#define USE_SHMGET_SCOREBOARD
+#define USE_FCNTL_SERIALIZED_ACCEPT
+#endif
+
+/* Convex OS v11 */
+#elif defined(CONVEXOS11)
+#undef HAVE_GMTOFF
+#undef NO_KILLPG
+#undef NO_SETSID
+#undef NEED_STRDUP
+#define HAVE_MMAP 1
+#define USE_MMAP_SCOREBOARD
+#define USE_MMAP_FILES
+#define HAVE_SYSLOG 1
+
+#define NO_TIMEZONE
+#include
+#include
+typedef int rlim_t;
+
+#elif defined(ISC)
+#include
+#define NO_KILLPG
+#undef NO_SETSID
+#define HAVE_SHMGET 1
+#define USE_SHMGET_SCOREBOARD
+#define USE_FCNTL_SERIALIZED_ACCEPT
+#define HAVE_SYSLOG 1
+
+#elif defined(NEWSOS)
+#define HAVE_SHMGET 1
+#define USE_SHMGET_SCOREBOARD
+#define USE_LONGJMP
+#define NO_SETSID
+#define NO_USE_SIGACTION
+#define NEED_WAITPID
+#define NO_OTHER_CHILD
+#define HAVE_SYSLOG 1
+#include
+#include
+#include
+typedef int pid_t;
+typedef int rlim_t;
+typedef int mode_t;
+
+#elif defined(RISCIX)
+#include
+typedef int rlim_t;
+#define NO_USE_SIGACTION
+#define USE_LONGJMP
+#define NEED_STRCASECMP
+#define NEED_STRNCASECMP
+#define NEED_STRDUP
+
+#elif defined(BEOS)
+#include
+
+#define NO_WRITEV
+#define NO_KILLPG
+#define NEED_INITGROUPS
+
+#elif defined(_CX_SX)
+#define JMP_BUF sigjmp_buf
+#include
+#include
+
+#elif defined(WIN32)
+
+/* All windows stuff is now in os/win32/os.h */
+
+#elif defined(TPF) /* IBM Transaction Processing Facility operating system */
+
+#include
+#include
+#include
+#include
+#define PRIMECRAS 0x010000
+#define JMP_BUF jmp_buf
+#define HAVE_SHMGET
+#undef HAVE_SYS_RESOURCE_H
+#define NEED_INITGROUPS
+#define NEED_SIGNAL_INTERRUPT
+#include
+#ifndef __strings_h
+#define NEED_STRCASECMP
+#define NEED_STRNCASECMP
+#endif
+#define NEED_STRDUP
+#define NO_DBM_REWRITEMAP
+#define NO_GETTIMEOFDAY
+#define NO_KILLPG
+#define NO_LINGCLOSE
+#define NO_MMAP
+#define NO_OTHER_CHILD
+#define NO_RELIABLE_PIPED_LOGS
+#define NO_SETSID
+#define NO_SLACK
+#define NO_TIMES
+#define NO_USE_SIGACTION
+#define NO_WRITEV
+#define USE_LONGJMP
+/*#define USE_SHMGET_SCOREBOARD*/
+#define USE_TPF_ACCEPT
+#define USE_TPF_CORE_SERIALIZED_ACCEPT
+/*#define USE_TPF_DAEMON*/
+#define USE_TPF_SCOREBOARD
+#define USE_TPF_SELECT
+#undef offsetof
+#define offsetof(s_type,field) ((size_t)&(((s_type*)0)->field))
+
+#elif defined(__TANDEM)
+#define NO_WRITEV
+#define NO_KILLPG
+#define NEED_INITGROUPS
+#define NO_SLACK
+
+#else
+/* Unknown system - Edit these to match */
+#ifdef BSD
+#define HAVE_GMTOFF 1
+#else
+#undef HAVE_GMTOFF
+#endif
+/* NO_KILLPG is set on systems that don't have killpg */
+#undef NO_KILLPG
+/* NO_SETSID is set on systems that don't have setsid */
+#undef NO_SETSID
+/* NEED_STRDUP is set on stupid systems that don't have strdup. */
+#undef NEED_STRDUP
+#endif
+
+/* stuff marked API_EXPORT is part of the API, and intended for use
+ * by modules
+ */
+#ifndef API_EXPORT
+#define API_EXPORT(type) type
+#endif
+
+/* Stuff marked API_EXPORT_NONSTD is part of the API, and intended for
+ * use by modules. The difference between API_EXPORT and
+ * API_EXPORT_NONSTD is that the latter is required for any functions
+ * which use varargs or are used via indirect function call. This
+ * is to accomodate the two calling conventions in windows dlls.
+ */
+#ifndef API_EXPORT_NONSTD
+#define API_EXPORT_NONSTD(type) type
+#endif
+
+#ifndef MODULE_VAR_EXPORT
+#define MODULE_VAR_EXPORT
+#endif
+#ifndef API_VAR_EXPORT
+#define API_VAR_EXPORT
+#endif
+
+/* modules should not used functions marked CORE_EXPORT
+ * or CORE_EXPORT_NONSTD */
+#ifndef CORE_EXPORT
+#define CORE_EXPORT API_EXPORT
+#endif
+#ifndef CORE_EXPORT_NONSTD
+#define CORE_EXPORT_NONSTD API_EXPORT_NONSTD
+#endif
+
+/* On Mac OS X Server, symbols that conflict with loaded dylibs
+ * (eg. System framework) need to be declared as private symbols with
+ * __private_extern__.
+ * For other systems, make that a no-op.
+ */
+#if (defined(MAC_OS) || defined(MAC_OS_X_SERVER)) && defined(__DYNAMIC__)
+#define ap_private_extern __private_extern__
+#else
+#define ap_private_extern
+#endif
+
+/*
+ * The particular directory style your system supports. If you have dirent.h
+ * in /usr/include (POSIX) or /usr/include/sys (SYSV), #include
+ * that file and define DIR_TYPE to be dirent. Otherwise, if you have
+ * /usr/include/sys/dir.h, define DIR_TYPE to be direct and include that
+ * file. If you have neither, I'm confused.
+ */
+
+#include
+#include
+
+#if !defined(NEXT) && !defined(WIN32)
+#include
+#define DIR_TYPE dirent
+#elif !defined(WIN32)
+#include
+#define DIR_TYPE direct
+#else
+#define DIR_TYPE dirent
+#endif
+
+#include
+#include
+#include
+#ifdef __TANDEM
+#include
+#endif
+#include "ap_ctype.h"
+#if !defined(MPE) && !defined(WIN32) && !defined(TPF) && !defined(__TANDEM)
+#include
+#endif
+#ifndef WIN32
+#include
+#ifdef HAVE_SYS_SELECT_H
+#include
+#endif /* HAVE_SYS_SELECT_H */
+#ifndef TPF
+#include
+#endif /* TPF */
+#include
+#include
+#if !defined(MPE) && !defined(BEOS) && !defined(TPF)
+#include /* for inet_ntoa */
+#endif
+#include
+#include
+#include
+#include
+#define closesocket(s) close(s)
+#ifndef O_BINARY
+#define O_BINARY (0)
+#endif
+
+#else /* WIN32 */
+#include
+#include
+#include
+#include
+#endif /* ndef WIN32 */
+#include
+#include /* for ctime */
+#ifdef WIN32
+#define strftime(s,max,format,tm) os_strftime(s,max,format,tm)
+#endif
+#include
+#if defined(TPF) && defined(NSIG)
+#undef NSIG
+#endif
+#include
+#if !defined(QNX) && !defined(CONVEXOS11) && !defined(NEXT) && !defined(TPF)
+#include
+#endif
+
+#ifdef NEED_PROCESS_H
+#include
+#endif
+
+#ifdef WIN32
+#include "../include/hsregex.h"
+#elif defined(USE_HSREGEX)
+#include "hsregex.h"
+#else
+#include
+#endif
+
+#ifdef HAVE_SYS_RESOURCE_H
+#include
+#ifdef SUNOS4
+int getrlimit(int, struct rlimit *);
+int setrlimit(int, struct rlimit *);
+#endif
+#endif
+#ifdef USE_MMAP_SCOREBOARD
+#if !defined(OS2) && !defined(WIN32)
+/* This file is not needed for OS/2 */
+#include
+#endif
+#endif
+#if !defined(MAP_ANON) && defined(MAP_ANONYMOUS)
+#define MAP_ANON MAP_ANONYMOUS
+#endif
+
+#if defined(USE_MMAP_FILES) && (defined(NO_MMAP) || !defined(HAVE_MMAP))
+#undef USE_MMAP_FILES
+#endif
+
+#if defined(USE_MMAP_SCOREBOARD) && (defined(NO_MMAP) || !defined(HAVE_MMAP))
+#undef USE_MMAP_SCOREBOARD
+#endif
+
+#if defined(USE_SHMGET_SCOREBOARD) && (defined(NO_SHMGET) || !defined(HAVE_SHMGET))
+#undef USE_SHMGET_SCOREBOARD
+#endif
+
+#ifndef LOGNAME_MAX
+#define LOGNAME_MAX 25
+#endif
+
+#ifdef HAVE_UNISTD_H
+#include
+#endif
+
+#ifdef ultrix
+#define ULTRIX_BRAIN_DEATH
+#endif
+
+#ifndef S_ISLNK
+#define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
+#endif
+
+#ifndef INADDR_NONE
+#define INADDR_NONE ((unsigned long) -1)
+#endif
+
+/*
+ * Replace signal function with sigaction equivalent
+ */
+#ifndef NO_USE_SIGACTION
+typedef void Sigfunc(int);
+
+#if defined(SIG_IGN) && !defined(SIG_ERR)
+#define SIG_ERR ((Sigfunc *)-1)
+#endif
+
+/*
+ * For some strange reason, QNX defines signal to signal. Eliminate it.
+ */
+#ifdef signal
+#undef signal
+#endif
+#define signal(s,f) ap_signal(s,f)
+Sigfunc *signal(int signo, Sigfunc * func);
+#endif
+
+#include
+
+#if defined(USE_LONGJMP)
+#define ap_longjmp(x, y) longjmp((x), (y))
+#define ap_setjmp(x) setjmp(x)
+#ifndef JMP_BUF
+#define JMP_BUF jmp_buf
+#endif
+#else
+#define ap_longjmp(x, y) siglongjmp((x), (y))
+#define ap_setjmp(x) sigsetjmp((x), 1)
+#ifndef JMP_BUF
+#define JMP_BUF sigjmp_buf
+#endif
+#endif
+
+/* Majority of os's want to verify FD_SETSIZE */
+#if !defined(WIN32) && !defined(TPF)
+#define CHECK_FD_SETSIZE
+#endif
+
+#ifdef USE_TPF_SELECT
+#define ap_select(_a, _b, _c, _d, _e) \
+ tpf_select(_a, _b, _c, _d, _e)
+#elif defined(SELECT_NEEDS_CAST)
+#define ap_select(_a, _b, _c, _d, _e) \
+ select((_a), (int *)(_b), (int *)(_c), (int *)(_d), (_e))
+#else
+#define ap_select(_a, _b, _c, _d, _e) \
+ select(_a, _b, _c, _d, _e)
+#endif
+
+#ifdef USE_TPF_ACCEPT
+#define ap_accept(_fd, _sa, _ln) tpf_accept(_fd, _sa, _ln)
+#else
+#define ap_accept(_fd, _sa, _ln) accept(_fd, _sa, _ln)
+#endif
+
+#ifdef NEED_SIGNAL_INTERRUPT
+#define ap_check_signals() tpf_process_signals()
+#else
+#define ap_check_signals()
+#endif
+
+#ifdef ULTRIX_BRAIN_DEATH
+#define ap_fdopen(d,m) fdopen((d), (char *)(m))
+#else
+#define ap_fdopen(d,m) fdopen((d), (m))
+#endif
+
+#ifndef ap_inet_addr
+#define ap_inet_addr inet_addr
+#endif
+
+#ifdef NO_OTHER_CHILD
+#define NO_RELIABLE_PIPED_LOGS
+#endif
+
+/* When the underlying OS doesn't support exec() of scripts which start
+ * with a HASHBANG (#!) followed by interpreter name and args, define this.
+ */
+#ifdef NEED_HASHBANG_EMUL
+extern int ap_execle(const char *filename, const char *arg,...);
+extern int ap_execve(const char *filename, const char *argv[],
+ const char *envp[]);
+/* ap_execle() is a wrapper function around ap_execve(). */
+#define execle ap_execle
+#define execve(path,argv,envp) ap_execve(path,argv,envp)
+#endif
+
+/* Finding offsets of elements within structures.
+ * Taken from the X code... they've sweated portability of this stuff
+ * so we don't have to. Sigh...
+ */
+
+#if defined(CRAY) || (defined(__arm) && !defined(LINUX))
+#ifdef __STDC__
+#define XtOffset(p_type,field) _Offsetof(p_type,field)
+#else
+#ifdef CRAY2
+#define XtOffset(p_type,field) \
+ (sizeof(int)*((unsigned int)&(((p_type)NULL)->field)))
+
+#else /* !CRAY2 */
+
+#define XtOffset(p_type,field) ((unsigned int)&(((p_type)NULL)->field))
+
+#endif /* !CRAY2 */
+#endif /* __STDC__ */
+#else /* ! (CRAY || __arm) */
+
+#define XtOffset(p_type,field) \
+ ((long) (((char *) (&(((p_type)NULL)->field))) - ((char *) NULL)))
+
+#endif /* !CRAY */
+
+#ifdef offsetof
+#define XtOffsetOf(s_type,field) offsetof(s_type,field)
+#else
+#define XtOffsetOf(s_type,field) XtOffset(s_type*,field)
+#endif
+
+/*
+ * NET_SIZE_T exists because of shortsightedness on the POSIX committee. BSD
+ * systems used "int *" as the parameter to accept(), getsockname(),
+ * getpeername() et al. Consequently many unixes took an int * for that
+ * parameter. The POSIX committee decided that "int" was just too generic and
+ * had to be replaced with size_t almost everywhere. There's no problem with
+ * that when you're passing by value. But when you're passing by reference
+ * this creates a gross source incompatibility with existing programs. On
+ * 32-bit architectures it creates only a warning. On 64-bit architectures it
+ * creates broken code -- because "int *" is a pointer to a 64-bit quantity and
+ * "size_t *" is frequently a pointer to a 32-bit quantity.
+ *
+ * Some Unixes adopted "size_t *" for the sake of POSIX compliance. Others
+ * ignored it because it was such a broken interface. Chaos ensued. POSIX
+ * finally woke up and decided that it was wrong and created a new type
+ * socklen_t. The only useful value for socklen_t is int, and that's how
+ * everyone who has a clue implements it. It is almost always the case that
+ * NET_SIZE_T should be defined to be an int, unless the system being compiled
+ * for was created in the window of POSIX madness.
+ */
+#ifndef NET_SIZE_T
+#define NET_SIZE_T int
+#endif
+
+/* Linux defines __WCOREDUMP, but doesn't define WCOREDUMP unless __USE_BSD
+ * is in use... we'd prefer to just use WCOREDUMP everywhere.
+ */
+#if defined(__WCOREDUMP) && !defined(WCOREDUMP)
+#define WCOREDUMP __WCOREDUMP
+#endif
+
+#ifdef SUNOS_LIB_PROTOTYPES
+/* Prototypes needed to get a clean compile with gcc -Wall.
+ * Believe it or not, these do have to be declared, at least on SunOS,
+ * because they aren't mentioned in the relevant system headers.
+ * Sun Quality Software. Gotta love it. This section is not
+ * currently (13Nov97) used.
+ */
+
+int getopt(int, char **, char *);
+
+int strcasecmp(const char *, const char *);
+int strncasecmp(const char *, const char *, int);
+int toupper(int);
+int tolower(int);
+
+int printf(char *,...);
+int fprintf(FILE *, char *,...);
+int fputs(char *, FILE *);
+int fread(char *, int, int, FILE *);
+int fwrite(char *, int, int, FILE *);
+int fgetc(FILE *);
+char *fgets(char *s, int, FILE*);
+int fflush(FILE *);
+int fclose(FILE *);
+int ungetc(int, FILE *);
+int _filbuf(FILE *); /* !!! */
+int _flsbuf(unsigned char, FILE *); /* !!! */
+int sscanf(char *, char *,...);
+void setbuf(FILE *, char *);
+void perror(char *);
+
+time_t time(time_t *);
+int strftime(char *, int, const char *, struct tm *);
+
+int initgroups(char *, int);
+int wait3(int *, int, void *); /* Close enough for us... */
+int lstat(const char *, struct stat *);
+int stat(const char *, struct stat *);
+int flock(int, int);
+#ifndef NO_KILLPG
+int killpg(int, int);
+#endif
+int socket(int, int, int);
+int setsockopt(int, int, int, const char *, int);
+int listen(int, int);
+int bind(int, struct sockaddr *, int);
+int connect(int, struct sockaddr *, int);
+int accept(int, struct sockaddr *, int *);
+int shutdown(int, int);
+
+int getsockname(int s, struct sockaddr *name, int *namelen);
+int getpeername(int s, struct sockaddr *name, int *namelen);
+int gethostname(char *name, int namelen);
+void syslog(int, char *,...);
+char *mktemp(char *);
+
+long vfprintf(FILE *, const char *, va_list);
+
+#endif /* SUNOS_LIB_PROTOTYPES */
+
+/* The assumption is that when the functions are missing,
+ * then there's no matching prototype available either.
+ * Declare what is needed exactly as the replacement routines implement it.
+ */
+#ifdef NEED_STRDUP
+extern char *strdup (const char *str);
+#endif
+#ifdef NEED_STRCASECMP
+extern int strcasecmp (const char *a, const char *b);
+#endif
+#ifdef NEED_STRNCASECMP
+extern int strncasecmp (const char *a, const char *b, int n);
+#endif
+#ifdef NEED_INITGROUPS
+extern int initgroups(const char *name, gid_t basegid);
+#endif
+#ifdef NEED_WAITPID
+extern int waitpid(pid_t pid, int *statusp, int options);
+#endif
+#ifdef NEED_STRERROR
+extern char *strerror (int err);
+#endif
+#ifdef NEED_DIFFTIME
+extern double difftime(time_t time1, time_t time0);
+#endif
+
+#ifndef ap_wait_t
+#define ap_wait_t int
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !AP_CONFIG_H */
diff --git a/include/ap_listen.h b/include/ap_listen.h
new file mode 100644
index 00000000000..600f6fca28d
--- /dev/null
+++ b/include/ap_listen.h
@@ -0,0 +1,86 @@
+/* ====================================================================
+ * Copyright (c) 1996-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+#ifndef AP_LISTEN_H
+#define AP_LISTEN_H
+
+typedef struct ap_listen_rec ap_listen_rec;
+struct ap_listen_rec {
+ ap_listen_rec *next;
+ struct sockaddr_in local_addr; /* local IP address and port */
+/* TODO: replace the fd with APR stuff */
+ int fd;
+/* more stuff here, like which protocol is bound to the port */
+};
+
+ap_listen_rec *ap_listeners;
+
+void ap_listen_pre_config(void);
+int ap_listen_open(pool *pconf, unsigned port);
+const char *ap_set_listenbacklog(cmd_parms *cmd, void *dummy, char *arg);
+const char *ap_set_listener(cmd_parms *cmd, void *dummy, char *ips);
+const char *ap_set_send_buffer_size(cmd_parms *cmd, void *dummy, char *arg);
+
+#define LISTEN_COMMANDS \
+{ "ListenBacklog", ap_set_listenbacklog, NULL, RSRC_CONF, TAKE1, \
+ "Maximum length of the queue of pending connections, as used by listen(2)" }, \
+{ "Listen", ap_set_listener, NULL, RSRC_CONF, TAKE1, \
+ "A port number or a numeric IP address and a port number"}, \
+{ "SendBufferSize", ap_set_send_buffer_size, NULL, RSRC_CONF, TAKE1, \
+ "Send buffer size in bytes"},
+
+#endif
diff --git a/include/ap_mmn.h b/include/ap_mmn.h
new file mode 100644
index 00000000000..6f3138346d0
--- /dev/null
+++ b/include/ap_mmn.h
@@ -0,0 +1,256 @@
+/* ====================================================================
+ * Copyright (c) 1998-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+#ifndef APACHE_AP_MMN_H
+#define APACHE_AP_MMN_H
+
+/*
+ * MODULE_MAGIC_NUMBER_MAJOR
+ * Major API changes that could cause compatibility problems for older modules
+ * such as structure size changes. No binary compatibility is possible across
+ * a change in the major version.
+ *
+ * MODULE_MAGIC_NUMBER_MINOR
+ * Minor API changes that do not cause binary compatibility problems.
+ * Should be reset to 0 when upgrading MODULE_MAGIC_NUMBER_MAJOR.
+ *
+ * See the MODULE_MAGIC_AT_LEAST macro below for an example.
+ */
+
+/*
+ * 19950525 - original value
+ * 19960512 (1.1b2) - updated, 1.1, version.
+ * 19960526 (1.1b3) - get_token(), table_unset(), pstrndup()
+ * functions added
+ * 19960725 (1.2-dev) - HTTP/1.1 compliance
+ * (new version of read_client_block)
+ * 19960806 (1.2-dev) - scan_script_header_err() added
+ * 19961007 (1.2-dev) - replace read_client_block() with get_client_block()
+ * 19961125 (1.2b1) - change setup_client_block() to Roy's version
+ * 19961211 (1.2b3) - rwrite() added
+ * 19970103 (1.2b5-dev) - header parse API
+ * 19970427 (1.2b9-dev) - port references made unsigned
+ * 19970526 (1.2) - correct vhost walk for multiple requests on a single
+ * connect
+ * 19970623 (1.3-dev) - NT changes
+ * 19970628 (1.3-dev) - ap_slack (fd fixes) added
+ * 19970717 (1.3-dev) - child_init API hook added
+ * 19970719 (1.3-dev) - discard_request_body() added (to clear the decks
+ * as needed)
+ * 19970728 (1.3a2-dev) - child_exit API hook added
+ * 19970818 (1.3a2-dev) - post read-request phase added
+ * 19970825 (1.3a2-dev) - r->mtime cell added
+ * 19970831 (1.3a2-dev) - error logging changed to use aplog_error()
+ * 19970902 (1.3a2-dev) - MD5 routines and structures renamed to ap_*
+ * 19970912 (1.3b1-dev) - set_last_modified split into set_last_modified,
+ * set_etag and meets_conditions
+ * register_other_child API
+ * piped_log API
+ * short_score split into parent and child pieces
+ * os_is_absolute_path
+ * 19971026 (1.3b3-dev) - custom config hooks in place
+ * 19980126 (1.3b4-dev) - ap_cpystrn(), table_addn(), table_setn(),
+ * table_mergen()
+ * 19980201 (1.3b4-dev) - construct_url()
+ * prototype server_rec * -> request_rec *
+ * add get_server_name() and get_server_port()
+ * 19980207 (1.3b4-dev) - add dynamic_load_handle to module structure as part
+ * of the STANDARD_MODULE_STUFF header
+ * 19980304 (1.3b6-dev) - abstraction of SERVER_BUILT and SERVER_VERSION
+ * 19980305 (1.3b6-dev) - ap_config.h added for use by external modules
+ * 19980312 (1.3b6-dev) - parse_uri_components() and its ilk
+ * remove r->hostlen, add r->unparsed_uri
+ * set_string_slot_lower()
+ * clarification: non-RAW_ARGS cmd handlers do not
+ * need to pstrdup() their arguments
+ * clarification: request_rec members content_type,
+ * handler, content_encoding, content_language,
+ * content_languages MUST all be lowercase strings,
+ * and MAY NOT be modified in place -- modifications
+ * require pstrdup().
+ * 19980317 (1.3b6-dev) - CORE_EXPORTs for win32 and
+ * API export basic_http_header, send_header_field,
+ * set_keepalive, srm_command_loop, check_cmd_context,
+ * tm2sec
+ * spacetoplus(), plustospace(), client_to_stdout()
+ * removed
+ * 19980324 (1.3b6-dev) - API_EXPORT(index_of_response)
+ * 19980413 (1.3b6-dev) - The BIG SYMBOL RENAMING: general ap_ prefix
+ * (see src/include/compat.h for more details)
+ * ap_vformatter() API, see src/include/ap.h
+ * 19980507 (1.3b7-dev) - addition of ap_add_version_component() and
+ * discontinuation of -DSERVER_SUBVERSION support
+ * 19980519 (1.3b7-dev) - add child_info * to spawn function (as passed to
+ * ap_spawn_child_err_buff) and to ap_call_exec to make
+ * children work correctly on Win32.
+ * 19980527 (1.3b8-dev) - renamed some more functions to ap_ prefix which were
+ * missed at the big renaming (they are defines):
+ * is_default_port, default_port and http_method.
+ * A new communication method for modules was added:
+ * they can create customized error messages under the
+ * "error-notes" key in the request_rec->notes table.
+ * This string will be printed in place of the canned
+ * error responses, and will be propagated to
+ * ErrorDocuments or cgi scripts in the
+ * (REDIRECT_)ERROR_NOTES variable.
+ * 19980627 (1.3.1-dev) - More renaming that we forgot/bypassed. In particular:
+ * table_elts --> ap_table_elts
+ * is_table_empty --> ap_is_table_empty
+ * 19980708 (1.3.1-dev) - ap_isalnum(), ap_isalpha(), ... "8-bit safe" ctype
+ * macros and apctype.h added
+ * 19980713 (1.3.1-dev) - renaming of C header files:
+ * 1. conf.h -> ap_config.h
+ * 2. conf_auto.h -> ap_config_auto.h - now merged
+ * 3. ap_config.h -> ap_config_auto.h - now merged
+ * 4. compat.h -> ap_compat.h
+ * 5. apctype.h -> ap_ctype.h
+ * 19980806 (1.3.2-dev) - add ap_log_rerror()
+ * - add ap_scan_script_header_err_core()
+ * - add ap_uuencode()
+ * - add ap_custom_response()
+ * 19980811 (1.3.2-dev) - added limit_req_line, limit_req_fieldsize, and
+ * limit_req_fields to server_rec.
+ * added limit_req_body to core_dir_config and
+ * ap_get_limit_req_body() to get its value.
+ * 19980812 (1.3.2-dev) - split off MODULE_MAGIC_NUMBER
+ * 19980812.2 - add ap_overlap_tables()
+ * 19980816 (1.3.2-dev) - change proxy to use tables for headers, change
+ * struct cache_req to typedef cache_req.
+ * Delete ap_proxy_get_header(), ap_proxy_add_header(),
+ * ap_proxy_del_header(). Change interface of
+ * ap_proxy_send_fb() and ap_proxy_cache_error().
+ * Add ap_proxy_send_hdr_line() and ap_proxy_bputs2().
+ * 19980825 (1.3.2-dev) - renamed is_HTTP_xxx() macros to ap_is_HTTP_xxx()
+ * 19980825.1 - mod_proxy only (minor change): modified interface of
+ * ap_proxy_read_headers() and rdcache() to use a
+ * request_rec* instead of pool*
+ * (for implementing better error reporting).
+ * 19980906 (1.3.2-dev) - added ap_md5_binary()
+ * 19980917 (1.3.2-dev) - bs2000: changed os_set_authfile() to os_set_account()
+ * 19981108 (1.3.4-dev) - added ap_method_number_of()
+ * - changed value of M_INVALID and added WebDAV methods
+ * 19981108.1 - ap_exists_config_define() is now public (minor bump)
+ * 19981204 - scoreboard changes -- added generation, changed
+ * exit_generation to running_generation. Somewhere
+ * earlier vhostrec was added, but it's only safe to use
+ * as of this rev. See scoreboard.h for documentation.
+ * 19981211 - DSO changes -- added ap_single_module_configure()
+ * -- added ap_single_module_init()
+ * 19981229 - mod_negotiation overhaul -- added ap_make_etag()
+ * and added vlist_validator to request_rec.
+ * 19990101 - renamed macro escape_uri() to ap_escape_uri()
+ * - added MODULE_MAGIC_COOKIE to identify module structs
+ * 19990103 (1.3.4-dev) - added ap_array_pstrcat()
+ * 19990105 (1.3.4-dev) - added ap_os_is_filename_valid()
+ * 19990106 (1.3.4-dev) - Move MODULE_MAGIC_COOKIE to the end of the
+ * STANDARD_MODULE_STUFF macro so the version
+ * numbers and file name remain at invariant offsets
+ * 19990108 (1.3.4-dev) - status_drops_connection -> ap_status_drops_connection
+ * scan_script_header -> ap_scan_script_header_err
+ * - reordered entries in request_rec that were waiting
+ * for a non-binary-compatible release.
+ * (1.3.5-dev)
+ * 19990108.1 - add ap_MD5Encode() for MD5 password handling.
+ * 19990108.2 - add ap_validate_password() and change ap_MD5Encode()
+ * to use a stronger algorithm.
+ * 19990108.4 - add ap_size_list_item(), ap_get_list_item(), and
+ * ap_find_list_item()
+ * 19990108.5 - added ap_sub_req_method_uri() and added const to the
+ * definition of method in request_rec.
+ * 19990108.6 - SIGPIPE is now ignored by the core server.
+ * 19990108.7 - ap_isxdigit added
+ * 19990320 - METHODS and M_INVALID symbol values modified
+ * 19990320.1 - add ap_vrprintf()
+ * 19990320.2 - add cmd_parms.context, ap_set_config_vectors,
+ * export ap_add_file_conf
+ * 19990320.3 - add ap_regexec() and ap_regerror()
+ * 19990320.4 - add ap_field_noparam()
+ * 19990320.5 - add local_ip/host to conn_rec for mass-vhost
+ * 19990320.6 - add ap_SHA1Final(), ap_SHA1Init(),
+ * ap_SHA1Update_binary(), ap_SHA1Update(),
+ * ap_base64encode(), ap_base64encode_binary(),
+ * ap_base64encode_len(), ap_base64decode(),
+ * ap_base64decode_binary(), ap_base64decode_len(),
+ * ap_pbase64decode(), ap_pbase64encode()
+ */
+
+#define MODULE_MAGIC_COOKIE 0x41503133UL /* "AP13" */
+
+#ifndef MODULE_MAGIC_NUMBER_MAJOR
+#define MODULE_MAGIC_NUMBER_MAJOR 19990320
+#endif
+#define MODULE_MAGIC_NUMBER_MINOR 6 /* 0...n */
+#define MODULE_MAGIC_NUMBER MODULE_MAGIC_NUMBER_MAJOR /* backward compat */
+
+/* Useful for testing for features. */
+#define MODULE_MAGIC_AT_LEAST(major,minor) \
+ ((major) > MODULE_MAGIC_NUMBER_MAJOR \
+ || ((major) == MODULE_MAGIC_NUMBER_MAJOR \
+ && (minor) >= MODULE_MAGIC_NUMBER_MINOR))
+
+/* For example, suppose you wish to use the ap_overlap_tables
+ function. You can do this:
+
+#if MODULE_MAGIC_AT_LEAST(19980812,2)
+ ... use ap_overlap_tables()
+#else
+ ... alternative code which doesn't use ap_overlap_tables()
+#endif
+
+*/
+
+#endif /* !APACHE_AP_MMN_H */
diff --git a/include/http_config.h b/include/http_config.h
new file mode 100644
index 00000000000..e0c29306f8c
--- /dev/null
+++ b/include/http_config.h
@@ -0,0 +1,414 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+#ifndef APACHE_HTTP_CONFIG_H
+#define APACHE_HTTP_CONFIG_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * The central data structures around here...
+ */
+
+/* Command dispatch structures... */
+
+/* Note that for all of these except RAW_ARGS, the config routine is
+ * passed a freshly allocated string which can be modified or stored
+ * or whatever... it's only necessary to do pstrdup() stuff with
+ * RAW_ARGS.
+ */
+enum cmd_how {
+ RAW_ARGS, /* cmd_func parses command line itself */
+ TAKE1, /* one argument only */
+ TAKE2, /* two arguments only */
+ ITERATE, /* one argument, occuring multiple times
+ * (e.g., IndexIgnore)
+ */
+ ITERATE2, /* two arguments, 2nd occurs multiple times
+ * (e.g., AddIcon)
+ */
+ FLAG, /* One of 'On' or 'Off' */
+ NO_ARGS, /* No args at all, e.g. */
+ TAKE12, /* one or two arguments */
+ TAKE3, /* three arguments only */
+ TAKE23, /* two or three arguments */
+ TAKE123, /* one, two or three arguments */
+ TAKE13 /* one or three arguments */
+};
+
+typedef struct command_struct {
+ const char *name; /* Name of this command */
+ const char *(*func) (); /* Function invoked */
+ void *cmd_data; /* Extra data, for functions which
+ * implement multiple commands...
+ */
+ int req_override; /* What overrides need to be allowed to
+ * enable this command.
+ */
+ enum cmd_how args_how; /* What the command expects as arguments */
+
+ const char *errmsg; /* 'usage' message, in case of syntax errors */
+} command_rec;
+
+/* The allowed locations for a configuration directive are the union of
+ * those indicated by each set bit in the req_override mask.
+ *
+ * (req_override & RSRC_CONF) => *.conf outside or
+ * (req_override & ACCESS_CONF) => *.conf inside or
+ * (req_override & OR_AUTHCFG) => *.conf inside or
+ * and .htaccess when AllowOverride AuthConfig
+ * (req_override & OR_LIMIT) => *.conf inside or
+ * and .htaccess when AllowOverride Limit
+ * (req_override & OR_OPTIONS) => *.conf anywhere
+ * and .htaccess when AllowOverride Options
+ * (req_override & OR_FILEINFO) => *.conf anywhere
+ * and .htaccess when AllowOverride FileInfo
+ * (req_override & OR_INDEXES) => *.conf anywhere
+ * and .htaccess when AllowOverride Indexes
+ */
+#define OR_NONE 0
+#define OR_LIMIT 1
+#define OR_OPTIONS 2
+#define OR_FILEINFO 4
+#define OR_AUTHCFG 8
+#define OR_INDEXES 16
+#define OR_UNSET 32
+#define ACCESS_CONF 64
+#define RSRC_CONF 128
+#define OR_ALL (OR_LIMIT|OR_OPTIONS|OR_FILEINFO|OR_AUTHCFG|OR_INDEXES)
+
+/* This can be returned by a function if they don't wish to handle
+ * a command. Make it something not likely someone will actually use
+ * as an error code.
+ */
+
+#define DECLINE_CMD "\a\b"
+
+/*
+ * This structure is passed to a command which is being invoked,
+ * to carry a large variety of miscellaneous data which is all of
+ * use to *somebody*...
+ */
+
+typedef struct {
+ void *info; /* Argument to command from cmd_table */
+ int override; /* Which allow-override bits are set */
+ int limited; /* Which methods are ed */
+
+ configfile_t *config_file; /* Config file structure from pcfg_openfile() */
+
+ ap_pool *pool; /* Pool to allocate new storage in */
+ struct pool *temp_pool; /* Pool for scratch memory; persists during
+ * configuration, but wiped before the first
+ * request is served...
+ */
+ server_rec *server; /* Server_rec being configured for */
+ char *path; /* If configuring for a directory,
+ * pathname of that directory.
+ * NOPE! That's what it meant previous to the
+ * existance of , and regex
+ * matching. Now the only usefulness that can
+ * be derived from this field is whether a command
+ * is being called in a server context (path == NULL)
+ * or being called in a dir context (path != NULL).
+ */
+ const command_rec *cmd; /* configuration command */
+ const char *end_token; /* end token required to end a nested section */
+ void *context; /* per_dir_config vector passed
+ * to handle_command */
+} cmd_parms;
+
+/* This structure records the existence of handlers in a module... */
+
+typedef struct {
+ const char *content_type; /* MUST be all lower case */
+ int (*handler) (request_rec *);
+} handler_rec;
+
+/*
+ * Module structures. Just about everything is dispatched through
+ * these, directly or indirectly (through the command and handler
+ * tables).
+ */
+
+typedef struct module_struct {
+ int version; /* API version, *not* module version;
+ * check that module is compatible with this
+ * version of the server.
+ */
+ int minor_version; /* API minor version. Provides API feature
+ * milestones. Not checked during module init
+ */
+ int module_index; /* Index to this modules structures in
+ * config vectors.
+ */
+
+ const char *name;
+ void *dynamic_load_handle;
+
+ struct module_struct *next;
+
+ unsigned long magic; /* Magic Cookie to identify a module structure;
+ * It's mainly important for the DSO facility
+ * (see also mod_so).
+ */
+
+ /* init() occurs after config parsing, but before any children are
+ * forked.
+ * Modules should not rely on the order in which create_server_config
+ * and create_dir_config are called.
+ */
+#ifdef ULTRIX_BRAIN_DEATH
+ void (*init) ();
+ void *(*create_dir_config) ();
+ void *(*merge_dir_config) ();
+ void *(*create_server_config) ();
+ void *(*merge_server_config) ();
+#else
+ void (*init) (server_rec *, pool *);
+ void *(*create_dir_config) (pool *p, char *dir);
+ void *(*merge_dir_config) (pool *p, void *base_conf, void *new_conf);
+ void *(*create_server_config) (pool *p, server_rec *s);
+ void *(*merge_server_config) (pool *p, void *base_conf, void *new_conf);
+#endif
+
+ const command_rec *cmds;
+ const handler_rec *handlers;
+
+ /* Hooks for getting into the middle of server ops...
+
+ * translate_handler --- translate URI to filename
+ * access_checker --- check access by host address, etc. All of these
+ * run; if all decline, that's still OK.
+ * check_user_id --- get and validate user id from the HTTP request
+ * auth_checker --- see if the user (from check_user_id) is OK *here*.
+ * If all of *these* decline, the request is rejected
+ * (as a SERVER_ERROR, since the module which was
+ * supposed to handle this was configured wrong).
+ * type_checker --- Determine MIME type of the requested entity;
+ * sets content_type, _encoding and _language fields.
+ * logger --- log a transaction.
+ * post_read_request --- run right after read_request or internal_redirect,
+ * and not run during any subrequests.
+ */
+
+ int (*translate_handler) (request_rec *);
+ int (*ap_check_user_id) (request_rec *);
+ int (*auth_checker) (request_rec *);
+ int (*access_checker) (request_rec *);
+ int (*type_checker) (request_rec *);
+ int (*fixer_upper) (request_rec *);
+ int (*logger) (request_rec *);
+ int (*header_parser) (request_rec *);
+
+ /* Regardless of the model the server uses for managing "units of
+ * execution", i.e. multi-process, multi-threaded, hybrids of those,
+ * there is the concept of a "heavy weight process". That is, a
+ * process with its own memory space, file spaces, etc. This method,
+ * child_init, is called once for each heavy-weight process before
+ * any requests are served. Note that no provision is made yet for
+ * initialization per light-weight process (i.e. thread). The
+ * parameters passed here are the same as those passed to the global
+ * init method above.
+ */
+#ifdef ULTRIX_BRAIN_DEATH
+ void (*child_init) ();
+ void (*child_exit) ();
+#else
+ void (*child_init) (server_rec *, pool *);
+ void (*child_exit) (server_rec *, pool *);
+#endif
+ int (*post_read_request) (request_rec *);
+} module;
+
+/* Initializer for the first few module slots, which are only
+ * really set up once we start running. Note that the first two slots
+ * provide a version check; this should allow us to deal with changes to
+ * the API. The major number should reflect changes to the API handler table
+ * itself or removal of functionality. The minor number should reflect
+ * additions of functionality to the existing API. (the server can detect
+ * an old-format module, and either handle it back-compatibly, or at least
+ * signal an error). See src/include/ap_mmn.h for MMN version history.
+ */
+
+#define STANDARD_MODULE_STUFF MODULE_MAGIC_NUMBER_MAJOR, \
+ MODULE_MAGIC_NUMBER_MINOR, \
+ -1, \
+ __FILE__, \
+ NULL, \
+ NULL, \
+ MODULE_MAGIC_COOKIE
+
+/* Generic accessors for other modules to get at their own module-specific
+ * data
+ */
+
+API_EXPORT(void *) ap_get_module_config(void *conf_vector, module *m);
+API_EXPORT(void) ap_set_module_config(void *conf_vector, module *m, void *val);
+
+#define ap_get_module_config(v,m) \
+ (((void **)(v))[(m)->module_index])
+#define ap_set_module_config(v,m,val) \
+ ((((void **)(v))[(m)->module_index]) = (val))
+
+/* Generic command handling function... */
+
+API_EXPORT_NONSTD(const char *) ap_set_string_slot(cmd_parms *, char *, char *);
+API_EXPORT_NONSTD(const char *) ap_set_string_slot_lower(cmd_parms *, char *, char *);
+API_EXPORT_NONSTD(const char *) ap_set_flag_slot(cmd_parms *, char *, int);
+API_EXPORT_NONSTD(const char *) ap_set_file_slot(cmd_parms *, char *, char *);
+
+/* For modules which need to read config files, open logs, etc. ...
+ * this returns the fname argument if it begins with '/'; otherwise
+ * it relativizes it wrt server_root.
+ */
+
+API_EXPORT(char *) ap_server_root_relative(pool *p, char *fname);
+
+/* Finally, the hook for dynamically loading modules in... */
+
+API_EXPORT(void) ap_add_module(module *m);
+API_EXPORT(void) ap_remove_module(module *m);
+API_EXPORT(void) ap_add_loaded_module(module *mod);
+API_EXPORT(void) ap_remove_loaded_module(module *mod);
+API_EXPORT(int) ap_add_named_module(const char *name);
+API_EXPORT(void) ap_clear_module_list(void);
+API_EXPORT(const char *) ap_find_module_name(module *m);
+API_EXPORT(module *) ap_find_linked_module(const char *name);
+
+/* for implementing subconfigs and customized config files */
+API_EXPORT(const char *) ap_srm_command_loop(cmd_parms *parms, void *config);
+
+#ifdef CORE_PRIVATE
+
+extern API_VAR_EXPORT module *top_module;
+
+extern module *ap_prelinked_modules[];
+extern module *ap_preloaded_modules[];
+extern API_VAR_EXPORT module **ap_loaded_modules;
+
+/* For mod_so.c... */
+
+void ap_single_module_configure(pool *p, server_rec *s, module *m);
+
+/* For http_main.c... */
+
+server_rec *ap_read_config(pool *conf_pool, pool *temp_pool, char *config_name);
+void ap_init_modules(pool *p, server_rec *s);
+void ap_child_init_modules(pool *p, server_rec *s);
+void ap_child_exit_modules(pool *p, server_rec *s);
+void ap_setup_prelinked_modules(void);
+void ap_show_directives(void);
+void ap_show_modules(void);
+
+/* For http_request.c... */
+
+void *ap_create_request_config(pool *p);
+CORE_EXPORT(void *) ap_create_per_dir_config(pool *p);
+void *ap_merge_per_dir_configs(pool *p, void *base, void *new);
+
+/* For http_core.c... ( command and virtual hosts) */
+
+int ap_parse_htaccess(void **result, request_rec *r, int override,
+ const char *path, const char *access_name);
+
+CORE_EXPORT(const char *) ap_init_virtual_host(pool *p, const char *hostname,
+ server_rec *main_server, server_rec **);
+void ap_process_resource_config(server_rec *s, char *fname, pool *p, pool *ptemp);
+
+/* ap_check_cmd_context() definitions: */
+API_EXPORT(const char *) ap_check_cmd_context(cmd_parms *cmd, unsigned forbidden);
+
+/* ap_check_cmd_context(): Forbidden in: */
+#define NOT_IN_VIRTUALHOST 0x01 /* */
+#define NOT_IN_LIMIT 0x02 /* */
+#define NOT_IN_DIRECTORY 0x04 /* */
+#define NOT_IN_LOCATION 0x08 /* */
+#define NOT_IN_FILES 0x10 /* */
+#define NOT_IN_DIR_LOC_FILE (NOT_IN_DIRECTORY|NOT_IN_LOCATION|NOT_IN_FILES) /* //*/
+#define GLOBAL_ONLY (NOT_IN_VIRTUALHOST|NOT_IN_LIMIT|NOT_IN_DIR_LOC_FILE)
+
+
+/* Module-method dispatchers, also for http_request.c */
+
+int ap_translate_name(request_rec *);
+int ap_check_access(request_rec *); /* check access on non-auth basis */
+int ap_check_user_id(request_rec *); /* obtain valid username from client auth */
+int ap_check_auth(request_rec *); /* check (validated) user is authorized here */
+int ap_find_types(request_rec *); /* identify MIME type */
+int ap_run_fixups(request_rec *); /* poke around for other metainfo, etc.... */
+int ap_invoke_handler(request_rec *);
+int ap_log_transaction(request_rec *r);
+int ap_header_parse(request_rec *);
+int ap_run_post_read_request(request_rec *);
+
+/* for mod_perl */
+
+CORE_EXPORT(const command_rec *) ap_find_command(const char *name, const command_rec *cmds);
+CORE_EXPORT(const command_rec *) ap_find_command_in_modules(const char *cmd_name, module **mod);
+CORE_EXPORT(void *) ap_set_config_vectors(cmd_parms *parms, void *config, module *mod);
+CORE_EXPORT(const char *) ap_handle_command(cmd_parms *parms, void *config, const char *l);
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !APACHE_HTTP_CONFIG_H */
diff --git a/include/http_core.h b/include/http_core.h
new file mode 100644
index 00000000000..459fd248f35
--- /dev/null
+++ b/include/http_core.h
@@ -0,0 +1,310 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+#ifndef APACHE_HTTP_CORE_H
+#define APACHE_HTTP_CORE_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*****************************************************************
+ *
+ * The most basic server code is encapsulated in a single module
+ * known as the core, which is just *barely* functional enough to
+ * serve documents, though not terribly well.
+ *
+ * Largely for NCSA back-compatibility reasons, the core needs to
+ * make pieces of its config structures available to other modules.
+ * The accessors are declared here, along with the interpretation
+ * of one of them (allow_options).
+ */
+
+#define OPT_NONE 0
+#define OPT_INDEXES 1
+#define OPT_INCLUDES 2
+#define OPT_SYM_LINKS 4
+#define OPT_EXECCGI 8
+#define OPT_UNSET 16
+#define OPT_INCNOEXEC 32
+#define OPT_SYM_OWNER 64
+#define OPT_MULTI 128
+#define OPT_ALL (OPT_INDEXES|OPT_INCLUDES|OPT_SYM_LINKS|OPT_EXECCGI)
+
+/* options for get_remote_host() */
+/* REMOTE_HOST returns the hostname, or NULL if the hostname
+ * lookup fails. It will force a DNS lookup according to the
+ * HostnameLookups setting.
+ */
+#define REMOTE_HOST (0)
+
+/* REMOTE_NAME returns the hostname, or the dotted quad if the
+ * hostname lookup fails. It will force a DNS lookup according
+ * to the HostnameLookups setting.
+ */
+#define REMOTE_NAME (1)
+
+/* REMOTE_NOLOOKUP is like REMOTE_NAME except that a DNS lookup is
+ * never forced.
+ */
+#define REMOTE_NOLOOKUP (2)
+
+/* REMOTE_DOUBLE_REV will always force a DNS lookup, and also force
+ * a double reverse lookup, regardless of the HostnameLookups
+ * setting. The result is the (double reverse checked) hostname,
+ * or NULL if any of the lookups fail.
+ */
+#define REMOTE_DOUBLE_REV (3)
+
+#define SATISFY_ALL 0
+#define SATISFY_ANY 1
+#define SATISFY_NOSPEC 2
+
+API_EXPORT(int) ap_allow_options (request_rec *);
+API_EXPORT(int) ap_allow_overrides (request_rec *);
+API_EXPORT(const char *) ap_default_type (request_rec *);
+API_EXPORT(const char *) ap_document_root (request_rec *); /* Don't use this! If your request went
+ * through a Userdir, or something like
+ * that, it'll screw you. But it's
+ * back-compatible...
+ */
+API_EXPORT(const char *) ap_get_remote_host(conn_rec *conn, void *dir_config, int type);
+API_EXPORT(const char *) ap_get_remote_logname(request_rec *r);
+
+/* Used for constructing self-referencing URLs, and things like SERVER_PORT,
+ * and SERVER_NAME.
+ */
+API_EXPORT(char *) ap_construct_url(pool *p, const char *uri, request_rec *r);
+API_EXPORT(const char *) ap_get_server_name(request_rec *r);
+API_EXPORT(unsigned) ap_get_server_port(const request_rec *r);
+API_EXPORT(unsigned long) ap_get_limit_req_body(const request_rec *r);
+API_EXPORT(void) ap_custom_response(request_rec *r, int status, char *string);
+API_EXPORT(int) ap_exists_config_define(char *name);
+
+/* Authentication stuff. This is one of the places where compatibility
+ * with the old config files *really* hurts; they don't discriminate at
+ * all between different authentication schemes, meaning that we need
+ * to maintain common state for all of them in the core, and make it
+ * available to the other modules through interfaces.
+ */
+
+typedef struct {
+ int method_mask;
+ char *requirement;
+} require_line;
+
+API_EXPORT(const char *) ap_auth_type (request_rec *);
+API_EXPORT(const char *) ap_auth_name (request_rec *);
+API_EXPORT(int) ap_satisfies (request_rec *r);
+API_EXPORT(const array_header *) ap_requires (request_rec *);
+
+#ifdef WIN32
+/*
+ * CGI Script stuff for Win32...
+ */
+typedef enum { eFileTypeUNKNOWN, eFileTypeBIN, eFileTypeEXE16, eFileTypeEXE32,
+ eFileTypeSCRIPT } file_type_e;
+typedef enum { INTERPRETER_SOURCE_UNSET, INTERPRETER_SOURCE_REGISTRY,
+ INTERPRETER_SOURCE_SHEBANG } interpreter_source_e;
+API_EXPORT(file_type_e) ap_get_win32_interpreter(const request_rec *, char **);
+#endif
+
+#ifdef CORE_PRIVATE
+
+/*
+ * Core is also unlike other modules in being implemented in more than
+ * one file... so, data structures are declared here, even though most of
+ * the code that cares really is in http_core.c. Also, another accessor.
+ */
+
+char *ap_response_code_string (request_rec *r, int error_index);
+
+extern API_VAR_EXPORT module core_module;
+
+/* Per-directory configuration */
+
+typedef unsigned char allow_options_t;
+typedef unsigned char overrides_t;
+
+typedef struct {
+ /* path of the directory/regex/etc. see also d_is_fnmatch below */
+ char *d;
+ /* the number of slashes in d */
+ unsigned d_components;
+
+ /* If (opts & OPT_UNSET) then no absolute assignment to options has
+ * been made.
+ * invariant: (opts_add & opts_remove) == 0
+ * Which said another way means that the last relative (options + or -)
+ * assignment made to each bit is recorded in exactly one of opts_add
+ * or opts_remove.
+ */
+ allow_options_t opts;
+ allow_options_t opts_add;
+ allow_options_t opts_remove;
+ overrides_t override;
+
+ /* MIME typing --- the core doesn't do anything at all with this,
+ * but it does know what to slap on a request for a document which
+ * goes untyped by other mechanisms before it slips out the door...
+ */
+
+ char *ap_default_type;
+
+ /* Authentication stuff. Groan... */
+
+ int satisfy;
+ char *ap_auth_type;
+ char *ap_auth_name;
+ array_header *ap_requires;
+
+ /* Custom response config. These can contain text or a URL to redirect to.
+ * if response_code_strings is NULL then there are none in the config,
+ * if it's not null then it's allocated to sizeof(char*)*RESPONSE_CODES.
+ * This lets us do quick merges in merge_core_dir_configs().
+ */
+
+ char **response_code_strings;
+
+ /* Hostname resolution etc */
+#define HOSTNAME_LOOKUP_OFF 0
+#define HOSTNAME_LOOKUP_ON 1
+#define HOSTNAME_LOOKUP_DOUBLE 2
+#define HOSTNAME_LOOKUP_UNSET 3
+ unsigned int hostname_lookups : 4;
+
+ signed int do_rfc1413 : 2; /* See if client is advertising a username? */
+
+ signed int content_md5 : 2; /* calculate Content-MD5? */
+
+#define USE_CANONICAL_NAME_OFF (0)
+#define USE_CANONICAL_NAME_ON (1)
+#define USE_CANONICAL_NAME_DNS (2)
+#define USE_CANONICAL_NAME_UNSET (3)
+ unsigned use_canonical_name : 2;
+
+ /* since is_fnmatch(conf->d) was being called so frequently in
+ * directory_walk() and its relatives, this field was created and
+ * is set to the result of that call.
+ */
+ unsigned d_is_fnmatch : 1;
+
+ /* System Resource Control */
+#ifdef RLIMIT_CPU
+ struct rlimit *limit_cpu;
+#endif
+#if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)
+ struct rlimit *limit_mem;
+#endif
+#ifdef RLIMIT_NPROC
+ struct rlimit *limit_nproc;
+#endif
+ unsigned long limit_req_body; /* limit on bytes in request msg body */
+
+ /* logging options */
+ enum { srv_sig_unset, srv_sig_off, srv_sig_on,
+ srv_sig_withmail } server_signature;
+ int loglevel;
+
+ /* Access control */
+ array_header *sec;
+ regex_t *r;
+
+#ifdef WIN32
+ /* Where to find interpreter to run scripts */
+ interpreter_source_e script_interpreter_source;
+#endif
+
+} core_dir_config;
+
+/* Per-server core configuration */
+
+typedef struct {
+
+#ifdef GPROF
+ char *gprof_dir;
+#endif
+
+ /* Name translations --- we want the core to be able to do *something*
+ * so it's at least a minimally functional web server on its own (and
+ * can be tested that way). But let's keep it to the bare minimum:
+ */
+ char *ap_document_root;
+
+ /* Access control */
+
+ char *access_name;
+ array_header *sec;
+ array_header *sec_url;
+} core_server_config;
+
+/* for http_config.c */
+void ap_core_reorder_directories(pool *, server_rec *);
+
+/* for mod_perl */
+CORE_EXPORT(void) ap_add_per_dir_conf (server_rec *s, void *dir_config);
+CORE_EXPORT(void) ap_add_per_url_conf (server_rec *s, void *url_config);
+CORE_EXPORT(void) ap_add_file_conf(core_dir_config *conf, void *url_config);
+CORE_EXPORT_NONSTD(const char *) ap_limit_section (cmd_parms *cmd, void *dummy, const char *arg);
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !APACHE_HTTP_CORE_H */
diff --git a/include/http_log.h b/include/http_log.h
new file mode 100644
index 00000000000..d9162bd22fb
--- /dev/null
+++ b/include/http_log.h
@@ -0,0 +1,162 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+#ifndef APACHE_HTTP_LOG_H
+#define APACHE_HTTP_LOG_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifdef HAVE_SYSLOG
+#include
+
+#define APLOG_EMERG LOG_EMERG /* system is unusable */
+#define APLOG_ALERT LOG_ALERT /* action must be taken immediately */
+#define APLOG_CRIT LOG_CRIT /* critical conditions */
+#define APLOG_ERR LOG_ERR /* error conditions */
+#define APLOG_WARNING LOG_WARNING /* warning conditions */
+#define APLOG_NOTICE LOG_NOTICE /* normal but significant condition */
+#define APLOG_INFO LOG_INFO /* informational */
+#define APLOG_DEBUG LOG_DEBUG /* debug-level messages */
+
+#define APLOG_LEVELMASK LOG_PRIMASK /* mask off the level value */
+
+#else
+
+#define APLOG_EMERG 0 /* system is unusable */
+#define APLOG_ALERT 1 /* action must be taken immediately */
+#define APLOG_CRIT 2 /* critical conditions */
+#define APLOG_ERR 3 /* error conditions */
+#define APLOG_WARNING 4 /* warning conditions */
+#define APLOG_NOTICE 5 /* normal but significant condition */
+#define APLOG_INFO 6 /* informational */
+#define APLOG_DEBUG 7 /* debug-level messages */
+
+#define APLOG_LEVELMASK 7 /* mask off the level value */
+
+#endif
+
+#define APLOG_NOERRNO (APLOG_LEVELMASK + 1)
+#ifdef WIN32
+/* Set to indicate that error msg should come from Win32's GetLastError(),
+ * not errno. */
+#define APLOG_WIN32ERROR ((APLOG_LEVELMASK+1) * 2)
+#endif
+
+#ifndef DEFAULT_LOGLEVEL
+#define DEFAULT_LOGLEVEL APLOG_WARNING
+#endif
+
+#define APLOG_MARK __FILE__,__LINE__
+
+void ap_open_logs (server_rec *, pool *p);
+
+/* The two primary logging functions, ap_log_error and ap_log_rerror,
+ * use a printf style format string to build the log message. It is
+ * VERY IMPORTANT that you not include any raw data from the network,
+ * such as the request-URI or request header fields, within the format
+ * string. Doing so makes the server vulnerable to a denial-of-service
+ * attack and other messy behavior. Instead, use a simple format string
+ * like "%s", followed by the string containing the untrusted data.
+ */
+API_EXPORT(void) ap_log_error(const char *file, int line, int level,
+ const server_rec *s, const char *fmt, ...)
+ __attribute__((format(printf,5,6)));
+API_EXPORT(void) ap_log_rerror(const char *file, int line, int level,
+ const request_rec *s, const char *fmt, ...)
+ __attribute__((format(printf,5,6)));
+API_EXPORT(void) ap_error_log2stderr (server_rec *);
+
+void ap_log_pid (pool *p, char *fname);
+/* These are for legacy code, new code should use ap_log_error,
+ * or ap_log_rerror.
+ */
+API_EXPORT(void) ap_log_error_old(const char *err, server_rec *s);
+API_EXPORT(void) ap_log_unixerr(const char *routine, const char *file,
+ const char *msg, server_rec *s);
+API_EXPORT(void) ap_log_printf(const server_rec *s, const char *fmt, ...)
+ __attribute__((format(printf,2,3)));
+API_EXPORT(void) ap_log_reason(const char *reason, const char *fname,
+ request_rec *r);
+
+typedef struct piped_log {
+ pool *p;
+#ifndef NO_RELIABLE_PIPED_LOGS
+ char *program;
+ int pid;
+ int fds[2];
+#else
+ FILE *write_f;
+#endif
+} piped_log;
+
+API_EXPORT(piped_log *) ap_open_piped_log (pool *p, const char *program);
+API_EXPORT(void) ap_close_piped_log (piped_log *);
+#ifndef NO_RELIABLE_PIPED_LOGS
+#define ap_piped_log_read_fd(pl) ((pl)->fds[0])
+#define ap_piped_log_write_fd(pl) ((pl)->fds[1])
+#else
+#define ap_piped_log_read_fd(pl) (-1)
+#define ap_piped_log_write_fd(pl) (fileno((pl)->write_f))
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !APACHE_HTTP_LOG_H */
diff --git a/include/http_main.h b/include/http_main.h
new file mode 100644
index 00000000000..a0d014de785
--- /dev/null
+++ b/include/http_main.h
@@ -0,0 +1,174 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+#ifndef APACHE_HTTP_MAIN_H
+#define APACHE_HTTP_MAIN_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Routines in http_main.c which other code --- in particular modules ---
+ * may want to call. Right now, that's limited to timeout handling.
+ * There are two functions which modules can call to trigger a timeout
+ * (with the per-virtual-server timeout duration); these are hard_timeout
+ * and soft_timeout.
+ *
+ * The difference between the two is what happens when the timeout
+ * expires (or earlier than that, if the client connection aborts) ---
+ * a soft_timeout just puts the connection to the client in an
+ * "aborted" state, which will cause http_protocol.c to stop trying to
+ * talk to the client, but otherwise allows the code to continue normally.
+ * hard_timeout(), by contrast, logs the request, and then aborts it
+ * completely --- longjmp()ing out to the accept() loop in http_main.
+ * Any resources tied into the request's resource pool will be cleaned up;
+ * everything that isn't will leak.
+ *
+ * soft_timeout() is recommended as a general rule, because it gives your
+ * code a chance to clean up. However, hard_timeout() may be the most
+ * convenient way of dealing with timeouts waiting for some external
+ * resource other than the client, if you can live with the restrictions.
+ *
+ * (When a hard timeout is in scope, critical sections can be guarded
+ * with block_alarms() and unblock_alarms() --- these are declared in
+ * alloc.c because they are most often used in conjunction with
+ * routines to allocate something or other, to make sure that the
+ * cleanup does get registered before any alarm is allowed to happen
+ * which might require it to be cleaned up; they * are, however,
+ * implemented in http_main.c).
+ *
+ * NOTE! It's not "fair" for a hard_timeout to be in scope through calls
+ * across modules. Your module code really has no idea what other modules may
+ * be present in the server, and they may not take too kindly to having a
+ * longjmp() happen -- it could result in corrupted state. Heck they may not
+ * even take to kindly to a soft_timeout()... because it can cause EINTR to
+ * happen on pretty much any syscall, and unless all the libraries and modules
+ * in use are known to deal well with EINTR it could cause corruption as well.
+ * But things are likely to do much better with a soft_timeout in scope than a
+ * hard_timeout.
+ *
+ * A module MAY NOT use a hard_timeout() across * sub_req_lookup_xxx()
+ * functions, or across run_sub_request() functions. A module SHOULD NOT use a
+ * soft_timeout() in either of these cases, but sometimes there's just no
+ * choice.
+ *
+ * kill_timeout() will disarm either variety of timeout.
+ *
+ * reset_timeout() resets the timeout in progress.
+ */
+
+void ap_start_shutdown(void);
+void ap_start_restart(int);
+API_EXPORT(void) ap_hard_timeout(char *, request_rec *);
+void ap_keepalive_timeout(char *, request_rec *);
+API_EXPORT(void) ap_soft_timeout(char *, request_rec *);
+API_EXPORT(void) ap_kill_timeout(request_rec *);
+API_EXPORT(void) ap_reset_timeout(request_rec *);
+
+API_EXPORT(void) ap_child_terminate(request_rec *r);
+API_EXPORT(void) ap_sync_scoreboard_image(void);
+int ap_update_child_status(int child_num, int status, request_rec *r);
+void ap_time_process_request(int child_num, int status);
+unsigned int ap_set_callback_and_alarm(void (*fn) (int), int x);
+API_EXPORT(int) ap_check_alarm(void);
+
+#ifndef NO_OTHER_CHILD
+/*
+ * register an other_child -- a child which the main loop keeps track of
+ * and knows it is different than the rest of the scoreboard.
+ *
+ * pid is the pid of the child.
+ *
+ * maintenance is a function that is invoked with a reason, the data
+ * pointer passed here, and when appropriate a status result from waitpid().
+ *
+ * write_fd is an fd that is probed for writing by select() if it is ever
+ * unwritable, then maintenance is invoked with reason OC_REASON_UNWRITABLE.
+ * This is useful for log pipe children, to know when they've blocked. To
+ * disable this feature, use -1 for write_fd.
+ */
+API_EXPORT(void) ap_register_other_child(int pid,
+ void (*maintenance) (int reason, void *data, ap_wait_t status), void *data,
+ int write_fd);
+#define OC_REASON_DEATH 0 /* child has died, caller must call
+ * unregister still */
+#define OC_REASON_UNWRITABLE 1 /* write_fd is unwritable */
+#define OC_REASON_RESTART 2 /* a restart is occuring, perform
+ * any necessary cleanup (including
+ * sending a special signal to child)
+ */
+#define OC_REASON_UNREGISTER 3 /* unregister has been called, do
+ * whatever is necessary (including
+ * kill the child) */
+#define OC_REASON_LOST 4 /* somehow the child exited without
+ * us knowing ... buggy os? */
+
+/*
+ * unregister an other_child. Note that the data pointer is used here, and
+ * is assumed to be unique per other_child. This is because the pid and
+ * write_fd are possibly killed off separately.
+ */
+API_EXPORT(void) ap_unregister_other_child(void *data);
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !APACHE_HTTP_MAIN_H */
diff --git a/include/http_protocol.h b/include/http_protocol.h
new file mode 100644
index 00000000000..3824c1aba06
--- /dev/null
+++ b/include/http_protocol.h
@@ -0,0 +1,223 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+#ifndef APACHE_HTTP_PROTOCOL_H
+#define APACHE_HTTP_PROTOCOL_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Prototypes for routines which either talk directly back to the user,
+ * or control the ones that eventually do.
+ */
+
+/* Read a request and fill in the fields. */
+
+request_rec *ap_read_request(conn_rec *c);
+
+/* Send a single HTTP header field */
+
+API_EXPORT_NONSTD(int) ap_send_header_field(request_rec *r, const char *fieldname,
+ const char *fieldval);
+
+/* Send the minimal part of an HTTP response header... but modules should be
+ * very careful about using this, and should prefer ap_send_http_header().
+ * Much of the HTTP/1.1 implementation correctness depends on code in
+ * ap_send_http_header().
+ */
+API_EXPORT(void) ap_basic_http_header(request_rec *r);
+
+/* Send the Status-Line and header fields for HTTP response */
+
+API_EXPORT(void) ap_send_http_header(request_rec *l);
+
+/* Send the response to special method requests */
+
+API_EXPORT(int) ap_send_http_trace(request_rec *r);
+int ap_send_http_options(request_rec *r);
+
+/* Finish up stuff after a request */
+
+API_EXPORT(void) ap_finalize_request_protocol(request_rec *r);
+
+/* Send error back to client... last arg indicates error status in case
+ * we get an error in the process of trying to deal with an ErrorDocument
+ * to handle some other error. In that case, we print the default report
+ * for the first thing that went wrong, and more briefly report on the
+ * problem with the ErrorDocument.
+ */
+
+void ap_send_error_response(request_rec *r, int recursive_error);
+
+/* Set last modified header line from the lastmod date of the associated file.
+ * Also, set content length.
+ *
+ * May return an error status, typically USE_LOCAL_COPY (that when the
+ * permit_cache argument is set to one).
+ */
+
+API_EXPORT(int) ap_set_content_length(request_rec *r, long length);
+API_EXPORT(int) ap_set_keepalive(request_rec *r);
+API_EXPORT(time_t) ap_rationalize_mtime(request_rec *r, time_t mtime);
+API_EXPORT(char *) ap_make_etag(request_rec *r, int force_weak);
+API_EXPORT(void) ap_set_etag(request_rec *r);
+API_EXPORT(void) ap_set_last_modified(request_rec *r);
+API_EXPORT(int) ap_meets_conditions(request_rec *r);
+
+/* Other ways to send stuff at the client. All of these keep track
+ * of bytes_sent automatically. This indirection is intended to make
+ * it a little more painless to slide things like HTTP-NG packetization
+ * underneath the main body of the code later. In the meantime, it lets
+ * us centralize a bit of accounting (bytes_sent).
+ *
+ * These also return the number of bytes written by the call.
+ * They should only be called with a timeout registered, for obvious reaasons.
+ * (Ditto the send_header stuff).
+ */
+
+API_EXPORT(long) ap_send_fd(FILE *f, request_rec *r);
+API_EXPORT(long) ap_send_fd_length(FILE *f, request_rec *r, long length);
+
+API_EXPORT(long) ap_send_fb(BUFF *f, request_rec *r);
+API_EXPORT(long) ap_send_fb_length(BUFF *f, request_rec *r, long length);
+
+API_EXPORT(size_t) ap_send_mmap(void *mm, request_rec *r, size_t offset,
+ size_t length);
+
+/* Hmmm... could macrofy these for now, and maybe forever, though the
+ * definitions of the macros would get a whole lot hairier.
+ */
+
+API_EXPORT(int) ap_rputc(int c, request_rec *r);
+API_EXPORT(int) ap_rputs(const char *str, request_rec *r);
+API_EXPORT(int) ap_rwrite(const void *buf, int nbyte, request_rec *r);
+API_EXPORT_NONSTD(int) ap_rvputs(request_rec *r,...);
+API_EXPORT(int) ap_vrprintf(request_rec *r, const char *fmt, va_list vlist);
+API_EXPORT_NONSTD(int) ap_rprintf(request_rec *r, const char *fmt,...)
+ __attribute__((format(printf,2,3)));
+API_EXPORT(int) ap_rflush(request_rec *r);
+
+/*
+ * Index used in custom_responses array for a specific error code
+ * (only use outside protocol.c is in getting them configured).
+ */
+
+API_EXPORT(int) ap_index_of_response(int status);
+
+/* Reading a block of data from the client connection (e.g., POST arg) */
+
+API_EXPORT(int) ap_setup_client_block(request_rec *r, int read_policy);
+API_EXPORT(int) ap_should_client_block(request_rec *r);
+API_EXPORT(long) ap_get_client_block(request_rec *r, char *buffer, int bufsiz);
+API_EXPORT(int) ap_discard_request_body(request_rec *r);
+
+/* Sending a byterange */
+
+API_EXPORT(int) ap_set_byterange(request_rec *r);
+API_EXPORT(int) ap_each_byterange(request_rec *r, long *offset, long *length);
+
+/* Support for the Basic authentication protocol. Note that there's
+ * nothing that prevents these from being in mod_auth.c, except that other
+ * modules which wanted to provide their own variants on finding users and
+ * passwords for Basic auth (a fairly common request) would then require
+ * mod_auth to be loaded or they wouldn't work.
+ *
+ * get_basic_auth_pw returns 0 (OK) if it set the 'pw' argument (and assured
+ * a correct value in r->connection->user); otherwise it returns an error
+ * code, either SERVER_ERROR if things are really confused, AUTH_REQUIRED
+ * if no authentication at all seemed to be in use, or DECLINED if there
+ * was authentication but it wasn't Basic (in which case, the caller should
+ * presumably decline as well).
+ *
+ * note_basic_auth_failure arranges for the right stuff to be scribbled on
+ * the HTTP return so that the client knows how to authenticate itself the
+ * next time. As does note_digest_auth_failure for Digest auth.
+ *
+ * note_auth_failure does the same thing, but will call the correct one
+ * based on the authentication type in use.
+ *
+ */
+
+API_EXPORT(void) ap_note_auth_failure(request_rec *r);
+API_EXPORT(void) ap_note_basic_auth_failure(request_rec *r);
+API_EXPORT(void) ap_note_digest_auth_failure(request_rec *r);
+API_EXPORT(int) ap_get_basic_auth_pw(request_rec *r, const char **pw);
+
+/*
+ * Setting up the protocol fields for subsidiary requests...
+ * Also, a wrapup function to keep the internal accounting straight.
+ */
+
+void ap_set_sub_req_protocol(request_rec *rnew, const request_rec *r);
+void ap_finalize_sub_req_protocol(request_rec *sub_r);
+
+/* This is also useful for putting sub_reqs and internal_redirects together */
+
+CORE_EXPORT(void) ap_parse_uri(request_rec *r, const char *uri);
+
+/* Get the method number associated with the given string, assumed to
+ * contain an HTTP method. Returns M_INVALID if not recognized.
+ */
+API_EXPORT(int) ap_method_number_of(const char *method);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !APACHE_HTTP_PROTOCOL_H */
diff --git a/include/http_request.h b/include/http_request.h
new file mode 100644
index 00000000000..4d83c543d6a
--- /dev/null
+++ b/include/http_request.h
@@ -0,0 +1,117 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+#ifndef APACHE_HTTP_REQUEST_H
+#define APACHE_HTTP_REQUEST_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* http_request.c is the code which handles the main line of request
+ * processing, once a request has been read in (finding the right per-
+ * directory configuration, building it if necessary, and calling all
+ * the module dispatch functions in the right order).
+ *
+ * The pieces here which are public to the modules, allow them to learn
+ * how the server would handle some other file or URI, or perhaps even
+ * direct the server to serve that other file instead of the one the
+ * client requested directly.
+ *
+ * There are two ways to do that. The first is the sub_request mechanism,
+ * which handles looking up files and URIs as adjuncts to some other
+ * request (e.g., directory entries for multiviews and directory listings);
+ * the lookup functions stop short of actually running the request, but
+ * (e.g., for includes), a module may call for the request to be run
+ * by calling run_sub_req. The space allocated to create sub_reqs can be
+ * reclaimed by calling destroy_sub_req --- be sure to copy anything you care
+ * about which was allocated in its pool elsewhere before doing this.
+ */
+
+API_EXPORT(request_rec *) ap_sub_req_lookup_uri(const char *new_file,
+ const request_rec *r);
+API_EXPORT(request_rec *) ap_sub_req_lookup_file(const char *new_file,
+ const request_rec *r);
+API_EXPORT(request_rec *) ap_sub_req_method_uri(const char *method,
+ const char *new_file,
+ const request_rec *r);
+API_EXPORT(int) ap_run_sub_req(request_rec *r);
+API_EXPORT(void) ap_destroy_sub_req(request_rec *r);
+
+/*
+ * Then there's the case that you want some other request to be served
+ * as the top-level request INSTEAD of what the client requested directly.
+ * If so, call this from a handler, and then immediately return OK.
+ */
+
+API_EXPORT(void) ap_internal_redirect(const char *new_uri, request_rec *);
+API_EXPORT(void) ap_internal_redirect_handler(const char *new_uri, request_rec *);
+API_EXPORT(int) ap_some_auth_required(request_rec *r);
+API_EXPORT(int) ap_is_initial_req(request_rec *r);
+API_EXPORT(time_t) ap_update_mtime(request_rec *r, time_t dependency_mtime);
+
+#ifdef CORE_PRIVATE
+/* Function called by main.c to handle first-level request */
+void ap_process_request(request_rec *);
+API_EXPORT(void) ap_die(int type, request_rec *r);
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !APACHE_HTTP_REQUEST_H */
diff --git a/include/http_vhost.h b/include/http_vhost.h
new file mode 100644
index 00000000000..acdb6e2f426
--- /dev/null
+++ b/include/http_vhost.h
@@ -0,0 +1,95 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+#ifndef APACHE_HTTP_VHOST_H
+#define APACHE_HTTP_VHOST_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* called before any config is read */
+void ap_init_vhost_config(pool *p);
+
+/* called after the config has been read */
+void ap_fini_vhost_config(pool *p, server_rec *main_server);
+
+/* handle addresses in statement */
+const char *ap_parse_vhost_addrs(pool *p, const char *hostname, server_rec *s);
+
+/* handle NameVirtualHost directive */
+const char *ap_set_name_virtual_host (cmd_parms *cmd, void *dummy, char *arg);
+
+/* given an ip address only, give our best guess as to what vhost it is */
+void ap_update_vhost_given_ip(conn_rec *conn);
+
+/* The above is never enough, and this is always called after the headers
+ * have been read. It may change r->server.
+ */
+void ap_update_vhost_from_headers(request_rec *r);
+
+/* return 1 if the host:port matches any of the aliases of r->server
+ * return 0 otherwise
+ */
+API_EXPORT(int) ap_matches_request_vhost(request_rec *r, const char *host,
+ unsigned port);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !APACHE_HTTP_VHOST_H */
diff --git a/include/httpd.h b/include/httpd.h
new file mode 100644
index 00000000000..7f19d99cc52
--- /dev/null
+++ b/include/httpd.h
@@ -0,0 +1,1167 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+#ifndef APACHE_HTTPD_H
+#define APACHE_HTTPD_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * httpd.h: header for simple (ha! not anymore) http daemon
+ */
+
+/* Headers in which EVERYONE has an interest... */
+
+#include "ap_config.h"
+#include "alloc.h"
+#include "buff.h"
+#include "ap.h"
+
+/* ----------------------------- config dir ------------------------------ */
+
+/* Define this to be the default server home dir. Most things later in this
+ * file with a relative pathname will have this added.
+ */
+#ifndef HTTPD_ROOT
+#ifdef OS2
+/* Set default for OS/2 file system */
+#define HTTPD_ROOT "/os2httpd"
+#elif defined(WIN32)
+/* Set default for Windows file system */
+#define HTTPD_ROOT "/apache"
+#elif defined(BEOS)
+#define HTTPD_ROOT "/boot/home/apache"
+#else
+#define HTTPD_ROOT "/usr/local/apache"
+#endif
+#endif /* HTTPD_ROOT */
+
+/* Default location of documents. Can be overridden by the DocumentRoot
+ * directive.
+ */
+#ifndef DOCUMENT_LOCATION
+#ifdef OS2
+/* Set default for OS/2 file system */
+#define DOCUMENT_LOCATION HTTPD_ROOT "/docs"
+#else
+#define DOCUMENT_LOCATION HTTPD_ROOT "/htdocs"
+#endif
+#endif /* DOCUMENT_LOCATION */
+
+/* Max. number of dynamically loaded modules */
+#ifndef DYNAMIC_MODULE_LIMIT
+#define DYNAMIC_MODULE_LIMIT 64
+#endif
+
+/* Default administrator's address */
+#define DEFAULT_ADMIN "[no address given]"
+
+/* The target name of the installed Apache */
+#ifndef TARGET
+#define TARGET "httpd"
+#endif
+
+/*
+ * --------- You shouldn't have to edit anything below this line ----------
+ *
+ * Any modifications to any defaults not defined above should be done in the
+ * respective config. file.
+ *
+ */
+
+
+/* -- Internal representation for a HTTP protocol number, e.g., HTTP/1.1 -- */
+
+#define HTTP_VERSION(major,minor) (1000*(major)+(minor))
+#define HTTP_VERSION_MAJOR(number) ((number)/1000)
+#define HTTP_VERSION_MINOR(number) ((number)%1000)
+
+
+/* -------------- Port number for server running standalone --------------- */
+
+#define DEFAULT_HTTP_PORT 80
+#define DEFAULT_HTTPS_PORT 443
+#define ap_is_default_port(port,r) ((port) == ap_default_port(r))
+#define ap_http_method(r) "http"
+#define ap_default_port(r) DEFAULT_HTTP_PORT
+
+/* --------- Default user name and group name running standalone ---------- */
+/* --- These may be specified as numbers by placing a # before a number --- */
+
+#ifndef DEFAULT_USER
+#define DEFAULT_USER "#-1"
+#endif
+#ifndef DEFAULT_GROUP
+#define DEFAULT_GROUP "#-1"
+#endif
+
+/* The name of the log files */
+#ifndef DEFAULT_XFERLOG
+#if defined(OS2) || defined(WIN32)
+#define DEFAULT_XFERLOG "logs/access.log"
+#else
+#define DEFAULT_XFERLOG "logs/access_log"
+#endif
+#endif /* DEFAULT_XFERLOG */
+
+#ifndef DEFAULT_ERRORLOG
+#if defined(OS2) || defined(WIN32)
+#define DEFAULT_ERRORLOG "logs/error.log"
+#else
+#define DEFAULT_ERRORLOG "logs/error_log"
+#endif
+#endif /* DEFAULT_ERRORLOG */
+
+#ifndef DEFAULT_PIDLOG
+#define DEFAULT_PIDLOG "logs/httpd.pid"
+#endif
+#ifndef DEFAULT_SCOREBOARD
+#define DEFAULT_SCOREBOARD "logs/apache_runtime_status"
+#endif
+#ifndef DEFAULT_LOCKFILE
+#define DEFAULT_LOCKFILE "logs/accept.lock"
+#endif
+
+/* Define this to be what your HTML directory content files are called */
+#ifndef DEFAULT_INDEX
+#define DEFAULT_INDEX "index.html"
+#endif
+
+/* Define this to 1 if you want fancy indexing, 0 otherwise */
+#ifndef DEFAULT_INDEXING
+#define DEFAULT_INDEXING 0
+#endif
+
+/* Define this to be what type you'd like returned for files with unknown */
+/* suffixes. MUST be all lower case. */
+#ifndef DEFAULT_CONTENT_TYPE
+#define DEFAULT_CONTENT_TYPE "text/plain"
+#endif
+
+/* Define this to be what your per-directory security files are called */
+#ifndef DEFAULT_ACCESS_FNAME
+#ifdef OS2
+/* Set default for OS/2 file system */
+#define DEFAULT_ACCESS_FNAME "htaccess"
+#else
+#define DEFAULT_ACCESS_FNAME ".htaccess"
+#endif
+#endif /* DEFAULT_ACCESS_FNAME */
+
+/* The name of the server config file */
+#ifndef SERVER_CONFIG_FILE
+#define SERVER_CONFIG_FILE "conf/httpd.conf"
+#endif
+
+/* The name of the document config file */
+#ifndef RESOURCE_CONFIG_FILE
+#define RESOURCE_CONFIG_FILE "conf/srm.conf"
+#endif
+
+/* The name of the MIME types file */
+#ifndef TYPES_CONFIG_FILE
+#define TYPES_CONFIG_FILE "conf/mime.types"
+#endif
+
+/* The name of the access file */
+#ifndef ACCESS_CONFIG_FILE
+#define ACCESS_CONFIG_FILE "conf/access.conf"
+#endif
+
+/* Whether we should enable rfc1413 identity checking */
+#ifndef DEFAULT_RFC1413
+#define DEFAULT_RFC1413 0
+#endif
+/* The default directory in user's home dir */
+#ifndef DEFAULT_USER_DIR
+#define DEFAULT_USER_DIR "public_html"
+#endif
+
+/* The default path for CGI scripts if none is currently set */
+#ifndef DEFAULT_PATH
+#define DEFAULT_PATH "/bin:/usr/bin:/usr/ucb:/usr/bsd:/usr/local/bin"
+#endif
+
+/* The path to the shell interpreter, for parsed docs */
+#ifndef SHELL_PATH
+#if defined(OS2) || defined(WIN32)
+/* Set default for OS/2 and Windows file system */
+#define SHELL_PATH "CMD.EXE"
+#else
+#define SHELL_PATH "/bin/sh"
+#endif
+#endif /* SHELL_PATH */
+
+/* The path to the suExec wrapper, can be overridden in Configuration */
+#ifndef SUEXEC_BIN
+#define SUEXEC_BIN HTTPD_ROOT "/sbin/suexec"
+#endif
+
+/* The default string lengths */
+#define MAX_STRING_LEN HUGE_STRING_LEN
+#define HUGE_STRING_LEN 8192
+
+/* The timeout for waiting for messages */
+#ifndef DEFAULT_TIMEOUT
+#define DEFAULT_TIMEOUT 300
+#endif
+
+/* The timeout for waiting for keepalive timeout until next request */
+#ifndef DEFAULT_KEEPALIVE_TIMEOUT
+#define DEFAULT_KEEPALIVE_TIMEOUT 15
+#endif
+
+/* The number of requests to entertain per connection */
+#ifndef DEFAULT_KEEPALIVE
+#define DEFAULT_KEEPALIVE 100
+#endif
+
+/* The size of the server's internal read-write buffers */
+#define IOBUFSIZE 8192
+
+/* Number of servers to spawn off by default --- also, if fewer than
+ * this free when the caretaker checks, it will spawn more.
+ */
+#ifndef DEFAULT_START_DAEMON
+#define DEFAULT_START_DAEMON 5
+#endif
+
+/* Maximum number of *free* server processes --- more than this, and
+ * they will die off.
+ */
+
+#ifndef DEFAULT_MAX_FREE_DAEMON
+#define DEFAULT_MAX_FREE_DAEMON 10
+#endif
+
+/* Minimum --- fewer than this, and more will be created */
+
+#ifndef DEFAULT_MIN_FREE_DAEMON
+#define DEFAULT_MIN_FREE_DAEMON 5
+#endif
+
+/* Limit on the total --- clients will be locked out if more servers than
+ * this are needed. It is intended solely to keep the server from crashing
+ * when things get out of hand.
+ *
+ * We keep a hard maximum number of servers, for two reasons --- first off,
+ * in case something goes seriously wrong, we want to stop the fork bomb
+ * short of actually crashing the machine we're running on by filling some
+ * kernel table. Secondly, it keeps the size of the scoreboard file small
+ * enough that we can read the whole thing without worrying too much about
+ * the overhead.
+ */
+#ifndef HARD_SERVER_LIMIT
+#ifdef WIN32
+#define HARD_SERVER_LIMIT 1024
+#else
+#define HARD_SERVER_LIMIT 256
+#endif
+#endif
+
+/*
+ * Special Apache error codes. These are basically used
+ * in http_main.c so we can keep track of various errors.
+ *
+ * APEXIT_OK:
+ * A normal exit
+ * APEXIT_INIT:
+ * A fatal error arising during the server's init sequence
+ * APEXIT_CHILDINIT:
+ * The child died during it's init sequence
+ * APEXIT_CHILDFATAL:
+ * A fatal error, resulting in the whole server aborting.
+ * If a child exits with this error, the parent process
+ * considers this a server-wide fatal error and aborts.
+ *
+ */
+#define APEXIT_OK 0x0
+#define APEXIT_INIT 0x2
+#define APEXIT_CHILDINIT 0x3
+#define APEXIT_CHILDFATAL 0xf
+
+/*
+ * (Unix, OS/2 only)
+ * Interval, in microseconds, between scoreboard maintenance. During
+ * each scoreboard maintenance cycle the parent decides if it needs to
+ * spawn a new child (to meet MinSpareServers requirements), or kill off
+ * a child (to meet MaxSpareServers requirements). It will only spawn or
+ * kill one child per cycle. Setting this too low will chew cpu. The
+ * default is probably sufficient for everyone. But some people may want
+ * to raise this on servers which aren't dedicated to httpd and where they
+ * don't like the httpd waking up each second to see what's going on.
+ */
+#ifndef SCOREBOARD_MAINTENANCE_INTERVAL
+#define SCOREBOARD_MAINTENANCE_INTERVAL 1000000
+#endif
+
+/* Number of requests to try to handle in a single process. If <= 0,
+ * the children don't die off. That's the default here, since I'm still
+ * interested in finding and stanching leaks.
+ */
+
+#ifndef DEFAULT_MAX_REQUESTS_PER_CHILD
+#define DEFAULT_MAX_REQUESTS_PER_CHILD 0
+#endif
+
+#ifndef DEFAULT_THREADS_PER_CHILD
+#define DEFAULT_THREADS_PER_CHILD 50
+#endif
+#ifndef DEFAULT_EXCESS_REQUESTS_PER_CHILD
+#define DEFAULT_EXCESS_REQUESTS_PER_CHILD 0
+#endif
+
+/* The maximum length of the queue of pending connections, as defined
+ * by listen(2). Under some systems, it should be increased if you
+ * are experiencing a heavy TCP SYN flood attack.
+ *
+ * It defaults to 511 instead of 512 because some systems store it
+ * as an 8-bit datatype; 512 truncated to 8-bits is 0, while 511 is
+ * 255 when truncated.
+ */
+
+#ifndef DEFAULT_LISTENBACKLOG
+#define DEFAULT_LISTENBACKLOG 511
+#endif
+
+/* Limits on the size of various request items. These limits primarily
+ * exist to prevent simple denial-of-service attacks on a server based
+ * on misuse of the protocol. The recommended values will depend on the
+ * nature of the server resources -- CGI scripts and database backends
+ * might require large values, but most servers could get by with much
+ * smaller limits than we use below. The request message body size can
+ * be limited by the per-dir config directive LimitRequestBody.
+ *
+ * Internal buffer sizes are two bytes more than the DEFAULT_LIMIT_REQUEST_LINE
+ * and DEFAULT_LIMIT_REQUEST_FIELDSIZE below, which explains the 8190.
+ * These two limits can be lowered (but not raised) by the server config
+ * directives LimitRequestLine and LimitRequestFieldsize, respectively.
+ *
+ * DEFAULT_LIMIT_REQUEST_FIELDS can be modified or disabled (set = 0) by
+ * the server config directive LimitRequestFields.
+ */
+#ifndef DEFAULT_LIMIT_REQUEST_LINE
+#define DEFAULT_LIMIT_REQUEST_LINE 8190
+#endif /* default limit on bytes in Request-Line (Method+URI+HTTP-version) */
+#ifndef DEFAULT_LIMIT_REQUEST_FIELDSIZE
+#define DEFAULT_LIMIT_REQUEST_FIELDSIZE 8190
+#endif /* default limit on bytes in any one header field */
+#ifndef DEFAULT_LIMIT_REQUEST_FIELDS
+#define DEFAULT_LIMIT_REQUEST_FIELDS 100
+#endif /* default limit on number of request header fields */
+
+/*
+ * The below defines the base string of the Server: header. Additional
+ * tokens can be added via the ap_add_version_component() API call.
+ *
+ * The tokens are listed in order of their significance for identifying the
+ * application.
+ *
+ * "Product tokens should be short and to the point -- use of them for
+ * advertizing or other non-essential information is explicitly forbidden."
+ *
+ * Example: "Apache/1.1.0 MrWidget/0.1-alpha"
+ */
+
+#define SERVER_BASEVERSION "Apache/1.3.9" /* SEE COMMENTS ABOVE */
+#define SERVER_VERSION SERVER_BASEVERSION
+enum server_token_type {
+ SrvTk_MIN, /* eg: Apache/1.3.0 */
+ SrvTk_OS, /* eg: Apache/1.3.0 (UNIX) */
+ SrvTk_FULL /* eg: Apache/1.3.0 (UNIX) PHP/3.0 FooBar/1.2b */
+};
+
+API_EXPORT(const char *) ap_get_server_version(void);
+API_EXPORT(void) ap_add_version_component(const char *component);
+API_EXPORT(const char *) ap_get_server_built(void);
+
+/* Numeric release version identifier: MMNNFFRBB: major minor fix final beta
+ * Always increases along the same track as the source branch.
+ * For example, Apache 1.4.2 would be '10402100', 2.5b7 would be '20500007'.
+ */
+#define APACHE_RELEASE 10309100
+
+#define SERVER_PROTOCOL "HTTP/1.1"
+#ifndef SERVER_SUPPORT
+#define SERVER_SUPPORT "http://www.apache.org/"
+#endif
+
+#define DECLINED -1 /* Module declines to handle */
+#define DONE -2 /* Module has served the response completely
+ * - it's safe to die() with no more output
+ */
+#define OK 0 /* Module has handled this stage. */
+
+
+/* ----------------------- HTTP Status Codes ------------------------- */
+
+/* The size of the static array in http_protocol.c for storing
+ * all of the potential response status-lines (a sparse table).
+ * A future version should dynamically generate the table at startup.
+ */
+#define RESPONSE_CODES 55
+
+#define HTTP_CONTINUE 100
+#define HTTP_SWITCHING_PROTOCOLS 101
+#define HTTP_PROCESSING 102
+#define HTTP_OK 200
+#define HTTP_CREATED 201
+#define HTTP_ACCEPTED 202
+#define HTTP_NON_AUTHORITATIVE 203
+#define HTTP_NO_CONTENT 204
+#define HTTP_RESET_CONTENT 205
+#define HTTP_PARTIAL_CONTENT 206
+#define HTTP_MULTI_STATUS 207
+#define HTTP_MULTIPLE_CHOICES 300
+#define HTTP_MOVED_PERMANENTLY 301
+#define HTTP_MOVED_TEMPORARILY 302
+#define HTTP_SEE_OTHER 303
+#define HTTP_NOT_MODIFIED 304
+#define HTTP_USE_PROXY 305
+#define HTTP_TEMPORARY_REDIRECT 307
+#define HTTP_BAD_REQUEST 400
+#define HTTP_UNAUTHORIZED 401
+#define HTTP_PAYMENT_REQUIRED 402
+#define HTTP_FORBIDDEN 403
+#define HTTP_NOT_FOUND 404
+#define HTTP_METHOD_NOT_ALLOWED 405
+#define HTTP_NOT_ACCEPTABLE 406
+#define HTTP_PROXY_AUTHENTICATION_REQUIRED 407
+#define HTTP_REQUEST_TIME_OUT 408
+#define HTTP_CONFLICT 409
+#define HTTP_GONE 410
+#define HTTP_LENGTH_REQUIRED 411
+#define HTTP_PRECONDITION_FAILED 412
+#define HTTP_REQUEST_ENTITY_TOO_LARGE 413
+#define HTTP_REQUEST_URI_TOO_LARGE 414
+#define HTTP_UNSUPPORTED_MEDIA_TYPE 415
+#define HTTP_RANGE_NOT_SATISFIABLE 416
+#define HTTP_EXPECTATION_FAILED 417
+#define HTTP_UNPROCESSABLE_ENTITY 422
+#define HTTP_LOCKED 423
+#define HTTP_FAILED_DEPENDENCY 424
+#define HTTP_INTERNAL_SERVER_ERROR 500
+#define HTTP_NOT_IMPLEMENTED 501
+#define HTTP_BAD_GATEWAY 502
+#define HTTP_SERVICE_UNAVAILABLE 503
+#define HTTP_GATEWAY_TIME_OUT 504
+#define HTTP_VERSION_NOT_SUPPORTED 505
+#define HTTP_VARIANT_ALSO_VARIES 506
+#define HTTP_INSUFFICIENT_STORAGE 507
+#define HTTP_NOT_EXTENDED 510
+
+#define DOCUMENT_FOLLOWS HTTP_OK
+#define PARTIAL_CONTENT HTTP_PARTIAL_CONTENT
+#define MULTIPLE_CHOICES HTTP_MULTIPLE_CHOICES
+#define MOVED HTTP_MOVED_PERMANENTLY
+#define REDIRECT HTTP_MOVED_TEMPORARILY
+#define USE_LOCAL_COPY HTTP_NOT_MODIFIED
+#define BAD_REQUEST HTTP_BAD_REQUEST
+#define AUTH_REQUIRED HTTP_UNAUTHORIZED
+#define FORBIDDEN HTTP_FORBIDDEN
+#define NOT_FOUND HTTP_NOT_FOUND
+#define METHOD_NOT_ALLOWED HTTP_METHOD_NOT_ALLOWED
+#define NOT_ACCEPTABLE HTTP_NOT_ACCEPTABLE
+#define LENGTH_REQUIRED HTTP_LENGTH_REQUIRED
+#define PRECONDITION_FAILED HTTP_PRECONDITION_FAILED
+#define SERVER_ERROR HTTP_INTERNAL_SERVER_ERROR
+#define NOT_IMPLEMENTED HTTP_NOT_IMPLEMENTED
+#define BAD_GATEWAY HTTP_BAD_GATEWAY
+#define VARIANT_ALSO_VARIES HTTP_VARIANT_ALSO_VARIES
+
+#define ap_is_HTTP_INFO(x) (((x) >= 100)&&((x) < 200))
+#define ap_is_HTTP_SUCCESS(x) (((x) >= 200)&&((x) < 300))
+#define ap_is_HTTP_REDIRECT(x) (((x) >= 300)&&((x) < 400))
+#define ap_is_HTTP_ERROR(x) (((x) >= 400)&&((x) < 600))
+#define ap_is_HTTP_CLIENT_ERROR(x) (((x) >= 400)&&((x) < 500))
+#define ap_is_HTTP_SERVER_ERROR(x) (((x) >= 500)&&((x) < 600))
+
+#define ap_status_drops_connection(x) \
+ (((x) == HTTP_BAD_REQUEST) || \
+ ((x) == HTTP_REQUEST_TIME_OUT) || \
+ ((x) == HTTP_LENGTH_REQUIRED) || \
+ ((x) == HTTP_REQUEST_ENTITY_TOO_LARGE) || \
+ ((x) == HTTP_REQUEST_URI_TOO_LARGE) || \
+ ((x) == HTTP_INTERNAL_SERVER_ERROR) || \
+ ((x) == HTTP_SERVICE_UNAVAILABLE) || \
+ ((x) == HTTP_NOT_IMPLEMENTED))
+
+/* Methods recognized (but not necessarily handled) by the server.
+ * These constants are used in bit shifting masks of size int, so it is
+ * unsafe to have more methods than bits in an int. HEAD == M_GET.
+ */
+#define M_GET 0
+#define M_PUT 1
+#define M_POST 2
+#define M_DELETE 3
+#define M_CONNECT 4
+#define M_OPTIONS 5
+#define M_TRACE 6
+#define M_PATCH 7
+#define M_PROPFIND 8
+#define M_PROPPATCH 9
+#define M_MKCOL 10
+#define M_COPY 11
+#define M_MOVE 12
+#define M_LOCK 13
+#define M_UNLOCK 14
+#define M_INVALID 15
+
+#define METHODS 16
+
+#define CGI_MAGIC_TYPE "application/x-httpd-cgi"
+#define INCLUDES_MAGIC_TYPE "text/x-server-parsed-html"
+#define INCLUDES_MAGIC_TYPE3 "text/x-server-parsed-html3"
+#ifdef CHARSET_EBCDIC
+#define ASCIITEXT_MAGIC_TYPE_PREFIX "text/x-ascii-" /* Text files whose content-type starts with this are passed thru unconverted */
+#endif /*CHARSET_EBCDIC*/
+#define MAP_FILE_MAGIC_TYPE "application/x-type-map"
+#define ASIS_MAGIC_TYPE "httpd/send-as-is"
+#define DIR_MAGIC_TYPE "httpd/unix-directory"
+#define STATUS_MAGIC_TYPE "application/x-httpd-status"
+
+/*
+ * Define the HTML doctype strings centrally.
+ */
+#define DOCTYPE_HTML_2_0 "\n"
+#define DOCTYPE_HTML_3_2 "\n"
+#define DOCTYPE_HTML_4_0S "\n"
+#define DOCTYPE_HTML_4_0T "\n"
+#define DOCTYPE_HTML_4_0F "\n"
+
+/* Just in case your linefeed isn't the one the other end is expecting. */
+#ifndef CHARSET_EBCDIC
+#define LF 10
+#define CR 13
+#else /* CHARSET_EBCDIC */
+#include "ebcdic.h"
+/* OSD_POSIX uses the EBCDIC charset. The transition ASCII->EBCDIC is done in
+ * the buff package (bread/bputs/bwrite), so everywhere else, we use
+ * "native EBCDIC" CR and NL characters. These are therefore defined as
+ * '\r' and '\n'.
+ * NB: this is not the whole truth - sometimes \015 and \012 are contained
+ * in literal (EBCDIC!) strings, so these are not converted but passed.
+ */
+#define CR '\r'
+#define LF '\n'
+#endif /* CHARSET_EBCDIC */
+
+/* Possible values for request_rec.read_body (set by handling module):
+ * REQUEST_NO_BODY Send 413 error if message has any body
+ * REQUEST_CHUNKED_ERROR Send 411 error if body without Content-Length
+ * REQUEST_CHUNKED_DECHUNK If chunked, remove the chunks for me.
+ * REQUEST_CHUNKED_PASS Pass the chunks to me without removal.
+ */
+#define REQUEST_NO_BODY 0
+#define REQUEST_CHUNKED_ERROR 1
+#define REQUEST_CHUNKED_DECHUNK 2
+#define REQUEST_CHUNKED_PASS 3
+
+/* Things which may vary per file-lookup WITHIN a request ---
+ * e.g., state of MIME config. Basically, the name of an object, info
+ * about the object, and any other info we may ahve which may need to
+ * change as we go poking around looking for it (e.g., overridden by
+ * .htaccess files).
+ *
+ * Note how the default state of almost all these things is properly
+ * zero, so that allocating it with pcalloc does the right thing without
+ * a whole lot of hairy initialization... so long as we are willing to
+ * make the (fairly) portable assumption that the bit pattern of a NULL
+ * pointer is, in fact, zero.
+ */
+
+/* This represents the result of calling htaccess; these are cached for
+ * each request.
+ */
+struct htaccess_result {
+ char *dir; /* the directory to which this applies */
+ int override; /* the overrides allowed for the .htaccess file */
+ void *htaccess; /* the configuration directives */
+/* the next one, or NULL if no more; N.B. never change this */
+ const struct htaccess_result *next;
+};
+
+typedef struct conn_rec conn_rec;
+typedef struct server_rec server_rec;
+typedef struct request_rec request_rec;
+typedef struct listen_rec listen_rec;
+
+#include "util_uri.h"
+
+struct request_rec {
+
+ ap_pool *pool;
+ conn_rec *connection;
+ server_rec *server;
+
+ request_rec *next; /* If we wind up getting redirected,
+ * pointer to the request we redirected to.
+ */
+ request_rec *prev; /* If this is an internal redirect,
+ * pointer to where we redirected *from*.
+ */
+
+ request_rec *main; /* If this is a sub_request (see request.h)
+ * pointer back to the main request.
+ */
+
+ /* Info about the request itself... we begin with stuff that only
+ * protocol.c should ever touch...
+ */
+
+ char *the_request; /* First line of request, so we can log it */
+ int assbackwards; /* HTTP/0.9, "simple" request */
+ int proxyreq; /* A proxy request (calculated during
+ * post_read_request or translate_name) */
+ int header_only; /* HEAD request, as opposed to GET */
+ char *protocol; /* Protocol, as given to us, or HTTP/0.9 */
+ int proto_num; /* Number version of protocol; 1.1 = 1001 */
+ const char *hostname; /* Host, as set by full URI or Host: */
+
+ time_t request_time; /* When the request started */
+
+ const char *status_line; /* Status line, if set by script */
+ int status; /* In any case */
+
+ /* Request method, two ways; also, protocol, etc.. Outside of protocol.c,
+ * look, but don't touch.
+ */
+
+ const char *method; /* GET, HEAD, POST, etc. */
+ int method_number; /* M_GET, M_POST, etc. */
+
+ /*
+ allowed is a bitvector of the allowed methods.
+
+ A handler must ensure that the request method is one that
+ it is capable of handling. Generally modules should DECLINE
+ any request methods they do not handle. Prior to aborting the
+ handler like this the handler should set r->allowed to the list
+ of methods that it is willing to handle. This bitvector is used
+ to construct the "Allow:" header required for OPTIONS requests,
+ and METHOD_NOT_ALLOWED and NOT_IMPLEMENTED status codes.
+
+ Since the default_handler deals with OPTIONS, all modules can
+ usually decline to deal with OPTIONS. TRACE is always allowed,
+ modules don't need to set it explicitly.
+
+ Since the default_handler will always handle a GET, a
+ module which does *not* implement GET should probably return
+ METHOD_NOT_ALLOWED. Unfortunately this means that a Script GET
+ handler can't be installed by mod_actions.
+ */
+ int allowed; /* Allowed methods - for 405, OPTIONS, etc */
+
+ int sent_bodyct; /* byte count in stream is for body */
+ long bytes_sent; /* body byte count, for easy access */
+ time_t mtime; /* Time the resource was last modified */
+
+ /* HTTP/1.1 connection-level features */
+
+ int chunked; /* sending chunked transfer-coding */
+ int byterange; /* number of byte ranges */
+ char *boundary; /* multipart/byteranges boundary */
+ const char *range; /* The Range: header */
+ long clength; /* The "real" content length */
+
+ long remaining; /* bytes left to read */
+ long read_length; /* bytes that have been read */
+ int read_body; /* how the request body should be read */
+ int read_chunked; /* reading chunked transfer-coding */
+ unsigned expecting_100; /* is client waiting for a 100 response? */
+
+ /* MIME header environments, in and out. Also, an array containing
+ * environment variables to be passed to subprocesses, so people can
+ * write modules to add to that environment.
+ *
+ * The difference between headers_out and err_headers_out is that the
+ * latter are printed even on error, and persist across internal redirects
+ * (so the headers printed for ErrorDocument handlers will have them).
+ *
+ * The 'notes' table is for notes from one module to another, with no
+ * other set purpose in mind...
+ */
+
+ table *headers_in;
+ table *headers_out;
+ table *err_headers_out;
+ table *subprocess_env;
+ table *notes;
+
+ /* content_type, handler, content_encoding, content_language, and all
+ * content_languages MUST be lowercased strings. They may be pointers
+ * to static strings; they should not be modified in place.
+ */
+ const char *content_type; /* Break these out --- we dispatch on 'em */
+ const char *handler; /* What we *really* dispatch on */
+
+ const char *content_encoding;
+ const char *content_language; /* for back-compat. only -- do not use */
+ array_header *content_languages; /* array of (char*) */
+
+ char *vlist_validator; /* variant list validator (if negotiated) */
+
+ int no_cache;
+ int no_local_copy;
+
+ /* What object is being requested (either directly, or via include
+ * or content-negotiation mapping).
+ */
+
+ char *unparsed_uri; /* the uri without any parsing performed */
+ char *uri; /* the path portion of the URI */
+ char *filename;
+ char *path_info;
+ char *args; /* QUERY_ARGS, if any */
+ struct stat finfo; /* ST_MODE set to zero if no such file */
+ uri_components parsed_uri; /* components of uri, dismantled */
+
+ /* Various other config info which may change with .htaccess files
+ * These are config vectors, with one void* pointer for each module
+ * (the thing pointed to being the module's business).
+ */
+
+ void *per_dir_config; /* Options set in config files, etc. */
+ void *request_config; /* Notes on *this* request */
+
+/*
+ * a linked list of the configuration directives in the .htaccess files
+ * accessed by this request.
+ * N.B. always add to the head of the list, _never_ to the end.
+ * that way, a sub request's list can (temporarily) point to a parent's list
+ */
+ const struct htaccess_result *htaccess;
+
+/* Things placed at the end of the record to avoid breaking binary
+ * compatibility. It would be nice to remember to reorder the entire
+ * record to improve 64bit alignment the next time we need to break
+ * binary compatibility for some other reason.
+ */
+};
+
+
+/* Things which are per connection
+ */
+
+struct conn_rec {
+
+ ap_pool *pool;
+ server_rec *server;
+ server_rec *base_server; /* Physical vhost this conn come in on */
+ void *vhost_lookup_data; /* used by http_vhost.c */
+
+ /* Information about the connection itself */
+
+ int child_num; /* The number of the child handling conn_rec */
+ BUFF *client; /* Connection to the guy */
+
+ /* Who is the client? */
+
+ struct sockaddr_in local_addr; /* local address */
+ struct sockaddr_in remote_addr; /* remote address */
+ char *remote_ip; /* Client's IP address */
+ char *remote_host; /* Client's DNS name, if known.
+ * NULL if DNS hasn't been checked,
+ * "" if it has and no address was found.
+ * N.B. Only access this though
+ * get_remote_host() */
+ char *remote_logname; /* Only ever set if doing rfc1413 lookups.
+ * N.B. Only access this through
+ * get_remote_logname() */
+ char *user; /* If an authentication check was made,
+ * this gets set to the user name. We assume
+ * that there's only one user per connection(!)
+ */
+ char *ap_auth_type; /* Ditto. */
+
+ unsigned aborted:1; /* Are we still talking? */
+ signed int keepalive:2; /* Are we using HTTP Keep-Alive?
+ * -1 fatal error, 0 undecided, 1 yes */
+ unsigned keptalive:1; /* Did we use HTTP Keep-Alive? */
+ signed int double_reverse:2;/* have we done double-reverse DNS?
+ * -1 yes/failure, 0 not yet, 1 yes/success */
+ int keepalives; /* How many times have we used it? */
+ char *local_ip; /* server IP address */
+ char *local_host; /* used for ap_get_server_name when
+ * UseCanonicalName is set to DNS
+ * (ignores setting of HostnameLookups) */
+};
+
+/* Per-vhost config... */
+
+/* The address 255.255.255.255, when used as a virtualhost address,
+ * will become the "default" server when the ip doesn't match other vhosts.
+ */
+#define DEFAULT_VHOST_ADDR 0xfffffffful
+
+typedef struct server_addr_rec server_addr_rec;
+struct server_addr_rec {
+ server_addr_rec *next;
+ struct in_addr host_addr; /* The bound address, for this server */
+ unsigned short host_port; /* The bound port, for this server */
+ char *virthost; /* The name given in */
+};
+
+struct server_rec {
+
+ server_rec *next;
+
+ /* description of where the definition came from */
+ const char *defn_name;
+ unsigned defn_line_number;
+
+ /* Full locations of server config info */
+
+ char *srm_confname;
+ char *access_confname;
+
+ /* Contact information */
+
+ char *server_admin;
+ char *server_hostname;
+ unsigned short port; /* for redirects, etc. */
+
+ /* Log files --- note that transfer log is now in the modules... */
+
+ char *error_fname;
+ FILE *error_log;
+ int loglevel;
+
+ /* Module-specific configuration for server, and defaults... */
+
+ int is_virtual; /* true if this is the virtual server */
+ void *module_config; /* Config vector containing pointers to
+ * modules' per-server config structures.
+ */
+ void *lookup_defaults; /* MIME type info, etc., before we start
+ * checking per-directory info.
+ */
+ /* Transaction handling */
+
+ server_addr_rec *addrs;
+ int timeout; /* Timeout, in seconds, before we give up */
+ int keep_alive_timeout; /* Seconds we'll wait for another request */
+ int keep_alive_max; /* Maximum requests per connection */
+ int keep_alive; /* Use persistent connections? */
+ int send_buffer_size; /* size of TCP send buffer (in bytes) */
+
+ char *path; /* Pathname for ServerPath */
+ int pathlen; /* Length of path */
+
+ array_header *names; /* Normal names for ServerAlias servers */
+ array_header *wild_names; /* Wildcarded names for ServerAlias servers */
+
+ uid_t server_uid; /* effective user id when calling exec wrapper */
+ gid_t server_gid; /* effective group id when calling exec wrapper */
+
+ int limit_req_line; /* limit on size of the HTTP request line */
+ int limit_req_fieldsize; /* limit on size of any request header field */
+ int limit_req_fields; /* limit on number of request header fields */
+};
+
+/* These are more like real hosts than virtual hosts */
+struct listen_rec {
+ listen_rec *next;
+ struct sockaddr_in local_addr; /* local IP address and port */
+ int fd;
+ int used; /* Only used during restart */
+/* more stuff here, like which protocol is bound to the port */
+};
+
+/* Prototypes for utilities... util.c.
+ */
+
+extern void ap_util_init(void);
+
+/* Time */
+extern API_VAR_EXPORT const char ap_month_snames[12][4];
+extern API_VAR_EXPORT const char ap_day_snames[7][4];
+
+API_EXPORT(struct tm *) ap_get_gmtoff(int *tz);
+API_EXPORT(char *) ap_get_time(void);
+API_EXPORT(char *) ap_field_noparam(pool *p, const char *intype);
+API_EXPORT(char *) ap_ht_time(pool *p, time_t t, const char *fmt, int gmt);
+API_EXPORT(char *) ap_gm_timestr_822(pool *p, time_t t);
+
+/* String handling. The *_nc variants allow you to use non-const char **s as
+ arguments (unfortunately C won't automatically convert a char ** to a const
+ char **) */
+
+API_EXPORT(char *) ap_getword(pool *p, const char **line, char stop);
+API_EXPORT(char *) ap_getword_nc(pool *p, char **line, char stop);
+API_EXPORT(char *) ap_getword_white(pool *p, const char **line);
+API_EXPORT(char *) ap_getword_white_nc(pool *p, char **line);
+API_EXPORT(char *) ap_getword_nulls(pool *p, const char **line, char stop);
+API_EXPORT(char *) ap_getword_nulls_nc(pool *p, char **line, char stop);
+API_EXPORT(char *) ap_getword_conf(pool *p, const char **line);
+API_EXPORT(char *) ap_getword_conf_nc(pool *p, char **line);
+
+API_EXPORT(const char *) ap_size_list_item(const char **field, int *len);
+API_EXPORT(char *) ap_get_list_item(pool *p, const char **field);
+API_EXPORT(int) ap_find_list_item(pool *p, const char *line, const char *tok);
+
+API_EXPORT(char *) ap_get_token(pool *p, const char **accept_line, int accept_white);
+API_EXPORT(int) ap_find_token(pool *p, const char *line, const char *tok);
+API_EXPORT(int) ap_find_last_token(pool *p, const char *line, const char *tok);
+
+API_EXPORT(int) ap_is_url(const char *u);
+API_EXPORT(int) ap_unescape_url(char *url);
+API_EXPORT(void) ap_no2slash(char *name);
+API_EXPORT(void) ap_getparents(char *name);
+API_EXPORT(char *) ap_escape_path_segment(pool *p, const char *s);
+API_EXPORT(char *) ap_os_escape_path(pool *p, const char *path, int partial);
+#define ap_escape_uri(ppool,path) ap_os_escape_path(ppool,path,1)
+API_EXPORT(char *) ap_escape_html(pool *p, const char *s);
+API_EXPORT(char *) ap_construct_server(pool *p, const char *hostname,
+ unsigned port, const request_rec *r);
+API_EXPORT(char *) ap_escape_shell_cmd(pool *p, const char *s);
+
+API_EXPORT(int) ap_count_dirs(const char *path);
+API_EXPORT(char *) ap_make_dirstr_prefix(char *d, const char *s, int n);
+API_EXPORT(char *) ap_make_dirstr_parent(pool *p, const char *s);
+/* deprecated. The previous two routines are preferred. */
+API_EXPORT(char *) ap_make_dirstr(pool *a, const char *s, int n);
+API_EXPORT(char *) ap_make_full_path(pool *a, const char *dir, const char *f);
+
+API_EXPORT(int) ap_is_matchexp(const char *str);
+API_EXPORT(int) ap_strcmp_match(const char *str, const char *exp);
+API_EXPORT(int) ap_strcasecmp_match(const char *str, const char *exp);
+API_EXPORT(char *) ap_pbase64decode(pool *p, const char *bufcoded);
+API_EXPORT(char *) ap_pbase64encode(pool *p, char *string);
+API_EXPORT(char *) ap_uudecode(pool *p, const char *bufcoded);
+API_EXPORT(char *) ap_uuencode(pool *p, char *string);
+
+#ifdef OS2
+void os2pathname(char *path);
+char *ap_double_quotes(pool *p, char *str);
+#endif
+
+API_EXPORT(int) ap_regexec(const regex_t *preg, const char *string,
+ size_t nmatch, regmatch_t pmatch[], int eflags);
+API_EXPORT(size_t) ap_regerror(int errcode, const regex_t *preg,
+ char *errbuf, size_t errbuf_size);
+API_EXPORT(char *) ap_pregsub(pool *p, const char *input, const char *source,
+ size_t nmatch, regmatch_t pmatch[]);
+
+API_EXPORT(void) ap_content_type_tolower(char *);
+API_EXPORT(void) ap_str_tolower(char *);
+API_EXPORT(int) ap_ind(const char *, char); /* Sigh... */
+API_EXPORT(int) ap_rind(const char *, char);
+
+API_EXPORT(char *) ap_escape_quotes (pool *p, const char *instring);
+
+/* Common structure for reading of config files / passwd files etc. */
+typedef struct {
+ int (*getch) (void *param); /* a getc()-like function */
+ void *(*getstr) (void *buf, size_t bufsiz, void *param); /* a fgets()-like function */
+ int (*close) (void *param); /* a close hander function */
+ void *param; /* the argument passed to getch/getstr/close */
+ const char *name; /* the filename / description */
+ unsigned line_number; /* current line number, starting at 1 */
+} configfile_t;
+
+/* Open a configfile_t as FILE, return open configfile_t struct pointer */
+API_EXPORT(configfile_t *) ap_pcfg_openfile(pool *p, const char *name);
+
+/* Allocate a configfile_t handle with user defined functions and params */
+API_EXPORT(configfile_t *) ap_pcfg_open_custom(pool *p, const char *descr,
+ void *param,
+ int(*getc_func)(void*),
+ void *(*gets_func) (void *buf, size_t bufsiz, void *param),
+ int(*close_func)(void *param));
+
+/* Read one line from open configfile_t, strip LF, increase line number */
+API_EXPORT(int) ap_cfg_getline(char *buf, size_t bufsize, configfile_t *cfp);
+
+/* Read one char from open configfile_t, increase line number upon LF */
+API_EXPORT(int) ap_cfg_getc(configfile_t *cfp);
+
+/* Detach from open configfile_t, calling the close handler */
+API_EXPORT(int) ap_cfg_closefile(configfile_t *cfp);
+
+#ifdef NEED_STRERROR
+char *strerror(int err);
+#endif
+
+/* Misc system hackery */
+
+API_EXPORT(uid_t) ap_uname2id(const char *name);
+API_EXPORT(gid_t) ap_gname2id(const char *name);
+API_EXPORT(int) ap_is_directory(const char *name);
+API_EXPORT(int) ap_can_exec(const struct stat *);
+API_EXPORT(void) ap_chdir_file(const char *file);
+
+#ifndef HAVE_CANONICAL_FILENAME
+/*
+ * We can't define these in os.h because of dependence on pool pointer.
+ */
+#define ap_os_canonical_filename(p,f) (f)
+#define ap_os_case_canonical_filename(p,f) (f)
+#define ap_os_systemcase_filename(p,f) (f)
+#else
+API_EXPORT(char *) ap_os_canonical_filename(pool *p, const char *file);
+#ifdef WIN32
+API_EXPORT(char *) ap_os_case_canonical_filename(pool *pPool, const char *szFile);
+API_EXPORT(char *) ap_os_systemcase_filename(pool *pPool, const char *szFile);
+#else
+#define ap_os_case_canonical_filename(p,f) ap_os_canonical_filename(p,f)
+#define ap_os_systemcase_filename(p,f) ap_os_canonical_filename(p,f)
+#endif
+#endif
+
+#ifdef _OSD_POSIX
+extern const char *os_set_account(pool *p, const char *account);
+extern int os_init_job_environment(server_rec *s, const char *user_name, int one_process);
+#endif /* _OSD_POSIX */
+
+char *ap_get_local_host(pool *);
+unsigned long ap_get_virthost_addr(char *hostname, unsigned short *port);
+
+extern API_VAR_EXPORT time_t ap_restart_time;
+
+/*
+ * Apache tries to keep all of its long term filehandles (such as log files,
+ * and sockets) above this number. This is to workaround problems in many
+ * third party libraries that are compiled with a small FD_SETSIZE. There
+ * should be no reason to lower this, because it's only advisory. If a file
+ * can't be allocated above this number then it will remain in the "slack"
+ * area.
+ *
+ * Only the low slack line is used by default. If HIGH_SLACK_LINE is defined
+ * then an attempt is also made to keep all non-FILE * files above the high
+ * slack line. This is to work around a Solaris C library limitation, where it
+ * uses an unsigned char to store the file descriptor.
+ */
+#ifndef LOW_SLACK_LINE
+#define LOW_SLACK_LINE 15
+#endif
+/* #define HIGH_SLACK_LINE 255 */
+
+/*
+ * The ap_slack() function takes a fd, and tries to move it above the indicated
+ * line. It returns an fd which may or may not have moved above the line, and
+ * never fails. If the high line was requested and it fails it will also try
+ * the low line.
+ */
+#ifdef NO_SLACK
+#define ap_slack(fd,line) (fd)
+#else
+int ap_slack(int fd, int line);
+#define AP_SLACK_LOW 1
+#define AP_SLACK_HIGH 2
+#endif
+
+API_EXPORT(char *) ap_escape_quotes(pool *p, const char *instr);
+
+/*
+ * Redefine assert() to something more useful for an Apache...
+ */
+API_EXPORT(void) ap_log_assert(const char *szExp, const char *szFile, int nLine)
+ __attribute__((noreturn));
+#define ap_assert(exp) ((exp) ? (void)0 : ap_log_assert(#exp,__FILE__,__LINE__))
+
+/* The optimized timeout code only works if we're not MULTITHREAD and we're
+ * also not using a scoreboard file
+ */
+#if !defined (MULTITHREAD) && \
+ (defined (USE_MMAP_SCOREBOARD) || defined (USE_SHMGET_SCOREBOARD))
+#define OPTIMIZE_TIMEOUTS
+#endif
+
+/* A set of flags which indicate places where the server should raise(SIGSTOP).
+ * This is useful for debugging, because you can then attach to that process
+ * with gdb and continue. This is important in cases where one_process
+ * debugging isn't possible.
+ */
+#define SIGSTOP_DETACH 1
+#define SIGSTOP_MAKE_CHILD 2
+#define SIGSTOP_SPAWN_CHILD 4
+#define SIGSTOP_PIPED_LOG_SPAWN 8
+#define SIGSTOP_CGI_CHILD 16
+
+#ifdef DEBUG_SIGSTOP
+extern int raise_sigstop_flags;
+#define RAISE_SIGSTOP(x) do { \
+ if (raise_sigstop_flags & SIGSTOP_##x) raise(SIGSTOP);\
+ } while (0)
+#else
+#define RAISE_SIGSTOP(x)
+#endif
+
+API_EXPORT(extern const char *) ap_psignature(const char *prefix, request_rec *r);
+
+/* strtoul does not exist on sunos4. */
+#ifdef strtoul
+#undef strtoul
+#endif
+#define strtoul strtoul_is_not_a_portable_function_use_strtol_instead
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !APACHE_HTTPD_H */
diff --git a/include/pcreposix.h b/include/pcreposix.h
new file mode 100644
index 00000000000..47838a8bc56
--- /dev/null
+++ b/include/pcreposix.h
@@ -0,0 +1,89 @@
+/*************************************************
+* Perl-Compatible Regular Expressions *
+*************************************************/
+
+/* Copyright (c) 1997-2000 University of Cambridge */
+/* Do not edit this file, this is provided by PCRE */
+
+#ifndef _PCREPOSIX_H
+#define _PCREPOSIX_H
+
+/* This is the header for the POSIX wrapper interface to the PCRE Perl-
+Compatible Regular Expression library. It defines the things POSIX says should
+be there. I hope. */
+
+/* Have to include stdlib.h in order to ensure that size_t is defined. */
+
+#include
+
+/* Allow for C++ users */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Options defined by POSIX. */
+
+#define REG_ICASE 0x01
+#define REG_NEWLINE 0x02
+#define REG_NOTBOL 0x04
+#define REG_NOTEOL 0x08
+
+/* These are not used by PCRE, but by defining them we make it easier
+to slot PCRE into existing programs that make POSIX calls. */
+
+#define REG_EXTENDED 0
+#define REG_NOSUB 0
+
+/* Error values. Not all these are relevant or used by the wrapper. */
+
+enum {
+ REG_ASSERT = 1, /* internal error ? */
+ REG_BADBR, /* invalid repeat counts in {} */
+ REG_BADPAT, /* pattern error */
+ REG_BADRPT, /* ? * + invalid */
+ REG_EBRACE, /* unbalanced {} */
+ REG_EBRACK, /* unbalanced [] */
+ REG_ECOLLATE, /* collation error - not relevant */
+ REG_ECTYPE, /* bad class */
+ REG_EESCAPE, /* bad escape sequence */
+ REG_EMPTY, /* empty expression */
+ REG_EPAREN, /* unbalanced () */
+ REG_ERANGE, /* bad range inside [] */
+ REG_ESIZE, /* expression too big */
+ REG_ESPACE, /* failed to get memory */
+ REG_ESUBREG, /* bad back reference */
+ REG_INVARG, /* bad argument */
+ REG_NOMATCH /* match failed */
+};
+
+
+/* The structure representing a compiled regular expression. */
+
+typedef struct {
+ void *re_pcre;
+ size_t re_nsub;
+ size_t re_erroffset;
+} regex_t;
+
+/* The structure in which a captured offset is returned. */
+
+typedef int regoff_t;
+
+typedef struct {
+ regoff_t rm_so;
+ regoff_t rm_eo;
+} regmatch_t;
+
+/* The functions */
+
+extern int regcomp(regex_t *, const char *, int);
+extern int regexec(regex_t *, const char *, size_t, regmatch_t *, int);
+extern size_t regerror(int, const regex_t *, char *, size_t);
+extern void regfree(regex_t *);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* End of pcreposix.h */
diff --git a/include/util_cfgtree.h b/include/util_cfgtree.h
new file mode 100644
index 00000000000..6a4a2f6f27e
--- /dev/null
+++ b/include/util_cfgtree.h
@@ -0,0 +1,70 @@
+/* ====================================================================
+ * The Apache Software License, Version 1.1
+ *
+ * Copyright (c) 2000 The Apache Software Foundation. All rights
+ * reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. The end-user documentation included with the redistribution,
+ * if any, must include the following acknowledgment:
+ * "This product includes software developed by the
+ * Apache Software Foundation (http://www.apache.org/)."
+ * Alternately, this acknowledgment may appear in the software itself,
+ * if and wherever such third-party acknowledgments normally appear.
+ *
+ * 4. The names "Apache" and "Apache Software Foundation" must
+ * not be used to endorse or promote products derived from this
+ * software without prior written permission. For written
+ * permission, please contact apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache",
+ * nor may "Apache" appear in their name, without prior written
+ * permission of the Apache Software Foundation.
+ *
+ * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
+ * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ */
+
+#ifndef AP_CONFTREE_H
+#define AP_CONFTREE_H
+
+typedef struct ap_directive_t {
+ const char *directive;
+ const char *args;
+ int line_num;
+ struct ap_directive_t *next;
+ struct ap_directive_t *first_child;
+ struct ap_directive_t *parent;
+} ap_directive_t;
+
+ap_directive_t *ap_add_node(ap_directive_t **parent, ap_directive_t *current,
+ ap_directive_t *todadd, int child);
+
+#endif
diff --git a/include/util_md5.h b/include/util_md5.h
new file mode 100644
index 00000000000..0a0dc9c9b3c
--- /dev/null
+++ b/include/util_md5.h
@@ -0,0 +1,80 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+#ifndef APACHE_UTIL_MD5_H
+#define APACHE_UTIL_MD5_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "ap_md5.h"
+
+API_EXPORT(char *) ap_md5(pool *a, const unsigned char *string);
+API_EXPORT(char *) ap_md5_binary(pool *a, const unsigned char *buf, int len);
+API_EXPORT(char *) ap_md5contextTo64(pool *p, AP_MD5_CTX * context);
+#ifdef CHARSET_EBCDIC
+API_EXPORT(char *) ap_md5digest(pool *p, FILE *infile, int convert);
+#else
+API_EXPORT(char *) ap_md5digest(pool *p, FILE *infile);
+#endif /* CHARSET_EBCDIC */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !APACHE_UTIL_MD5_H */
diff --git a/include/util_script.h b/include/util_script.h
new file mode 100644
index 00000000000..416d72942dc
--- /dev/null
+++ b/include/util_script.h
@@ -0,0 +1,91 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+#ifndef APACHE_UTIL_SCRIPT_H
+#define APACHE_UTIL_SCRIPT_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef APACHE_ARG_MAX
+#ifdef _POSIX_ARG_MAX
+#define APACHE_ARG_MAX _POSIX_ARG_MAX
+#else
+#define APACHE_ARG_MAX 512
+#endif
+#endif
+
+API_EXPORT(char **) ap_create_environment(pool *p, table *t);
+API_EXPORT(int) ap_find_path_info(const char *uri, const char *path_info);
+API_EXPORT(void) ap_add_cgi_vars(request_rec *r);
+API_EXPORT(void) ap_add_common_vars(request_rec *r);
+API_EXPORT(int) ap_scan_script_header_err(request_rec *r, FILE *f, char *buffer);
+API_EXPORT(int) ap_scan_script_header_err_buff(request_rec *r, BUFF *f,
+ char *buffer);
+API_EXPORT(int) ap_scan_script_header_err_core(request_rec *r, char *buffer,
+ int (*getsfunc) (char *, int, void *),
+ void *getsfunc_data);
+API_EXPORT(void) ap_send_size(size_t size, request_rec *r);
+API_EXPORT(int) ap_call_exec(request_rec *r, child_info *pinfo, char *argv0, char **env,
+ int shellcmd);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !APACHE_UTIL_SCRIPT_H */
diff --git a/modules/.cvsignore b/modules/.cvsignore
new file mode 100644
index 00000000000..f3c7a7c5da6
--- /dev/null
+++ b/modules/.cvsignore
@@ -0,0 +1 @@
+Makefile
diff --git a/modules/Makefile.in b/modules/Makefile.in
new file mode 100644
index 00000000000..da8a82274b5
--- /dev/null
+++ b/modules/Makefile.in
@@ -0,0 +1,10 @@
+
+DEPTH = ..
+topsrcdir = @topsrcdir@
+srcdir = @srcdir@
+VPATH = @srcdir@
+
+SUBDIRS = mpm $(MODULE_DIRS)
+
+include $(topsrcdir)/build/rules.mk
+
diff --git a/modules/README b/modules/README
new file mode 100644
index 00000000000..df25f051f25
--- /dev/null
+++ b/modules/README
@@ -0,0 +1,34 @@
+The directory structure for this level is as follows:
+
+standard/
+
+ In this directory are the standard supported modules for
+ Apache. Not all are compiled by default.
+
+proxy/
+
+ This houses the code for the proxy module for Apache.
+
+experimental/
+
+ In this directory we've placed some modules which we think
+ provide some pretty interesting functionality, but which
+ are still in the early stages of development and could
+ evolve radically in the future. This code isn't supported
+ officially.
+
+extra/
+
+ This is the directory for third-party modules, such as mod_jserv.
+
+test/
+
+ This directory houses modules which test various components
+ of Apache. You should not compile these into a production
+ server.
+
+example/
+
+ This directory houses example modules, to help module authors
+ figure their way around the Apache API and module concept.
+
diff --git a/modules/aaa/.cvsignore b/modules/aaa/.cvsignore
new file mode 100644
index 00000000000..c3690626fe3
--- /dev/null
+++ b/modules/aaa/.cvsignore
@@ -0,0 +1,6 @@
+Makefile
+*.lo
+*.so
+*.dll
+*.def
+*.exp
diff --git a/modules/aaa/.indent.pro b/modules/aaa/.indent.pro
new file mode 100644
index 00000000000..a9fbe9f9a1f
--- /dev/null
+++ b/modules/aaa/.indent.pro
@@ -0,0 +1,54 @@
+-i4 -npsl -di0 -br -nce -d0 -cli0 -npcs -nfc1
+-TBUFF
+-TFILE
+-TTRANS
+-TUINT4
+-T_trans
+-Tallow_options_t
+-Tapache_sfio
+-Tarray_header
+-Tbool_int
+-Tbuf_area
+-Tbuff_struct
+-Tbuffy
+-Tcmd_how
+-Tcmd_parms
+-Tcommand_rec
+-Tcommand_struct
+-Tconn_rec
+-Tcore_dir_config
+-Tcore_server_config
+-Tdir_maker_func
+-Tevent
+-Tglobals_s
+-Thandler_func
+-Thandler_rec
+-Tjoblist_s
+-Tlisten_rec
+-Tmerger_func
+-Tmode_t
+-Tmodule
+-Tmodule_struct
+-Tmutex
+-Tn_long
+-Tother_child_rec
+-Toverrides_t
+-Tparent_score
+-Tpid_t
+-Tpiped_log
+-Tpool
+-Trequest_rec
+-Trequire_line
+-Trlim_t
+-Tscoreboard
+-Tsemaphore
+-Tserver_addr_rec
+-Tserver_rec
+-Tserver_rec_chain
+-Tshort_score
+-Ttable
+-Ttable_entry
+-Tthread
+-Tu_wide_int
+-Tvtime_t
+-Twide_int
diff --git a/modules/aaa/Makefile.in b/modules/aaa/Makefile.in
new file mode 100644
index 00000000000..ccd3c197552
--- /dev/null
+++ b/modules/aaa/Makefile.in
@@ -0,0 +1,8 @@
+
+DEPTH = ../..
+topsrcdir = @topsrcdir@
+srcdir = @srcdir@
+VPATH = @srcdir@
+
+include $(topsrcdir)/build/special.mk
+
diff --git a/modules/aaa/config.m4 b/modules/aaa/config.m4
new file mode 100644
index 00000000000..9d069b51c76
--- /dev/null
+++ b/modules/aaa/config.m4
@@ -0,0 +1 @@
+APACHE_MODULE(standard)
diff --git a/modules/aaa/mod_auth_digest.c b/modules/aaa/mod_auth_digest.c
new file mode 100644
index 00000000000..43795221f86
--- /dev/null
+++ b/modules/aaa/mod_auth_digest.c
@@ -0,0 +1,1919 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+/*
+ * mod_auth_digest: MD5 digest authentication
+ *
+ * Originally by Alexei Kosut
+ * Updated to RFC-2617 by Ronald Tschalär
+ * based on mod_auth, by Rob McCool and Robert S. Thau
+ *
+ * This module an updated version of modules/standard/mod_digest.c
+ * However, it has not been extensively tested yet, and is therefore
+ * currently marked experimental. Send problem reports to me
+ * (ronald@innovation.ch)
+ *
+ * Requires either /dev/random (or equivalent) or the truerand library,
+ * available for instance from
+ * ftp://research.att.com/dist/mab/librand.shar
+ *
+ * Open Issues:
+ * - qop=auth-int (when streams and trailer support available)
+ * - nonce-format configurability
+ * - Proxy-Authorization-Info header is set by this module, but is
+ * currently ignored by mod_proxy (needs patch to mod_proxy)
+ * - generating the secret takes a while (~ 8 seconds) if using the
+ * truerand library
+ * - shared-mem not completely tested yet. Seems to work ok for me,
+ * but... (definitely won't work on Windoze)
+ */
+
+/* The section for the Configure script:
+ * MODULE-DEFINITION-START
+ * Name: digest_auth_module
+ * ConfigStart
+
+ RULE_DEV_RANDOM=`./helpers/CutRule DEV_RANDOM $file`
+ if [ "$RULE_DEV_RANDOM" = "default" ]; then
+ if [ -r "/dev/random" ]; then
+ RULE_DEV_RANDOM="/dev/random"
+ elif [ -r "/dev/urandom" ]; then
+ RULE_DEV_RANDOM="/dev/urandom"
+ else
+ RULE_DEV_RANDOM="truerand"
+ if helpers/TestCompile func randbyte; then
+ :
+ elif helpers/TestCompile lib rand randbyte; then
+ :
+ else
+ echo " (mod_auth_digest) truerand library missing!"
+ echo "** This will most probably defeat successful compilation."
+ echo "** See Rule DEV_RANDOM in src/Configuration.tmpl for more information."
+ fi
+ fi
+ fi
+ if [ "$RULE_DEV_RANDOM" = "truerand" ]; then
+ echo " using truerand library (-lrand) for the random seed"
+ LIBS="$LIBS -L/usr/local/lib -lrand"
+ else
+ echo " using $RULE_DEV_RANDOM for the random seed"
+ CFLAGS="$CFLAGS -DDEV_RANDOM=$RULE_DEV_RANDOM"
+ fi
+
+ * ConfigEnd
+ * MODULE-DEFINITION-END
+ */
+
+#include "httpd.h"
+#include "http_config.h"
+#include "http_conf_globals.h"
+#include "http_core.h"
+#include "http_request.h"
+#include "http_log.h"
+#include "http_protocol.h"
+#include "ap_config.h"
+#include "ap_ctype.h"
+#include "util_uri.h"
+#include "util_md5.h"
+#include "ap_sha1.h"
+#ifdef HAVE_SHMEM_MM
+#include "mm.h"
+#endif /* HAVE_SHMEM_MM */
+
+
+/* struct to hold the configuration info */
+
+typedef struct digest_config_struct {
+ const char *dir_name;
+ const char *pwfile;
+ const char *grpfile;
+ const char *realm;
+ const char **qop_list;
+ AP_SHA1_CTX nonce_ctx;
+ long nonce_lifetime;
+ const char *nonce_format;
+ int check_nc;
+ const char *algorithm;
+ char *uri_list;
+ const char *ha1;
+} digest_config_rec;
+
+
+#define DFLT_ALGORITHM "MD5"
+
+#define DFLT_NONCE_LIFE 300L
+#define NEXTNONCE_DELTA 30
+
+
+#define NONCE_TIME_LEN (((sizeof(time_t)+2)/3)*4)
+#define NONCE_HASH_LEN 40
+#define NONCE_LEN (NONCE_TIME_LEN + NONCE_HASH_LEN)
+
+#define SECRET_LEN 20
+
+
+/* client list definitions */
+
+typedef struct hash_entry {
+ unsigned long key; /* the key for this entry */
+ struct hash_entry *next; /* next entry in the bucket */
+ unsigned long nonce_count; /* for nonce-count checking */
+ char ha1[17]; /* for algorithm=MD5-sess */
+ char last_nonce[NONCE_LEN+1]; /* for one-time nonce's */
+} client_entry;
+
+static struct hash_table {
+ client_entry **table;
+ unsigned long tbl_len;
+ unsigned long num_entries;
+ unsigned long num_created;
+ unsigned long num_removed;
+ unsigned long num_renewed;
+} *client_list;
+
+
+/* struct to hold a parsed Authorization header */
+
+enum hdr_sts { NO_HEADER, NOT_DIGEST, INVALID, VALID };
+
+typedef struct digest_header_struct {
+ const char *scheme;
+ const char *realm;
+ const char *username;
+ char *nonce;
+ const char *uri;
+ const char *digest;
+ const char *algorithm;
+ const char *cnonce;
+ const char *opaque;
+ unsigned long opaque_num;
+ const char *message_qop;
+ const char *nonce_count;
+ /* the following fields are not (directly) from the header */
+ time_t nonce_time;
+ enum hdr_sts auth_hdr_sts;
+ uri_components *request_uri;
+ int needed_auth;
+ client_entry *client;
+} digest_header_rec;
+
+
+/* (mostly) nonce stuff */
+
+typedef union time_union {
+ time_t time;
+ unsigned char arr[sizeof(time_t)];
+} time_rec;
+
+
+static unsigned char secret[SECRET_LEN];
+static int call_cnt = 0;
+
+
+#ifdef HAVE_SHMEM_MM
+/* opaque stuff */
+
+static MM *opaque_mm;
+static unsigned long *opaque_cntr;
+
+static MM *client_mm;
+
+static MM *otn_count_mm;
+static time_t *otn_counter; /* one-time-nonce counter */
+
+#define SHMEM_SIZE 1000 /* ~ 12 entries */
+#define NUM_BUCKETS 15UL
+
+#else /* HAVE_SHMEM_MM */
+static void *client_mm = NULL;
+#endif /* HAVE_SHMEM_MM */
+
+module MODULE_VAR_EXPORT digest_auth_module;
+
+/*
+ * initialization code
+ */
+
+#ifdef HAVE_SHMEM_MM
+static void cleanup_tables(void *not_used)
+{
+ fprintf(stderr, "Digest: cleaning up shared memory\n");
+ fflush(stderr);
+
+ if (client_mm) {
+ mm_destroy(client_mm);
+ client_mm = NULL;
+ }
+
+ if (opaque_mm) {
+ mm_destroy(opaque_mm);
+ opaque_mm = NULL;
+ }
+
+ if (otn_count_mm) {
+ mm_destroy(otn_count_mm);
+ otn_count_mm = NULL;
+ }
+}
+#endif /* HAVE_SHMEM_MM */
+
+static void initialize_secret(server_rec *s)
+{
+#ifdef DEV_RANDOM
+ FILE *rnd;
+ size_t got, tot;
+#else
+ extern int randbyte(void); /* from the truerand library */
+ unsigned int idx;
+#endif
+
+ ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, s,
+ "Digest: generating secret for digest authentication ...");
+
+#ifdef DEV_RANDOM
+#define XSTR(x) #x
+#define STR(x) XSTR(x)
+ if ((rnd = fopen(STR(DEV_RANDOM), "rb")) == NULL) {
+ ap_log_error(APLOG_MARK, APLOG_CRIT, s,
+ "Digest: Couldn't open " STR(DEV_RANDOM));
+ exit(EXIT_FAILURE);
+ }
+ if (setvbuf(rnd, NULL, _IONBF, 0) != 0) {
+ ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_CRIT, s,
+ "Digest: Error trying to disable buffering for " STR(DEV_RANDOM));
+ exit(EXIT_FAILURE);
+ }
+ for (tot=0; tottable = (client_entry**) (client_list + 1);
+ for (idx=0; idxtable[idx] = NULL;
+ client_list->tbl_len = NUM_BUCKETS;
+ client_list->num_entries = 0;
+
+
+ /* setup opaque */
+
+ opaque_mm = mm_create(sizeof(*opaque_cntr), tmpnam(NULL));
+ if (opaque_mm == NULL)
+ goto failed;
+#ifdef MPE
+ if (geteuid() == 1) {
+#else
+ if (geteuid() == 0) {
+#endif
+ if (mm_permission(opaque_mm, 0600, ap_user_id, ap_group_id))
+ goto failed;
+ }
+ opaque_cntr = mm_malloc(opaque_mm, sizeof(*opaque_cntr));
+ if (opaque_cntr == NULL)
+ goto failed;
+ *opaque_cntr = 1UL;
+
+
+ /* setup one-time-nonce counter */
+
+ otn_count_mm = mm_create(sizeof(*otn_counter), tmpnam(NULL));
+ if (otn_count_mm == NULL)
+ goto failed;
+#ifdef MPE
+ if (geteuid() == 1) {
+#else
+ if (geteuid() == 0) {
+#endif
+ if (mm_permission(otn_count_mm, 0600, ap_user_id, ap_group_id))
+ goto failed;
+ }
+ otn_counter = mm_malloc(otn_count_mm, sizeof(*otn_counter));
+ if (otn_counter == NULL)
+ goto failed;
+ *otn_counter = 0;
+
+
+ /* success */
+ return;
+
+failed:
+ if (!client_mm || (client_list && client_list->table && !opaque_mm)
+ || (opaque_cntr && !otn_count_mm))
+ ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, s,
+ "Digest: failed to create shared memory segments; reason "
+ "was `%s' - all nonce-count checking, one-time nonces, "
+ "and MD5-sess algorithm disabled", mm_error());
+ else
+ ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, s,
+ "Digest: failed to allocate shared mem; reason was `%s' "
+ "- all nonce-count checking, one-time nonces, and "
+ "MD5-sess algorithm disabled", mm_error());
+
+ cleanup_tables(NULL);
+}
+#endif /* HAVE_SHMEM_MM */
+
+static void initialize_module(server_rec *s, pool *p)
+{
+ /* keep from doing the init more than once at startup, and delay
+ * the init until the second round
+ */
+ if (++call_cnt < 2)
+ return;
+
+ /* only initialize the secret on startup, not on restarts */
+ if (call_cnt == 2)
+ initialize_secret(s);
+
+#ifdef HAVE_SHMEM_MM
+ /* Note: this stuff is currently fixed for the lifetime of the server,
+ * i.e. even across restarts. This means that A) any shmem-size
+ * configuration changes are ignored, and B) certain optimizations,
+ * such as only allocating the smallest necessary entry for each
+ * client, can't be done. However, the alternative is a nightmare:
+ * we can't call mm_destroy on a graceful restart because there will
+ * be children using the tables, and we also don't know when the
+ * last child dies. Therefore we can never clean up the old stuff,
+ * creating a creeping memory leak.
+ */
+ initialize_tables(s);
+ /* atexit(cleanup_tables); */
+ ap_register_cleanup(p, NULL, cleanup_tables, ap_null_cleanup);
+#endif /* HAVE_SHMEM_MM */
+}
+
+
+/*
+ * configuration code
+ */
+
+static void *create_digest_dir_config(pool *p, char *dir)
+{
+ digest_config_rec *conf;
+
+ if (dir == NULL) return NULL;
+
+ conf = (digest_config_rec *) ap_pcalloc(p, sizeof(digest_config_rec));
+ if (conf) {
+ conf->qop_list = ap_palloc(p, sizeof(char*));
+ conf->qop_list[0] = NULL;
+ conf->nonce_lifetime = DFLT_NONCE_LIFE;
+ conf->dir_name = ap_pstrdup(p, dir);
+ conf->algorithm = DFLT_ALGORITHM;
+ }
+
+ return conf;
+}
+
+static const char *set_realm(cmd_parms *cmd, void *config, const char *realm)
+{
+ digest_config_rec *conf = (digest_config_rec *) config;
+
+ /* The core already handles the realm, but it's just too convenient to
+ * grab it ourselves too and cache some setups. However, we need to
+ * let the core get at it too, which is why we decline at the end -
+ * this relies on the fact that http_core is last in the list.
+ */
+ conf->realm = realm;
+
+ /* we precompute the part of the nonce hash that is constant (well,
+ * the host:port would be too, but that varies for .htaccess files
+ * and directives outside a virtual host section)
+ */
+ ap_SHA1Init(&conf->nonce_ctx);
+ ap_SHA1Update_binary(&conf->nonce_ctx, (const unsigned char *) realm,
+ strlen(realm));
+ ap_SHA1Update_binary(&conf->nonce_ctx, secret, sizeof(secret));
+
+ return DECLINE_CMD;
+}
+
+static const char *set_digest_file(cmd_parms *cmd, void *config,
+ const char *file)
+{
+ ((digest_config_rec *) config)->pwfile = file;
+ return NULL;
+}
+
+static const char *set_group_file(cmd_parms *cmd, void *config,
+ const char *file)
+{
+ ((digest_config_rec *) config)->grpfile = file;
+ return NULL;
+}
+
+static const char *set_qop(cmd_parms *cmd, void *config, const char *op)
+{
+ digest_config_rec *conf = (digest_config_rec *) config;
+ const char **tmp;
+ int cnt;
+
+ if (!strcasecmp(op, "none")) {
+ if (conf->qop_list[0] == NULL) {
+ conf->qop_list = ap_palloc(cmd->pool, 2 * sizeof(char*));
+ conf->qop_list[1] = NULL;
+ }
+ conf->qop_list[0] = "none";
+ return NULL;
+ }
+
+ if (!strcasecmp(op, "auth-int"))
+ ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, cmd->server,
+ "Digest: WARNING: qop `auth-int' currently only works "
+ "correctly for responses with no entity");
+ else if (strcasecmp(op, "auth"))
+ return ap_pstrcat(cmd->pool, "Unrecognized qop: ", op, NULL);
+
+ for (cnt=0; conf->qop_list[cnt] != NULL; cnt++)
+ ;
+ tmp = ap_palloc(cmd->pool, (cnt+2)*sizeof(char*));
+ memcpy(tmp, conf->qop_list, cnt*sizeof(char*));
+ tmp[cnt] = ap_pstrdup(cmd->pool, op);
+ tmp[cnt+1] = NULL;
+ conf->qop_list = tmp;
+
+ return NULL;
+}
+
+static const char *set_nonce_lifetime(cmd_parms *cmd, void *config,
+ const char *t)
+{
+ char *endptr;
+ long lifetime;
+
+ lifetime = strtol(t, &endptr, 10);
+ if (endptr < (t+strlen(t)) && !ap_isspace(*endptr))
+ return ap_pstrcat(cmd->pool, "Invalid time in AuthDigestNonceLifetime: ", t, NULL);
+
+ ((digest_config_rec *) config)->nonce_lifetime = lifetime;
+ return NULL;
+}
+
+static const char *set_nonce_format(cmd_parms *cmd, void *config,
+ const char *fmt)
+{
+ ((digest_config_rec *) config)->nonce_format = fmt;
+ return "AuthDigestNonceFormat is not implemented (yet)";
+}
+
+static const char *set_nc_check(cmd_parms *cmd, void *config, int flag)
+{
+ ((digest_config_rec *) config)->check_nc = flag;
+ return NULL;
+}
+
+static const char *set_algorithm(cmd_parms *cmd, void *config, const char *alg)
+{
+ if (!strcasecmp(alg, "MD5-sess"))
+#ifdef HAVE_SHMEM_MM
+ ;
+#else /* HAVE_SHMEM_MM */
+ ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, cmd->server,
+ "Digest: WARNING: algorithm `MD5-sess' is currently not "
+ "correctly implemented");
+#endif /* HAVE_SHMEM_MM */
+ else if (strcasecmp(alg, "MD5"))
+ return ap_pstrcat(cmd->pool, "Invalid algorithm in AuthDigestAlgorithm: ", alg, NULL);
+
+ ((digest_config_rec *) config)->algorithm = alg;
+ return NULL;
+}
+
+static const char *set_uri_list(cmd_parms *cmd, void *config, const char *uri)
+{
+ digest_config_rec *c = (digest_config_rec *) config;
+ if (c->uri_list) {
+ c->uri_list[strlen(c->uri_list)-1] = '\0';
+ c->uri_list = ap_pstrcat(cmd->pool, c->uri_list, " ", uri, "\"", NULL);
+ }
+ else
+ c->uri_list = ap_pstrcat(cmd->pool, ", domain=\"", uri, "\"", NULL);
+ return NULL;
+}
+
+static const command_rec digest_cmds[] =
+{
+ {"AuthName", set_realm, NULL, OR_AUTHCFG, TAKE1,
+ "The authentication realm (e.g. \"Members Only\")"},
+ {"AuthDigestFile", set_digest_file, NULL, OR_AUTHCFG, TAKE1,
+ "The name of the file containing the usernames and password hashes"},
+ {"AuthDigestGroupFile", set_group_file, NULL, OR_AUTHCFG, TAKE1,
+ "The name of the file containing the group names and members"},
+ {"AuthDigestQop", set_qop, NULL, OR_AUTHCFG, ITERATE,
+ "A list of quality-of-protection options"},
+ {"AuthDigestNonceLifetime", set_nonce_lifetime, NULL, OR_AUTHCFG, TAKE1,
+ "Maximum lifetime of the server nonce (seconds)"},
+ {"AuthDigestNonceFormat", set_nonce_format, NULL, OR_AUTHCFG, TAKE1,
+ "The format to use when generating the server nonce"},
+ {"AuthDigestNcCheck", set_nc_check, NULL, OR_AUTHCFG, FLAG,
+ "Whether or not to check the nonce-count sent by the client"},
+ {"AuthDigestAlgorithm", set_algorithm, NULL, OR_AUTHCFG, TAKE1,
+ "The algorithm used for the hash calculation"},
+ {"AuthDigestDomain", set_uri_list, NULL, OR_AUTHCFG, ITERATE,
+ "A list of URI's which belong to the same protection space as the current URI"},
+ {NULL}
+};
+
+
+#ifdef HAVE_SHMEM_MM
+/*
+ * client list code
+ *
+ * Each client is assigned a number, which is transfered in the opaque
+ * field of the WWW-Authenticate and Authorization headers. The number
+ * is just a simple counter which is incremented for each new client.
+ * Clients can't forge this number because it is hashed up into the
+ * server nonce, and that is checked.
+ *
+ * The clients are kept in a simple hash table, which consists of an
+ * array of client_entry's, each with a linked list of entries hanging
+ * off it. The client's number modulo the size of the array gives the
+ * bucket number.
+ *
+ * The clients are garbage collected whenever a new client is allocated
+ * but there is not enough space left in the shared memory segment. A
+ * simple semi-LRU is used for this: whenever a client entry is accessed
+ * it is moved to the beginning of the linked list in its bucket (this
+ * also makes for faster lookups for current clients). The garbage
+ * collecter then just removes the oldest entry (i.e. the one at the
+ * end of the list) in each bucket.
+ *
+ * The main advantages of the above scheme are that it's easy to implement
+ * and it keeps the hash table evenly balanced (i.e. same number of entries
+ * in each bucket). The major disadvantage is that you may be throwing
+ * entries out which are in active use. This is not tragic, as these
+ * clients will just be sent a new client id (opaque field) and nonce
+ * with a stale=true (i.e. it will just look like the nonce expired,
+ * thereby forcing an extra round trip). If the shared memory segment
+ * has enough headroom over the current client set size then this should
+ * not occur too often.
+ *
+ * To help tune the size of the shared memory segment (and see if the
+ * above algorithm is really sufficient) a set of counters is kept
+ * indicating the number of clients held, the number of garbage collected
+ * clients, and the number of erroneously purged clients. These are printed
+ * out at each garbage collection run. Note that access to the counters is
+ * not synchronized because they are just indicaters, and whether they are
+ * off by a few doesn't matter; and for the same reason no attempt is made
+ * to guarantee the num_renewed is correct in the face of clients spoofing
+ * the opaque field.
+ */
+
+/*
+ * Get the client given its client number (the key). Returns the entry,
+ * or NULL if its not found.
+ *
+ * Access to the list itself is synchronized via locks. However, access
+ * to the entry returned by get_client() is NOT synchronized. This means
+ * that there are potentially problems if a client uses multiple,
+ * simultaneous connections to access url's within the same protection
+ * space. However, these problems are not new: when using multiple
+ * connections you have no guarantee of the order the requests are
+ * processed anyway, so you have problems with the nonce-count and
+ * one-time nonces anyway.
+ */
+static client_entry *get_client(unsigned long key, const request_rec *r)
+{
+ int bucket;
+ client_entry *entry, *prev = NULL;
+
+
+ if (!key || !client_mm) return NULL;
+
+ bucket = key % client_list->tbl_len;
+ entry = client_list->table[bucket];
+
+ mm_lock(client_mm, MM_LOCK_RD);
+
+ while(entry && key != entry->key) {
+ prev = entry;
+ entry = entry->next;
+ }
+
+ if (entry && prev) { /* move entry to front of list */
+ prev->next = entry->next;
+ entry->next = client_list->table[bucket];
+ client_list->table[bucket] = entry;
+ }
+
+ mm_unlock(client_mm);
+
+ if (entry)
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_DEBUG, r,
+ "get_client(): client %lu found", key);
+ else
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_DEBUG, r,
+ "get_client(): client %lu not found", key);
+
+ return entry;
+}
+
+
+/* A simple garbage-collecter to remove unused clients. It removes the
+ * last entry in each bucket and updates the counters. Returns the
+ * number of removed entries.
+ */
+static long gc(void)
+{
+ client_entry *entry, *prev;
+ unsigned long num_removed = 0, idx;
+
+ /* garbage collect all last entries */
+
+ for (idx=0; idxtbl_len; idx++) {
+ entry = client_list->table[idx];
+ prev = NULL;
+ while (entry->next) { /* find last entry */
+ prev = entry;
+ entry = entry->next;
+ }
+ if (prev) prev->next = NULL; /* cut list */
+ else client_list->table[idx] = NULL;
+ if (entry) { /* remove entry */
+ mm_free(client_mm, entry);
+ num_removed++;
+ }
+ }
+
+ /* update counters and log */
+
+ client_list->num_entries -= num_removed;
+ client_list->num_removed += num_removed;
+
+ return num_removed;
+}
+
+
+/*
+ * Add a new client to the list. Returns the entry if successful, NULL
+ * otherwise. This triggers the garbage collection is memory is low.
+ */
+static client_entry *add_client(unsigned long key, client_entry *new,
+ server_rec *s)
+{
+ int bucket;
+ client_entry *entry;
+
+
+ if (!key || !client_mm) return NULL;
+
+ bucket = key % client_list->tbl_len;
+ entry = client_list->table[bucket];
+
+ mm_lock(client_mm, MM_LOCK_RW);
+
+ /* try to allocate a new entry */
+
+ entry = mm_malloc(client_mm, sizeof(client_entry));
+ if (!entry) {
+ long num_removed = gc();
+ ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, s,
+ "Digest: gc'd %ld client entries. Total new clients: "
+ "%ld; Total removed clients: %ld; Total renewed clients: "
+ "%ld", num_removed,
+ client_list->num_created - client_list->num_renewed,
+ client_list->num_removed, client_list->num_renewed);
+ entry = mm_malloc(client_mm, sizeof(client_entry));
+ if (!entry) return NULL; /* give up */
+ }
+
+ /* now add the entry */
+
+ memcpy(entry, new, sizeof(client_entry));
+ entry->key = key;
+ entry->next = client_list->table[bucket];
+ client_list->table[bucket] = entry;
+ client_list->num_created++;
+ client_list->num_entries++;
+
+ mm_unlock(client_mm);
+
+ ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_DEBUG, s,
+ "allocated new client %lu", key);
+
+ return entry;
+}
+#else /* HAVE_SHMEM_MM */
+static client_entry *get_client(unsigned long key, const request_rec *r)
+{
+ return NULL;
+}
+#endif /* HAVE_SHMEM_MM */
+
+
+/*
+ * Authorization header parser code
+ */
+
+/* Parse the Authorization header, if it exists */
+static int get_digest_rec(request_rec *r, digest_header_rec *resp)
+{
+ const char *auth_line = ap_table_get(r->headers_in,
+ r->proxyreq ? "Proxy-Authorization"
+ : "Authorization");
+ size_t l;
+ int vk = 0, vv = 0;
+ char *key, *value;
+
+
+ if (!auth_line) {
+ resp->auth_hdr_sts = NO_HEADER;
+ return !OK;
+ }
+
+ resp->scheme = ap_getword_white(r->pool, &auth_line);
+ if (strcasecmp(resp->scheme, "Digest")) {
+ resp->auth_hdr_sts = NOT_DIGEST;
+ return !OK;
+ }
+
+ l = strlen(auth_line);
+
+ key = ap_palloc(r->pool, l+1);
+ value = ap_palloc(r->pool, l+1);
+
+ while (auth_line[0] != '\0') {
+
+ /* find key */
+
+ while (ap_isspace(auth_line[0])) auth_line++;
+ vk = 0;
+ while (auth_line[0] != '=' && auth_line[0] != ','
+ && auth_line[0] != '\0' && !ap_isspace(auth_line[0]))
+ key[vk++] = *auth_line++;
+ key[vk] = '\0';
+ while (ap_isspace(auth_line[0])) auth_line++;
+
+ /* find value */
+
+ if (auth_line[0] == '=') {
+ auth_line++;
+ while (ap_isspace(auth_line[0])) auth_line++;
+
+ vv = 0;
+ if (auth_line[0] == '\"') { /* quoted string */
+ auth_line++;
+ while (auth_line[0] != '\"' && auth_line[0] != '\0') {
+ if (auth_line[0] == '\\' && auth_line[1] != '\0')
+ auth_line++; /* escaped char */
+ value[vv++] = *auth_line++;
+ }
+ if (auth_line[0] != '\0') auth_line++;
+ }
+ else { /* token */
+ while (auth_line[0] != ',' && auth_line[0] != '\0'
+ && !ap_isspace(auth_line[0]))
+ value[vv++] = *auth_line++;
+ }
+ value[vv] = '\0';
+ }
+
+ while (auth_line[0] != ',' && auth_line[0] != '\0') auth_line++;
+ if (auth_line[0] != '\0') auth_line++;
+
+ if (!strcasecmp(key, "username"))
+ resp->username = ap_pstrdup(r->pool, value);
+ else if (!strcasecmp(key, "realm"))
+ resp->realm = ap_pstrdup(r->pool, value);
+ else if (!strcasecmp(key, "nonce"))
+ resp->nonce = ap_pstrdup(r->pool, value);
+ else if (!strcasecmp(key, "uri"))
+ resp->uri = ap_pstrdup(r->pool, value);
+ else if (!strcasecmp(key, "response"))
+ resp->digest = ap_pstrdup(r->pool, value);
+ else if (!strcasecmp(key, "algorithm"))
+ resp->algorithm = ap_pstrdup(r->pool, value);
+ else if (!strcasecmp(key, "cnonce"))
+ resp->cnonce = ap_pstrdup(r->pool, value);
+ else if (!strcasecmp(key, "opaque"))
+ resp->opaque = ap_pstrdup(r->pool, value);
+ else if (!strcasecmp(key, "qop"))
+ resp->message_qop = ap_pstrdup(r->pool, value);
+ else if (!strcasecmp(key, "nc"))
+ resp->nonce_count = ap_pstrdup(r->pool, value);
+ }
+
+ if (!resp->username || !resp->realm || !resp->nonce || !resp->uri
+ || !resp->digest) {
+ resp->auth_hdr_sts = INVALID;
+ return !OK;
+ }
+
+ if (resp->opaque)
+ resp->opaque_num = (unsigned long) strtol(resp->opaque, NULL, 16);
+
+ resp->auth_hdr_sts = VALID;
+ return OK;
+}
+
+
+/* Because the browser may preemptively send auth info, incrementing the
+ * nonce-count when it does, and because the client does not get notified
+ * if the URI didn't need authentication after all, we need to be sure to
+ * update the nonce-count each time we receive an Authorization header no
+ * matter what the final outcome of the request. Furthermore this is a
+ * convenient place to get the request-uri (before any subrequests etc
+ * are initiated) and to initialize the request_config.
+ *
+ * Note that this must be called after mod_proxy had its go so that
+ * r->proxyreq is set correctly.
+ */
+static int update_nonce_count(request_rec *r)
+{
+ digest_header_rec *resp;
+ int res;
+
+ if (!ap_is_initial_req(r))
+ return DECLINED;
+
+ resp = ap_pcalloc(r->pool, sizeof(digest_header_rec));
+ resp->request_uri = &r->parsed_uri;
+ resp->needed_auth = 0;
+ ap_set_module_config(r->request_config, &digest_auth_module, resp);
+
+ res = get_digest_rec(r, resp);
+ resp->client = get_client(resp->opaque_num, r);
+ if (res == OK && resp->client)
+ resp->client->nonce_count++;
+
+ return DECLINED;
+}
+
+
+/*
+ * Nonce generation code
+ */
+
+/* The hash part of the nonce is a SHA-1 hash of the time, realm, opaque,
+ * and our secret.
+ */
+static void gen_nonce_hash(char *hash, const char *timestr, const char *opaque,
+ const server_rec *server,
+ const digest_config_rec *conf)
+{
+ const char *hex = "0123456789abcdef";
+ unsigned char sha1[SHA_DIGESTSIZE];
+ AP_SHA1_CTX ctx;
+ int idx;
+
+ memcpy(&ctx, &conf->nonce_ctx, sizeof(ctx));
+ ap_SHA1Update_binary(&ctx, (const unsigned char *) server->server_hostname,
+ strlen(server->server_hostname));
+ ap_SHA1Update_binary(&ctx, (const unsigned char *) &server->port,
+ sizeof(server->port));
+ ap_SHA1Update_binary(&ctx, (const unsigned char *) timestr, strlen(timestr));
+ if (opaque)
+ ap_SHA1Update_binary(&ctx, (const unsigned char *) opaque,
+ strlen(opaque));
+ ap_SHA1Final(sha1, &ctx);
+
+ for (idx=0; idx> 4];
+ *hash++ = hex[sha1[idx] & 0xF];
+ }
+
+ *hash++ = '\0';
+}
+
+
+/* The nonce has the format b64(time)+hash .
+ */
+static const char *gen_nonce(pool *p, time_t now, const char *opaque,
+ const server_rec *server,
+ const digest_config_rec *conf)
+{
+ char *nonce = ap_palloc(p, NONCE_LEN+1);
+ time_rec t;
+
+ if (conf->nonce_lifetime != 0)
+ t.time = now;
+ else
+#ifdef HAVE_SHMEM_MM
+ /* this counter is not synch'd, because it doesn't really matter
+ * if it counts exactly.
+ */
+ t.time = (*otn_counter)++;
+#else /* HAVE_SHMEM_MM */
+ t.time = 42;
+#endif /* HAVE_SHMEM_MM */
+ ap_base64encode_binary(nonce, t.arr, sizeof(t.arr));
+ gen_nonce_hash(nonce+NONCE_TIME_LEN, nonce, opaque, server, conf);
+
+ return nonce;
+}
+
+
+/*
+ * Opaque and hash-table management
+ */
+
+#ifdef HAVE_SHMEM_MM
+/*
+ * Generate a new client entry, add it to the list, and return the
+ * entry. Returns NULL if failed.
+ */
+static client_entry *gen_client(const request_rec *r)
+{
+ unsigned long op;
+ client_entry new = { 0, NULL, 0, "", "" }, *entry;
+
+ if (!opaque_mm) return 0;
+
+ mm_lock(opaque_mm, MM_LOCK_RW);
+ op = (*opaque_cntr)++;
+ mm_unlock(opaque_mm);
+
+ if (!(entry = add_client(op, &new, r->server))) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
+ "Digest: failed to allocate client entry - ignoring "
+ "client");
+ return NULL;
+ }
+
+ return entry;
+}
+#else /* HAVE_SHMEM_MM */
+static client_entry *gen_client(const request_rec *r) { return NULL; }
+#endif /* HAVE_SHMEM_MM */
+
+
+
+/*
+ * MD5-sess code.
+ *
+ * If you want to use algorithm=MD5-sess you must write get_userpw_hash()
+ * yourself (see below). The dummy provided here just returns the hash
+ * from the auth-file, i.e. it is only useful for testing client
+ * implementations of MD5-sess .
+ */
+
+/*
+ * get_userpw_hash() will be called each time a new session needs to be
+ * generated and is expected to return the equivalent of
+ *
+ * ap_md5(r->pool,
+ * ap_pstrcat(r->pool, username, ":", ap_auth_name(r), ":", passwd))
+ *
+ * You must implement this yourself, and will probably consist of code
+ * contacting the password server and retrieving the hash from it.
+ *
+ * TBD: This function should probably be in a seperate source file so that
+ * people need not modify mod_auth_digest.c each time they install a new version
+ * of apache.
+ */
+static const char *get_userpw_hash(const request_rec *r,
+ const digest_header_rec *resp,
+ const digest_config_rec *conf)
+{
+ /* for now, just get it from pwfile */
+ return conf->ha1;
+}
+
+
+static const char *get_session(const request_rec *r,
+ digest_header_rec *resp,
+ const digest_config_rec *conf)
+{
+ const char *ha1 = NULL, *urp;
+
+ /* get ha1 from client list */
+ if (resp->opaque && resp->client)
+ ha1 = resp->client->ha1;
+
+ /* generate new session if necessary */
+ if (ha1 == NULL || ha1[0] == '\0') {
+ urp = get_userpw_hash(r, resp, conf);
+ ha1 = ap_md5(r->pool,
+ (unsigned char *) ap_pstrcat(r->pool, ha1, ":", resp->nonce,
+ ":", resp->cnonce, NULL));
+ if (!resp->client)
+ resp->client = gen_client(r);
+ if (resp->client)
+ memcpy(resp->client->ha1, ha1, 17);
+ }
+
+ return ha1;
+}
+
+
+static void clear_session(const digest_header_rec *resp)
+{
+ if (resp->client)
+ resp->client->ha1[0] = '\0';
+}
+
+
+/*
+ * Authorization challenge generation code (for WWW-Authenticate)
+ */
+
+static const char *guess_domain(pool *p, const char *uri, const char *filename,
+ const char *dir)
+{
+ size_t u_len = strlen(uri), f_len = strlen(filename), d_len = strlen(dir);
+ const char *u, *f;
+
+
+ /* Because of things like mod_alias and mod_rewrite and the fact that
+ * protection is often on a directory basis (not a location basis) it
+ * is hard to determine the uri to put in the domain attribute.
+ *
+ * What we do is the following: first we see if the directory is
+ * a prefix for the uri - if this is the case we assume that therefore
+ * a directive was protecting this uri and we can use it
+ * for the domain.
+ */
+ if (u_len >= d_len && !memcmp(uri, dir, d_len))
+ return dir;
+
+ /* Now we check for , and if we find one we send back a
+ * dummy uri - this is the only way to specify that the protection
+ * space only covers a single uri.
+ */
+ if (dir[0] != '/')
+ /* This doesn't work for Amaya (ok, it's of arguable validity in
+ * the first place), so just return the file name instead
+ return "http://0.0.0.0/";
+ */
+ return dir;
+
+ /* Next we find the largest common common suffix of the request-uri
+ * and the final file name, ignoring any extensions; this gives us a
+ * hint as to where any rewriting could've occured (assuming that some
+ * prefix of the uri is rewritten, not a suffix).
+ */
+ u = uri + u_len - 1; /* strip any extension */
+ while (u > uri && *u != '/') u--;
+ while (*u && *u != '.') u++;
+ if (*u == '.') u--;
+ if (*u == '/') u--;
+
+ f = filename + f_len - 1; /* strip any extension */
+ while (f > filename && *f != '/') f--;
+ while (*f && *f != '.') f++;
+ if (*f == '.') f--;
+ if (*f == '/') f--;
+
+ while (*f == *u && f > filename && u > uri) u--, f--;
+ f++; u++;
+
+ while (*f && *f != '/') f++, u++; /* suffix must start with / */
+
+ /* Now, if the directory reaches into this common suffix then we can
+ * take the uri with the same reach.
+ */
+ if ((unsigned long) (f-filename) < d_len) {
+ char *tmp = ap_pstrdup(p, uri);
+ tmp[(u-uri)+(d_len-(f-filename))] = '\0';
+ return tmp;
+ }
+
+ return ""; /* give up */
+}
+
+
+static const char *ltox(pool *p, unsigned long num)
+{
+ if (num != 0)
+ return ap_psprintf(p, "%lx", num);
+ else
+ return "";
+}
+
+static void note_digest_auth_failure(request_rec *r,
+ const digest_config_rec *conf,
+ digest_header_rec *resp, int stale)
+{
+ const char *qop, *opaque, *opaque_param, *domain, *nonce;
+ int cnt;
+
+
+ /* Setup qop */
+
+ if (conf->qop_list[0] == NULL)
+ qop = ", qop=\"auth\"";
+ else if (!strcasecmp(conf->qop_list[0], "none"))
+ qop = "";
+ else {
+ qop = ap_pstrcat(r->pool, ", qop=\"", conf->qop_list[0], NULL);
+ for (cnt=1; conf->qop_list[cnt] != NULL; cnt++)
+ qop = ap_pstrcat(r->pool, qop, ",", conf->qop_list[cnt], NULL);
+ qop = ap_pstrcat(r->pool, qop, "\"", NULL);
+ }
+
+ /* MD5-sess stuff */
+
+ if (!stale && !strcasecmp(conf->algorithm, "MD5-sess"))
+ clear_session(resp);
+
+ /* Setup opaque */
+
+ if (resp->opaque == NULL) {
+ /* new client */
+ if ((conf->check_nc || conf->nonce_lifetime == 0
+ || !strcasecmp(conf->algorithm, "MD5-sess"))
+ && (resp->client = gen_client(r)) != NULL)
+ opaque = ltox(r->pool, resp->client->key);
+ else
+ opaque = ""; /* opaque not needed */
+ }
+ else if (resp->client == NULL) {
+ /* client info was gc'd */
+ resp->client = gen_client(r);
+ if (resp->client != NULL) {
+ opaque = ltox(r->pool, resp->client->key);
+ stale = 1;
+ client_list->num_renewed++;
+ }
+ else
+ opaque = ""; /* ??? */
+ }
+ else {
+ opaque = resp->opaque;
+ /* we're generating a new nonce, so reset the nonce-count */
+ resp->client->nonce_count = 0;
+ }
+
+ if (opaque[0])
+ opaque_param = ap_pstrcat(r->pool, ", opaque=\"", opaque, "\"", NULL);
+ else
+ opaque_param = NULL;
+
+ /* Setup nonce */
+
+ nonce = gen_nonce(r->pool, r->request_time, opaque, r->server, conf);
+ if (resp->client && conf->nonce_lifetime == 0)
+ memcpy(resp->client->last_nonce, nonce, NONCE_LEN+1);
+
+ /* setup domain attribute. We want to send this attribute wherever
+ * possible so that the client won't send the Authorization header
+ * unneccessarily (it's usually > 200 bytes!).
+ */
+
+ if (conf->uri_list)
+ domain = conf->uri_list;
+ else {
+ /* They didn't specify any domain, so let's guess at it */
+ domain = guess_domain(r->pool, resp->request_uri->path, r->filename,
+ conf->dir_name);
+ if (domain[0] == '/' && domain[1] == '\0')
+ domain = ""; /* "/" is the default, so no need to send it */
+ else
+ domain = ap_pstrcat(r->pool, ", domain=\"", domain, "\"", NULL);
+ }
+
+ ap_table_mergen(r->err_headers_out,
+ r->proxyreq ? "Proxy-Authenticate" : "WWW-Authenticate",
+ ap_psprintf(r->pool, "Digest realm=\"%s\", nonce=\"%s\", "
+ "algorithm=%s%s%s%s%s",
+ ap_auth_name(r), nonce, conf->algorithm,
+ opaque_param ? opaque_param : "",
+ domain ? domain : "",
+ stale ? ", stale=true" : "", qop));
+}
+
+
+/*
+ * Authorization header verification code
+ */
+
+static const char *get_hash(request_rec *r, const char *user,
+ const char *realm, const char *auth_pwfile)
+{
+ configfile_t *f;
+ char l[MAX_STRING_LEN];
+ const char *rpw;
+ char *w, *x;
+
+ if (!(f = ap_pcfg_openfile(r->pool, auth_pwfile))) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
+ "Digest: Could not open password file: %s", auth_pwfile);
+ return NULL;
+ }
+ while (!(ap_cfg_getline(l, MAX_STRING_LEN, f))) {
+ if ((l[0] == '#') || (!l[0]))
+ continue;
+ rpw = l;
+ w = ap_getword(r->pool, &rpw, ':');
+ x = ap_getword(r->pool, &rpw, ':');
+
+ if (x && w && !strcmp(user, w) && !strcmp(realm, x)) {
+ ap_cfg_closefile(f);
+ return ap_pstrdup(r->pool, rpw);
+ }
+ }
+ ap_cfg_closefile(f);
+ return NULL;
+}
+
+static int check_nc(const request_rec *r, const digest_header_rec *resp,
+ const digest_config_rec *conf)
+{
+ if (conf->check_nc && client_mm) {
+ unsigned long nc;
+
+ const char *snc = resp->nonce_count;
+ char *endptr;
+
+ nc = strtol(snc, &endptr, 16);
+ if (endptr < (snc+strlen(snc)) && !ap_isspace(*endptr)) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Digest: invalid nc %s received - not a number", snc);
+ return !OK;
+ }
+
+ if (!resp->client)
+ return !OK;
+
+ if (nc != resp->client->nonce_count) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_DEBUG, r,
+ "nonce-count check failed: %lu != %lu", nc,
+ resp->client->nonce_count);
+ return !OK;
+ }
+ }
+
+ return OK;
+}
+
+static int check_nonce(request_rec *r, digest_header_rec *resp,
+ const digest_config_rec *conf)
+{
+ double dt;
+ time_rec nonce_time;
+ char tmp, hash[NONCE_HASH_LEN+1];
+
+ if (strlen(resp->nonce) != NONCE_LEN) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Digest: invalid nonce %s received - length is not %d",
+ resp->nonce, NONCE_LEN);
+ note_digest_auth_failure(r, conf, resp, 1);
+ return AUTH_REQUIRED;
+ }
+
+ tmp = resp->nonce[NONCE_TIME_LEN];
+ resp->nonce[NONCE_TIME_LEN] = '\0';
+ ap_base64decode_binary(nonce_time.arr, resp->nonce);
+ gen_nonce_hash(hash, resp->nonce, resp->opaque, r->server, conf);
+ resp->nonce[NONCE_TIME_LEN] = tmp;
+ resp->nonce_time = nonce_time.time;
+
+ if (strcmp(hash, resp->nonce+NONCE_TIME_LEN)) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Digest: invalid nonce %s received - hash is not %s",
+ resp->nonce, hash);
+ note_digest_auth_failure(r, conf, resp, 1);
+ return AUTH_REQUIRED;
+ }
+
+ dt = difftime(r->request_time, nonce_time.time);
+ if (conf->nonce_lifetime > 0 && dt < 0) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Digest: invalid nonce %s received - user attempted "
+ "time travel", resp->nonce);
+ note_digest_auth_failure(r, conf, resp, 1);
+ return AUTH_REQUIRED;
+ }
+
+ if (conf->nonce_lifetime > 0) {
+ if (dt > conf->nonce_lifetime) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, r,
+ "Digest: user %s: nonce expired - sending new nonce",
+ r->connection->user);
+ note_digest_auth_failure(r, conf, resp, 1);
+ return AUTH_REQUIRED;
+ }
+ }
+ else if (conf->nonce_lifetime == 0 && resp->client) {
+ if (memcmp(resp->client->last_nonce, resp->nonce, NONCE_LEN)) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, r,
+ "Digest: user %s: one-time-nonce mismatch - sending "
+ "new nonce", r->connection->user);
+ note_digest_auth_failure(r, conf, resp, 1);
+ return AUTH_REQUIRED;
+ }
+ }
+ /* else (lifetime < 0) => never expires */
+
+ return OK;
+}
+
+/* The actual MD5 code... whee */
+
+static const char *old_digest(const request_rec *r,
+ const digest_header_rec *resp, const char *ha1)
+{
+ const char *ha2;
+
+ /* rfc-2069 */
+ ha2 = ap_md5(r->pool, (unsigned char *)ap_pstrcat(r->pool, r->method, ":",
+ resp->uri, NULL));
+ return ap_md5(r->pool,
+ (unsigned char *)ap_pstrcat(r->pool, ha1, ":", resp->nonce,
+ ":", ha2, NULL));
+}
+
+static const char *new_digest(const request_rec *r,
+ digest_header_rec *resp,
+ const digest_config_rec *conf)
+{
+ const char *ha1, *ha2, *a2;
+
+ /* draft-ietf-http-authentication-03 */
+ if (resp->algorithm && !strcasecmp(resp->algorithm, "MD5-sess"))
+ ha1 = get_session(r, resp, conf);
+ else
+ ha1 = conf->ha1;
+
+ if (resp->message_qop && !strcasecmp(resp->message_qop, "auth-int"))
+ a2 = ap_pstrcat(r->pool, r->method, ":", resp->uri, ":",
+ ap_md5(r->pool, (const unsigned char*) ""), NULL); /* TBD */
+ else
+ a2 = ap_pstrcat(r->pool, r->method, ":", resp->uri, NULL);
+ ha2 = ap_md5(r->pool, (const unsigned char *)a2);
+
+ return ap_md5(r->pool,
+ (unsigned char *)ap_pstrcat(r->pool, ha1, ":", resp->nonce,
+ ":", resp->nonce_count, ":",
+ resp->cnonce, ":",
+ resp->message_qop, ":", ha2,
+ NULL));
+}
+
+
+/* These functions return 0 if client is OK, and proper error status
+ * if not... either AUTH_REQUIRED, if we made a check, and it failed, or
+ * SERVER_ERROR, if things are so totally confused that we couldn't
+ * figure out how to tell if the client is authorized or not.
+ *
+ * If they return DECLINED, and all other modules also decline, that's
+ * treated by the server core as a configuration error, logged and
+ * reported as such.
+ */
+
+/* Determine user ID, and check if the attributes are correct, if it
+ * really is that user, if the nonce is correct, etc.
+ */
+
+static int authenticate_digest_user(request_rec *r)
+{
+ digest_config_rec *conf;
+ digest_header_rec *resp;
+ request_rec *mainreq;
+ conn_rec *conn = r->connection;
+ const char *t;
+ int res;
+
+
+ /* do we require Digest auth for this URI? */
+
+ if (!(t = ap_auth_type(r)) || strcasecmp(t, "Digest"))
+ return DECLINED;
+
+ if (!ap_auth_name(r)) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Digest: need AuthName: %s", r->uri);
+ return SERVER_ERROR;
+ }
+
+
+ /* get the client response and mark */
+
+ mainreq = r;
+ while (mainreq->main != NULL) mainreq = mainreq->main;
+ while (mainreq->prev != NULL) mainreq = mainreq->prev;
+ resp = (digest_header_rec *) ap_get_module_config(mainreq->request_config,
+ &digest_auth_module);
+ resp->needed_auth = 1;
+
+
+ /* get our conf */
+
+ conf = (digest_config_rec *) ap_get_module_config(r->per_dir_config,
+ &digest_auth_module);
+
+
+ /* check for existence and syntax of Auth header */
+
+ if (resp->auth_hdr_sts != VALID) {
+ if (resp->auth_hdr_sts == NOT_DIGEST)
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Digest: client used wrong authentication scheme "
+ "`%s': %s", resp->scheme, r->uri);
+ else if (resp->auth_hdr_sts == INVALID)
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Digest: missing user, realm, nonce, uri, or digest "
+ "in authorization header: %s", r->uri);
+ /* else (resp->auth_hdr_sts == NO_HEADER) */
+ note_digest_auth_failure(r, conf, resp, 0);
+ return AUTH_REQUIRED;
+ }
+
+ r->connection->user = (char *) resp->username;
+ r->connection->ap_auth_type = (char *) "Digest";
+
+
+ /* check the auth attributes */
+
+ if (strcmp(resp->uri, resp->request_uri->path)) {
+ uri_components *r_uri = resp->request_uri, d_uri;
+ ap_parse_uri_components(r->pool, resp->uri, &d_uri);
+
+ if ((d_uri.hostname && d_uri.hostname[0] != '\0'
+ && strcasecmp(d_uri.hostname, r->server->server_hostname))
+ || (d_uri.port_str && d_uri.port != r->server->port)
+ || (!d_uri.port_str && r->server->port != 80)
+ || strcmp(d_uri.path, r_uri->path)
+ || (d_uri.query != r_uri->query
+ && (!d_uri.query || !r_uri->query
+ || strcmp(d_uri.query, r_uri->query)))
+ ) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Digest: uri mismatch - <%s> does not match "
+ "request-uri <%s>", resp->uri,
+ ap_unparse_uri_components(r->pool, r_uri, 0));
+ return BAD_REQUEST;
+ }
+ }
+
+ if (resp->opaque && resp->opaque_num == 0) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Digest: received invalid opaque - got `%s'",
+ resp->opaque);
+ note_digest_auth_failure(r, conf, resp, 0);
+ return AUTH_REQUIRED;
+ }
+
+ if (strcmp(resp->realm, conf->realm)) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Digest: realm mismatch - got `%s' but expected `%s'",
+ resp->realm, conf->realm);
+ note_digest_auth_failure(r, conf, resp, 0);
+ return AUTH_REQUIRED;
+ }
+
+ if (resp->algorithm != NULL
+ && strcasecmp(resp->algorithm, "MD5")
+ && strcasecmp(resp->algorithm, "MD5-sess")) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Digest: unknown algorithm `%s' received: %s",
+ resp->algorithm, r->uri);
+ note_digest_auth_failure(r, conf, resp, 0);
+ return AUTH_REQUIRED;
+ }
+
+ if (!conf->pwfile)
+ return DECLINED;
+
+ if (!(conf->ha1 = get_hash(r, conn->user, conf->realm, conf->pwfile))) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Digest: user `%s' in realm `%s' not found: %s",
+ conn->user, conf->realm, r->uri);
+ note_digest_auth_failure(r, conf, resp, 0);
+ return AUTH_REQUIRED;
+ }
+
+ if (resp->message_qop == NULL) {
+ /* old (rfc-2069) style digest */
+ if (strcmp(resp->digest, old_digest(r, resp, conf->ha1))) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Digest: user %s: password mismatch: %s", conn->user,
+ r->uri);
+ note_digest_auth_failure(r, conf, resp, 0);
+ return AUTH_REQUIRED;
+ }
+ }
+ else {
+ int match = 0, idx;
+ for (idx=0; conf->qop_list[idx] != NULL; idx++) {
+ if (!strcasecmp(conf->qop_list[idx], resp->message_qop)) {
+ match = 1;
+ break;
+ }
+ }
+
+ if (!match
+ && !(conf->qop_list[0] == NULL
+ && !strcasecmp(resp->message_qop, "auth"))) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Digest: invalid qop `%s' received: %s",
+ resp->message_qop, r->uri);
+ note_digest_auth_failure(r, conf, resp, 0);
+ return AUTH_REQUIRED;
+ }
+
+ if (strcmp(resp->digest, new_digest(r, resp, conf))) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Digest: user %s: password mismatch: %s", conn->user,
+ r->uri);
+ note_digest_auth_failure(r, conf, resp, 0);
+ return AUTH_REQUIRED;
+ }
+ }
+
+ if (check_nc(r, resp, conf) != OK) {
+ note_digest_auth_failure(r, conf, resp, 0);
+ return AUTH_REQUIRED;
+ }
+
+ /* Note: this check is done last so that a "stale=true" can be
+ generated if the nonce is old */
+ if ((res = check_nonce(r, resp, conf)))
+ return res;
+
+ return OK;
+}
+
+
+/*
+ * Checking ID
+ */
+
+static table *groups_for_user(request_rec *r, const char *user,
+ const char *grpfile)
+{
+ configfile_t *f;
+ table *grps = ap_make_table(r->pool, 15);
+ pool *sp;
+ char l[MAX_STRING_LEN];
+ const char *group_name, *ll, *w;
+
+ if (!(f = ap_pcfg_openfile(r->pool, grpfile))) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
+ "Digest: Could not open group file: %s", grpfile);
+ return NULL;
+ }
+
+ sp = ap_make_sub_pool(r->pool);
+
+ while (!(ap_cfg_getline(l, MAX_STRING_LEN, f))) {
+ if ((l[0] == '#') || (!l[0]))
+ continue;
+ ll = l;
+ ap_clear_pool(sp);
+
+ group_name = ap_getword(sp, &ll, ':');
+
+ while (ll[0]) {
+ w = ap_getword_conf(sp, &ll);
+ if (!strcmp(w, user)) {
+ ap_table_setn(grps, ap_pstrdup(r->pool, group_name), "in");
+ break;
+ }
+ }
+ }
+
+ ap_cfg_closefile(f);
+ ap_destroy_pool(sp);
+ return grps;
+}
+
+
+static int digest_check_auth(request_rec *r)
+{
+ const digest_config_rec *conf =
+ (digest_config_rec *) ap_get_module_config(r->per_dir_config,
+ &digest_auth_module);
+ const char *user = r->connection->user;
+ int m = r->method_number;
+ int method_restricted = 0;
+ register int x;
+ const char *t, *w;
+ table *grpstatus;
+ const array_header *reqs_arr;
+ require_line *reqs;
+
+ if (!(t = ap_auth_type(r)) || strcasecmp(t, "Digest"))
+ return DECLINED;
+
+ reqs_arr = ap_requires(r);
+ /* If there is no "requires" directive, then any user will do.
+ */
+ if (!reqs_arr)
+ return OK;
+ reqs = (require_line *) reqs_arr->elts;
+
+ if (conf->grpfile)
+ grpstatus = groups_for_user(r, user, conf->grpfile);
+ else
+ grpstatus = NULL;
+
+ for (x = 0; x < reqs_arr->nelts; x++) {
+
+ if (!(reqs[x].method_mask & (1 << m)))
+ continue;
+
+ method_restricted = 1;
+
+ t = reqs[x].requirement;
+ w = ap_getword_white(r->pool, &t);
+ if (!strcasecmp(w, "valid-user"))
+ return OK;
+ else if (!strcasecmp(w, "user")) {
+ while (t[0]) {
+ w = ap_getword_conf(r->pool, &t);
+ if (!strcmp(user, w))
+ return OK;
+ }
+ }
+ else if (!strcasecmp(w, "group")) {
+ if (!grpstatus)
+ return DECLINED;
+
+ while (t[0]) {
+ w = ap_getword_conf(r->pool, &t);
+ if (ap_table_get(grpstatus, w))
+ return OK;
+ }
+ }
+ else {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Digest: access to %s failed, reason: unknown require "
+ "directive \"%s\"", r->uri, reqs[x].requirement);
+ return DECLINED;
+ }
+ }
+
+ if (!method_restricted)
+ return OK;
+
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Digest: access to %s failed, reason: user %s not allowed access",
+ r->uri, user);
+
+ note_digest_auth_failure(r, conf,
+ (digest_header_rec *) ap_get_module_config(r->request_config,
+ &digest_auth_module),
+ 0);
+ return AUTH_REQUIRED;
+}
+
+
+/*
+ * Authorization-Info header code
+ */
+
+#ifdef SEND_DIGEST
+static const char *hdr(const table *tbl, const char *name)
+{
+ const char *val = ap_table_get(tbl, name);
+ if (val)
+ return val;
+ else
+ return "";
+}
+#endif
+
+static int add_auth_info(request_rec *r)
+{
+ const digest_config_rec *conf =
+ (digest_config_rec *) ap_get_module_config(r->per_dir_config,
+ &digest_auth_module);
+ digest_header_rec *resp =
+ (digest_header_rec *) ap_get_module_config(r->request_config,
+ &digest_auth_module);
+ const char *ai = NULL, *digest = NULL, *nextnonce = "";
+
+ if (resp == NULL || !resp->needed_auth || conf == NULL)
+ return OK;
+
+
+ /* rfc-2069 digest
+ */
+ if (resp->message_qop == NULL) {
+ /* old client, so calc rfc-2069 digest */
+
+#ifdef SEND_DIGEST
+ /* most of this totally bogus because the handlers don't set the
+ * headers until the final handler phase (I wonder why this phase
+ * is called fixup when there's almost nothing you can fix up...)
+ *
+ * Because it's basically impossible to get this right (e.g. the
+ * Content-length is never set yet when we get here, and we can't
+ * calc the entity hash) it's best to just leave this #def'd out.
+ */
+ char *entity_info =
+ ap_md5(r->pool,
+ (unsigned char *) ap_pstrcat(r->pool,
+ ap_unparse_uri_components(r->pool,
+ resp->request_uri, 0), ":",
+ r->content_type ? r->content_type : ap_default_type(r), ":",
+ hdr(r->headers_out, "Content-Length"), ":",
+ r->content_encoding ? r->content_encoding : "", ":",
+ hdr(r->headers_out, "Last-Modified"), ":",
+ r->no_cache && !ap_table_get(r->headers_out, "Expires") ?
+ ap_gm_timestr_822(r->pool, r->request_time) :
+ hdr(r->headers_out, "Expires"),
+ NULL));
+ digest =
+ ap_md5(r->pool,
+ (unsigned char *)ap_pstrcat(r->pool, conf->ha1, ":",
+ resp->nonce, ":",
+ r->method, ":",
+ ap_gm_timestr_822(r->pool, r->request_time), ":",
+ entity_info, ":",
+ ap_md5(r->pool, (unsigned char *) ""), /* H(entity) - TBD */
+ NULL));
+#endif
+ }
+
+
+ /* setup nextnonce
+ */
+ if (conf->nonce_lifetime > 0) {
+ /* send nextnonce if current nonce will expire in less than 30 secs */
+ if (difftime(r->request_time, resp->nonce_time) > (conf->nonce_lifetime-NEXTNONCE_DELTA)) {
+ nextnonce = ap_pstrcat(r->pool, ", nextnonce=\"",
+ gen_nonce(r->pool, r->request_time,
+ resp->opaque, r->server, conf),
+ "\"", NULL);
+ resp->client->nonce_count = 0;
+ }
+ }
+ else if (conf->nonce_lifetime == 0 && resp->client) {
+ const char *nonce = gen_nonce(r->pool, 0, resp->opaque, r->server,
+ conf);
+ nextnonce = ap_pstrcat(r->pool, ", nextnonce=\"", nonce, "\"", NULL);
+ memcpy(resp->client->last_nonce, nonce, NONCE_LEN+1);
+ }
+ /* else nonce never expires, hence no nextnonce */
+
+
+ /* do rfc-2069 digest
+ */
+ if (conf->qop_list[0] && !strcasecmp(conf->qop_list[0], "none")
+ && resp->message_qop == NULL) {
+ /* use only RFC-2069 format */
+ if (digest)
+ ai = ap_pstrcat(r->pool, "digest=\"", digest, "\"", nextnonce,NULL);
+ else
+ ai = nextnonce;
+ }
+ else {
+ const char *resp_dig, *ha1, *a2, *ha2;
+
+ /* calculate rspauth attribute
+ */
+ if (resp->algorithm && !strcasecmp(resp->algorithm, "MD5-sess"))
+ ha1 = get_session(r, resp, conf);
+ else
+ ha1 = conf->ha1;
+
+ if (resp->message_qop && !strcasecmp(resp->message_qop, "auth-int"))
+ a2 = ap_pstrcat(r->pool, ":", resp->uri, ":",
+ ap_md5(r->pool, (const unsigned char *) ""), NULL); /* TBD */
+ else
+ a2 = ap_pstrcat(r->pool, ":", resp->uri, NULL);
+ ha2 = ap_md5(r->pool, (const unsigned char *)a2);
+
+ resp_dig = ap_md5(r->pool,
+ (unsigned char *)ap_pstrcat(r->pool, ha1, ":",
+ resp->nonce, ":",
+ resp->nonce_count, ":",
+ resp->cnonce, ":",
+ resp->message_qop ?
+ resp->message_qop : "",
+ ":", ha2, NULL));
+
+ /* assemble Authentication-Info header
+ */
+ ai = ap_pstrcat(r->pool,
+ "rspauth=\"", resp_dig, "\"",
+ nextnonce,
+ resp->cnonce ? ", cnonce=\"" : "",
+ resp->cnonce ? ap_escape_quotes(r->pool, resp->cnonce) :
+ "",
+ resp->cnonce ? "\"" : "",
+ resp->nonce_count ? ", nc=" : "",
+ resp->nonce_count ? resp->nonce_count : "",
+ resp->message_qop ? ", qop=" : "",
+ resp->message_qop ? resp->message_qop : "",
+ digest ? "digest=\"" : "",
+ digest ? digest : "",
+ digest ? "\"" : "",
+ NULL);
+ }
+
+ if (ai && ai[0])
+ ap_table_mergen(r->headers_out,
+ r->proxyreq ? "Proxy-Authentication-Info" :
+ "Authentication-Info",
+ ai);
+ return OK;
+}
+
+
+module MODULE_VAR_EXPORT digest_auth_module =
+{
+ STANDARD_MODULE_STUFF,
+ initialize_module, /* initializer */
+ create_digest_dir_config, /* dir config creater */
+ NULL, /* dir merger --- default is to override */
+ NULL, /* server config */
+ NULL, /* merge server config */
+ digest_cmds, /* command table */
+ NULL, /* handlers */
+ NULL, /* filename translation */
+ authenticate_digest_user, /* check_user_id */
+ digest_check_auth, /* check auth */
+ NULL, /* check access */
+ NULL, /* type_checker */
+ add_auth_info, /* fixups */
+ NULL, /* logger */
+ NULL, /* header parser */
+ NULL, /* child_init */
+ NULL, /* child_exit */
+ update_nonce_count /* post read-request */
+};
+
diff --git a/modules/aaa/mod_auth_digest.dsp b/modules/aaa/mod_auth_digest.dsp
new file mode 100644
index 00000000000..2f700573f5f
--- /dev/null
+++ b/modules/aaa/mod_auth_digest.dsp
@@ -0,0 +1,97 @@
+# Microsoft Developer Studio Project File - Name="ApacheModuleAuthDigest" - Package Owner=<4>
+# Microsoft Developer Studio Generated Build File, Format Version 5.00
+# ** DO NOT EDIT **
+
+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102
+
+CFG=ApacheModuleAuthDigest - Win32 Debug
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,
+!MESSAGE use the Export Makefile command and run
+!MESSAGE
+!MESSAGE NMAKE /f "ApacheModuleAuthDigest.mak".
+!MESSAGE
+!MESSAGE You can specify a configuration when running NMAKE
+!MESSAGE by defining the macro CFG on the command line. For example:
+!MESSAGE
+!MESSAGE NMAKE /f "ApacheModuleAuthDigest.mak"\
+ CFG="ApacheModuleAuthDigest - Win32 Debug"
+!MESSAGE
+!MESSAGE Possible choices for configuration are:
+!MESSAGE
+!MESSAGE "ApacheModuleAuthDigest - Win32 Release" (based on\
+ "Win32 (x86) Dynamic-Link Library")
+!MESSAGE "ApacheModuleAuthDigest - Win32 Debug" (based on\
+ "Win32 (x86) Dynamic-Link Library")
+!MESSAGE
+
+# Begin Project
+# PROP Scc_ProjName ""
+# PROP Scc_LocalPath ""
+CPP=cl.exe
+MTL=midl.exe
+RSC=rc.exe
+
+!IF "$(CFG)" == "ApacheModuleAuthDigest - Win32 Release"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir "Release"
+# PROP BASE Intermediate_Dir "Release"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir ".\ApacheModuleAuthDigestR"
+# PROP Intermediate_Dir ".\ApacheModuleAuthDigestR"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c
+# ADD CPP /nologo /MT /W3 /GX /O2 /I "..\..\include" /I ".\\" /I "..\..\lib\apr\include" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "SHARED_MODULE" /YX /FD /c
+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /o NUL /win32
+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /o NUL /win32
+# ADD BASE RSC /l 0x409 /d "NDEBUG"
+# ADD RSC /l 0x409 /d "NDEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /machine:I386
+# ADD LINK32 ApacheCore.lib aprlib.lib kernel32.lib /nologo /subsystem:windows /dll /map /machine:I386 /libpath:"..\..\CoreR" /libpath:"..\..\lib\apr\Release"
+
+!ELSEIF "$(CFG)" == "ApacheModuleAuthDigest - Win32 Debug"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 1
+# PROP BASE Output_Dir "Debug"
+# PROP BASE Intermediate_Dir "Debug"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 1
+# PROP Output_Dir ".\ApacheModuleAuthDigestD"
+# PROP Intermediate_Dir ".\ApacheModuleAuthDigestD"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /FD /c
+# ADD CPP /nologo /MTd /W3 /Gm /GX /Zi /Od /I "..\..\include" /I ".\\" /I "..\..\lib\apr\include" /D "_DEBUG" /D "SHARED_MODULE" /D "WIN32" /D "_WINDOWS" /YX /FD /c
+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /o NUL /win32
+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /o NUL /win32
+# ADD BASE RSC /l 0x409 /d "_DEBUG"
+# ADD RSC /l 0x409 /d "_DEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /debug /machine:I386 /pdbtype:sept
+# ADD LINK32 ApacheCore.lib aprlib.lib kernel32.lib /nologo /subsystem:windows /dll /map /debug /machine:I386 /pdbtype:sept /libpath:"..\..\CoreD" /libpath:"..\..\lib\apr\Debug"
+
+!ENDIF
+
+# Begin Target
+
+# Name "ApacheModuleAuthDigest - Win32 Release"
+# Name "ApacheModuleAuthDigest - Win32 Debug"
+# Begin Source File
+
+SOURCE=..\..\modules\standard\mod_auth_digest.c
+# End Source File
+# End Target
+# End Project
diff --git a/modules/arch/win32/mod_isapi.c b/modules/arch/win32/mod_isapi.c
new file mode 100644
index 00000000000..fa002708ba5
--- /dev/null
+++ b/modules/arch/win32/mod_isapi.c
@@ -0,0 +1,569 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+/*
+ * mod_isapi.c - Internet Server Application (ISA) module for Apache
+ * by Alexei Kosut
+ *
+ * This module implements Microsoft's ISAPI, allowing Apache (when running
+ * under Windows) to load Internet Server Applications (ISAPI extensions).
+ * It implements all of the ISAPI 2.0 specification, except for the
+ * "Microsoft-only" extensions dealing with asynchronous I/O. All ISAPI
+ * extensions that use only synchronous I/O and are compatible with the
+ * ISAPI 2.0 specification should work (most ISAPI 1.0 extensions should
+ * function as well).
+ *
+ * To load, simply place the ISA in a location in the document tree.
+ * Then add an "AddHandler isapi-isa dll" into your config file.
+ * You should now be able to load ISAPI DLLs just be reffering to their
+ * URLs. Make sure the ExecCGI option is active in the directory
+ * the ISA is in.
+ */
+
+#include "httpd.h"
+#include "http_config.h"
+#include "http_core.h"
+#include "http_protocol.h"
+#include "http_request.h"
+#include "http_log.h"
+#include "util_script.h"
+
+/* We use the exact same header file as the original */
+#include
+
+/* Seems IIS does not enforce the requirement for \r\n termination on HSE_REQ_SEND_RESPONSE_HEADER,
+ define this to conform */
+#define RELAX_HEADER_RULE
+
+module isapi_module;
+
+/* Our "Connection ID" structure */
+
+typedef struct {
+ LPEXTENSION_CONTROL_BLOCK ecb;
+ request_rec *r;
+ int status;
+} isapi_cid;
+
+/* Declare the ISAPI functions */
+
+BOOL WINAPI GetServerVariable (HCONN hConn, LPSTR lpszVariableName,
+ LPVOID lpvBuffer, LPDWORD lpdwSizeofBuffer);
+BOOL WINAPI WriteClient (HCONN ConnID, LPVOID Buffer, LPDWORD lpwdwBytes,
+ DWORD dwReserved);
+BOOL WINAPI ReadClient (HCONN ConnID, LPVOID lpvBuffer, LPDWORD lpdwSize);
+BOOL WINAPI ServerSupportFunction (HCONN hConn, DWORD dwHSERequest,
+ LPVOID lpvBuffer, LPDWORD lpdwSize,
+ LPDWORD lpdwDataType);
+
+/*
+ The optimiser blows it totally here. What happens is that autos are addressed relative to the
+ stack pointer, which, of course, moves around. The optimiser seems to lose track of it somewhere
+ between setting isapi_entry and calling through it. We work around the problem by forcing it to
+ use frame pointers.
+*/
+#pragma optimize("y",off)
+
+int isapi_handler (request_rec *r) {
+ LPEXTENSION_CONTROL_BLOCK ecb =
+ ap_pcalloc(r->pool, sizeof(struct _EXTENSION_CONTROL_BLOCK));
+ HSE_VERSION_INFO *pVer = ap_pcalloc(r->pool, sizeof(HSE_VERSION_INFO));
+
+ HINSTANCE isapi_handle;
+ BOOL (*isapi_version)(HSE_VERSION_INFO *); /* entry point 1 */
+ DWORD (*isapi_entry)(LPEXTENSION_CONTROL_BLOCK); /* entry point 2 */
+ BOOL (*isapi_term)(DWORD); /* optional entry point 3 */
+
+ isapi_cid *cid = ap_pcalloc(r->pool, sizeof(isapi_cid));
+ table *e = r->subprocess_env;
+ int retval;
+
+ /* Use similar restrictions as CGIs */
+
+ if (!(ap_allow_options(r) & OPT_EXECCGI))
+ return FORBIDDEN;
+
+ if (r->finfo.st_mode == 0)
+ return NOT_FOUND;
+
+ if (S_ISDIR(r->finfo.st_mode))
+ return FORBIDDEN;
+
+ /* Load the module */
+
+ if (!(isapi_handle = LoadLibraryEx(r->filename, NULL,
+ LOAD_WITH_ALTERED_SEARCH_PATH))) {
+ ap_log_rerror(APLOG_MARK, APLOG_ALERT, r,
+ "Could not load DLL: %s", r->filename);
+ return SERVER_ERROR;
+ }
+
+ if (!(isapi_version =
+ (void *)(GetProcAddress(isapi_handle, "GetExtensionVersion")))) {
+ ap_log_rerror(APLOG_MARK, APLOG_ALERT, r,
+ "DLL could not load GetExtensionVersion(): %s", r->filename);
+ FreeLibrary(isapi_handle);
+ return SERVER_ERROR;
+ }
+
+ if (!(isapi_entry =
+ (void *)(GetProcAddress(isapi_handle, "HttpExtensionProc")))) {
+ ap_log_rerror(APLOG_MARK, APLOG_ALERT, r,
+ "DLL could not load HttpExtensionProc(): %s", r->filename);
+ FreeLibrary(isapi_handle);
+ return SERVER_ERROR;
+ }
+
+ isapi_term = (void *)(GetProcAddress(isapi_handle, "TerminateExtension"));
+
+ /* Run GetExtensionVersion() */
+
+ if ((*isapi_version)(pVer) != TRUE) {
+ ap_log_rerror(APLOG_MARK, APLOG_ALERT, r,
+ "ISAPI GetExtensionVersion() failed: %s", r->filename);
+ FreeLibrary(isapi_handle);
+ return SERVER_ERROR;
+ }
+
+ /* Set up variables */
+ ap_add_common_vars(r);
+ ap_add_cgi_vars(r);
+
+ /* Set up connection ID */
+ ecb->ConnID = (HCONN)cid;
+ cid->ecb = ecb;
+ cid->r = r;
+ cid->status = 0;
+
+ ecb->cbSize = sizeof(struct _EXTENSION_CONTROL_BLOCK);
+ ecb->dwVersion = MAKELONG(0, 2);
+ ecb->dwHttpStatusCode = 0;
+ strcpy(ecb->lpszLogData, "");
+ ecb->lpszMethod = r->method;
+ ecb->lpszQueryString = ap_table_get(e, "QUERY_STRING");
+ ecb->lpszPathInfo = ap_table_get(e, "PATH_INFO");
+ ecb->lpszPathTranslated = ap_table_get(e, "PATH_TRANSLATED");
+ ecb->lpszContentType = ap_table_get(e, "CONTENT_TYPE");
+
+ /* Set up client input */
+ if ((retval = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))) {
+ if (isapi_term) (*isapi_term)(HSE_TERM_MUST_UNLOAD);
+ FreeLibrary(isapi_handle);
+ return retval;
+ }
+
+ if (ap_should_client_block(r)) {
+ /* Unlike IIS, which limits this to 48k, we read the whole
+ * sucker in. I suppose this could be bad for memory if someone
+ * uploaded the complete works of Shakespeare. Well, WebSite
+ * does the same thing.
+ */
+ long to_read = atol(ap_table_get(e, "CONTENT_LENGTH"));
+ long read;
+
+ /* Actually, let's cap it at 48k, until we figure out what
+ * to do with this... we don't want a Content-Length: 1000000000
+ * taking out the machine.
+ */
+
+ if (to_read > 49152) {
+ if (isapi_term) (*isapi_term)(HSE_TERM_MUST_UNLOAD);
+ FreeLibrary(isapi_handle);
+ return HTTP_REQUEST_ENTITY_TOO_LARGE;
+ }
+
+ ecb->lpbData = ap_pcalloc(r->pool, 1 + to_read);
+
+ if ((read = ap_get_client_block(r, ecb->lpbData, to_read)) < 0) {
+ if (isapi_term) (*isapi_term)(HSE_TERM_MUST_UNLOAD);
+ FreeLibrary(isapi_handle);
+ return SERVER_ERROR;
+ }
+
+ /* Although its not to spec, IIS seems to null-terminate
+ * its lpdData string. So we will too. To make sure
+ * cbAvailable matches cbTotalBytes, we'll up the latter
+ * and equalize them.
+ */
+ ecb->cbAvailable = ecb->cbTotalBytes = read + 1;
+ ecb->lpbData[read] = '\0';
+ }
+ else {
+ ecb->cbTotalBytes = 0;
+ ecb->cbAvailable = 0;
+ ecb->lpbData = NULL;
+ }
+
+ /* Set up the callbacks */
+
+ ecb->GetServerVariable = &GetServerVariable;
+ ecb->WriteClient = &WriteClient;
+ ecb->ReadClient = &ReadClient;
+ ecb->ServerSupportFunction = &ServerSupportFunction;
+
+ /* All right... try and load the sucker */
+ retval = (*isapi_entry)(ecb);
+
+ /* Set the status (for logging) */
+ if (ecb->dwHttpStatusCode)
+ r->status = ecb->dwHttpStatusCode;
+
+ /* Check for a log message - and log it */
+ if (ecb->lpszLogData && strcmp(ecb->lpszLogData, ""))
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
+ "%s: %s", ecb->lpszLogData, r->filename);
+
+ /* All done with the DLL... get rid of it */
+ if (isapi_term) (*isapi_term)(HSE_TERM_MUST_UNLOAD);
+ FreeLibrary(isapi_handle);
+
+ switch(retval) {
+ case HSE_STATUS_SUCCESS:
+ case HSE_STATUS_SUCCESS_AND_KEEP_CONN:
+ /* Ignore the keepalive stuff; Apache handles it just fine without
+ * the ISA's "advice".
+ */
+
+ if (cid->status) /* We have a special status to return */
+ return cid->status;
+
+ return OK;
+ case HSE_STATUS_PENDING: /* We don't support this */
+ ap_log_rerror(APLOG_MARK, APLOG_WARNING, r,
+ "ISAPI asynchronous I/O not supported: %s", r->filename);
+ case HSE_STATUS_ERROR:
+ default:
+ return SERVER_ERROR;
+ }
+
+}
+#pragma optimize("",on)
+
+BOOL WINAPI GetServerVariable (HCONN hConn, LPSTR lpszVariableName,
+ LPVOID lpvBuffer, LPDWORD lpdwSizeofBuffer) {
+ request_rec *r = ((isapi_cid *)hConn)->r;
+ table *e = r->subprocess_env;
+ const char *result;
+
+ /* Mostly, we just grab it from the environment, but there are
+ * a couple of special cases
+ */
+
+ if (!strcasecmp(lpszVariableName, "UNMAPPED_REMOTE_USER")) {
+ /* We don't support NT users, so this is always the same as
+ * REMOTE_USER
+ */
+ result = ap_table_get(e, "REMOTE_USER");
+ }
+ else if (!strcasecmp(lpszVariableName, "SERVER_PORT_SECURE")) {
+ /* Apache doesn't support secure requests inherently, so
+ * we have no way of knowing. We'll be conservative, and say
+ * all requests are insecure.
+ */
+ result = "0";
+ }
+ else if (!strcasecmp(lpszVariableName, "URL")) {
+ result = r->uri;
+ }
+ else {
+ result = ap_table_get(e, lpszVariableName);
+ }
+
+ if (result) {
+ if (strlen(result) > *lpdwSizeofBuffer) {
+ *lpdwSizeofBuffer = strlen(result);
+ SetLastError(ERROR_INSUFFICIENT_BUFFER);
+ return FALSE;
+ }
+ strncpy(lpvBuffer, result, *lpdwSizeofBuffer);
+ return TRUE;
+ }
+
+ /* Didn't find it */
+ SetLastError(ERROR_INVALID_INDEX);
+ return FALSE;
+}
+
+BOOL WINAPI WriteClient (HCONN ConnID, LPVOID Buffer, LPDWORD lpwdwBytes,
+ DWORD dwReserved) {
+ request_rec *r = ((isapi_cid *)ConnID)->r;
+ int writ; /* written, actually, but why shouldn't I make up words? */
+
+ /* We only support synchronous writing */
+ if (dwReserved && dwReserved != HSE_IO_SYNC) {
+ ap_log_rerror(APLOG_MARK, APLOG_WARNING, r,
+ "ISAPI asynchronous I/O not supported: %s", r->filename);
+ SetLastError(ERROR_INVALID_PARAMETER);
+ return FALSE;
+ }
+
+ if ((writ = ap_rwrite(Buffer, *lpwdwBytes, r)) == EOF) {
+ SetLastError(ERROR); /* XXX: Find the right error code */
+ return FALSE;
+ }
+
+ *lpwdwBytes = writ;
+ return TRUE;
+}
+
+BOOL WINAPI ReadClient (HCONN ConnID, LPVOID lpvBuffer, LPDWORD lpdwSize) {
+ /* Doesn't need to do anything; we've read all the data already */
+ return TRUE;
+}
+
+/* XXX: There is an O(n^2) attack possible here. */
+BOOL WINAPI ServerSupportFunction (HCONN hConn, DWORD dwHSERequest,
+ LPVOID lpvBuffer, LPDWORD lpdwSize,
+ LPDWORD lpdwDataType) {
+ isapi_cid *cid = (isapi_cid *)hConn;
+ request_rec *subreq, *r = cid->r;
+ char *data;
+
+ switch (dwHSERequest) {
+ case HSE_REQ_SEND_URL_REDIRECT_RESP:
+ /* Set the status to be returned when the HttpExtensionProc()
+ * is done.
+ */
+ ap_table_set (r->headers_out, "Location", lpvBuffer);
+ cid->status = cid->r->status = cid->ecb->dwHttpStatusCode = REDIRECT;
+ return TRUE;
+
+ case HSE_REQ_SEND_URL:
+ /* Read any additional input */
+
+ if (r->remaining > 0) {
+ char argsbuffer[HUGE_STRING_LEN];
+
+ while (ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN));
+ }
+
+ /* Reset the method to GET */
+ r->method = ap_pstrdup(r->pool, "GET");
+ r->method_number = M_GET;
+
+ /* Don't let anyone think there's still data */
+ ap_table_unset(r->headers_in, "Content-Length");
+
+ ap_internal_redirect((char *)lpvBuffer, r);
+ return TRUE;
+
+ case HSE_REQ_SEND_RESPONSE_HEADER:
+ r->status_line = lpvBuffer ? lpvBuffer : ap_pstrdup(r->pool, "200 OK");
+ sscanf(r->status_line, "%d", &r->status);
+ cid->ecb->dwHttpStatusCode = r->status;
+
+ /* Now fill in the HTTP headers, and the rest of it. Ick.
+ * lpdwDataType contains a string that has headers (in MIME
+ * format), a blank like, then (possibly) data. We need
+ * to parse it.
+ *
+ * Easy case first:
+ */
+ if (!lpdwDataType) {
+ ap_send_http_header(r);
+ return TRUE;
+ }
+
+ /* Make a copy - don't disturb the original */
+ data = ap_pstrdup(r->pool, (char *)lpdwDataType);
+
+ /* We *should* break before this while loop ends */
+ while (*data) {
+ char *value, *lf = strchr(data, '\n');
+ int p;
+
+#ifdef RELAX_HEADER_RULE
+ if (lf)
+ *lf = '\0';
+#else
+ if (!lf) { /* Huh? Invalid data, I think */
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
+ "ISA sent invalid headers: %s", r->filename);
+ SetLastError(ERROR); /* XXX: Find right error */
+ return FALSE;
+ }
+
+ /* Get rid of \n and \r */
+ *lf = '\0';
+#endif
+ p = strlen(data);
+ if (p > 0 && data[p-1] == '\r') data[p-1] = '\0';
+
+ /* End of headers */
+ if (*data == '\0') {
+#ifdef RELAX_HEADER_RULE
+ if (lf)
+#endif
+ data = lf + 1; /* Reset data */
+ break;
+ }
+
+ if (!(value = strchr(data, ':'))) {
+ SetLastError(ERROR); /* XXX: Find right error */
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
+ "ISA sent invalid headers", r->filename);
+ return FALSE;
+ }
+
+ *value++ = '\0';
+ while (*value && ap_isspace(*value)) ++value;
+
+ /* Check all the special-case headers. Similar to what
+ * ap_scan_script_header_err() does (see that function for
+ * more detail)
+ */
+
+ if (!strcasecmp(data, "Content-Type")) {
+ char *tmp;
+ /* Nuke trailing whitespace */
+
+ char *endp = value + strlen(value) - 1;
+ while (endp > value && ap_isspace(*endp)) *endp-- = '\0';
+
+ tmp = ap_pstrdup (r->pool, value);
+ ap_str_tolower(tmp);
+ r->content_type = tmp;
+ }
+ else if (!strcasecmp(data, "Content-Length")) {
+ ap_table_set(r->headers_out, data, value);
+ }
+ else if (!strcasecmp(data, "Transfer-Encoding")) {
+ ap_table_set(r->headers_out, data, value);
+ }
+ else if (!strcasecmp(data, "Set-Cookie")) {
+ ap_table_add(r->err_headers_out, data, value);
+ }
+ else {
+ ap_table_merge(r->err_headers_out, data, value);
+ }
+
+ /* Reset data */
+#ifdef RELAX_HEADER_RULE
+ if (!lf) {
+ data += p;
+ break;
+ }
+#endif
+ data = lf + 1;
+ }
+
+ /* All the headers should be set now */
+
+ ap_send_http_header(r);
+
+ /* Any data left should now be sent directly */
+ ap_rputs(data, r);
+
+ return TRUE;
+
+ case HSE_REQ_MAP_URL_TO_PATH:
+ /* Map a URL to a filename */
+ subreq = ap_sub_req_lookup_uri(ap_pstrndup(r->pool, (char *)lpvBuffer,
+ *lpdwSize), r);
+
+ GetFullPathName(subreq->filename, *lpdwSize - 1, (char *)lpvBuffer, NULL);
+
+ /* IIS puts a trailing slash on directories, Apache doesn't */
+
+ if (S_ISDIR (subreq->finfo.st_mode)) {
+ int l = strlen((char *)lpvBuffer);
+
+ ((char *)lpvBuffer)[l] = '\\';
+ ((char *)lpvBuffer)[l + 1] = '\0';
+ }
+
+ return TRUE;
+
+ case HSE_REQ_DONE_WITH_SESSION:
+ /* Do nothing... since we don't support async I/O, they'll
+ * return from HttpExtensionProc soon
+ */
+ return TRUE;
+
+ /* We don't support all this async I/O, Microsoft-specific stuff */
+ case HSE_REQ_IO_COMPLETION:
+ case HSE_REQ_TRANSMIT_FILE:
+ ap_log_rerror(APLOG_MARK, APLOG_WARNING, r,
+ "ISAPI asynchronous I/O not supported: %s", r->filename);
+ default:
+ SetLastError(ERROR_INVALID_PARAMETER);
+ return FALSE;
+ }
+}
+
+handler_rec isapi_handlers[] = {
+{ "isapi-isa", isapi_handler },
+{ NULL}
+};
+
+module isapi_module = {
+ STANDARD_MODULE_STUFF,
+ NULL, /* initializer */
+ NULL, /* create per-dir config */
+ NULL, /* merge per-dir config */
+ NULL, /* server config */
+ NULL, /* merge server config */
+ NULL, /* command table */
+ isapi_handlers, /* handlers */
+ NULL, /* filename translation */
+ NULL, /* check_user_id */
+ NULL, /* check auth */
+ NULL, /* check access */
+ NULL, /* type_checker */
+ NULL, /* logger */
+ NULL /* header parser */
+};
diff --git a/modules/cache/.indent.pro b/modules/cache/.indent.pro
new file mode 100644
index 00000000000..a9fbe9f9a1f
--- /dev/null
+++ b/modules/cache/.indent.pro
@@ -0,0 +1,54 @@
+-i4 -npsl -di0 -br -nce -d0 -cli0 -npcs -nfc1
+-TBUFF
+-TFILE
+-TTRANS
+-TUINT4
+-T_trans
+-Tallow_options_t
+-Tapache_sfio
+-Tarray_header
+-Tbool_int
+-Tbuf_area
+-Tbuff_struct
+-Tbuffy
+-Tcmd_how
+-Tcmd_parms
+-Tcommand_rec
+-Tcommand_struct
+-Tconn_rec
+-Tcore_dir_config
+-Tcore_server_config
+-Tdir_maker_func
+-Tevent
+-Tglobals_s
+-Thandler_func
+-Thandler_rec
+-Tjoblist_s
+-Tlisten_rec
+-Tmerger_func
+-Tmode_t
+-Tmodule
+-Tmodule_struct
+-Tmutex
+-Tn_long
+-Tother_child_rec
+-Toverrides_t
+-Tparent_score
+-Tpid_t
+-Tpiped_log
+-Tpool
+-Trequest_rec
+-Trequire_line
+-Trlim_t
+-Tscoreboard
+-Tsemaphore
+-Tserver_addr_rec
+-Tserver_rec
+-Tserver_rec_chain
+-Tshort_score
+-Ttable
+-Ttable_entry
+-Tthread
+-Tu_wide_int
+-Tvtime_t
+-Twide_int
diff --git a/modules/cache/mod_file_cache.c b/modules/cache/mod_file_cache.c
new file mode 100644
index 00000000000..81e269dc4c2
--- /dev/null
+++ b/modules/cache/mod_file_cache.c
@@ -0,0 +1,559 @@
+/* ====================================================================
+ * Copyright (c) 1998-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+/*
+ * Author: mod_file_cache by Bill Stoddard
+ * Based on mod_mmap_static by Dean Gaudet
+ *
+ * v0.01: initial implementation
+ */
+
+/*
+ Documentation:
+
+ Some sites have a set of static files that are really busy, and
+ change infrequently (or even on a regular schedule). Save time
+ by caching open handles to these files. This module, unlike
+ mod_mmap_static, caches open file handles, not file content.
+ On systems (like Windows) with heavy system call overhead and
+ that have an efficient sendfile implementation, caching file handles
+ offers several advantages over caching content. First, the file system
+ can manage the memory, allowing infrequently hit cached files to
+ be paged out. Second, since caching open handles does not consume
+ significant resources, it will be possible to enable an AutoLoadCache
+ feature where static files are dynamically loaded in the cache
+ as the server runs. On systems that have file change notification,
+ this module can be enhanced to automatically garbage collect
+ cached files that change on disk.
+
+ This module should work on Unix systems that have sendfile. Place
+ cachefile directives into your configuration to direct files to
+ be cached.
+
+ cachefile /path/to/file1
+ cachefile /path/to/file2
+ ...
+
+ These files are only cached when the server is restarted, so if you
+ change the list, or if the files are changed, then you'll need to
+ restart the server.
+
+ To reiterate that point: if the files are modified *in place*
+ without restarting the server you may end up serving requests that
+ are completely bogus. You should update files by unlinking the old
+ copy and putting a new copy in place.
+
+ There's no such thing as inheriting these files across vhosts or
+ whatever... place the directives in the main server only.
+
+ Known problems:
+
+ Don't use Alias or RewriteRule to move these files around... unless
+ you feel like paying for an extra stat() on each request. This is
+ a deficiency in the Apache API that will hopefully be solved some day.
+ The file will be served out of the file handle cache, but there will be
+ an extra stat() that's a waste.
+*/
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+#define CORE_PRIVATE
+
+#include "httpd.h"
+#include "http_config.h"
+#include "http_log.h"
+#include "http_protocol.h"
+#include "http_request.h"
+#include "http_core.h"
+#include "apr_mmap.h"
+
+module MODULE_VAR_EXPORT file_cache_module;
+static ap_pool_t *context;
+static int once_through = 0;
+
+typedef struct {
+#if 1
+ ap_file_t *file;
+#else
+ ap_mmap_t *mm;
+#endif
+ char *filename;
+ ap_finfo_t finfo;
+} a_file;
+
+typedef struct {
+ ap_array_header_t *files;
+ ap_array_header_t *inode_sorted;
+} a_server_config;
+
+
+static void *create_server_config(ap_pool_t *p, server_rec *s)
+{
+ a_server_config *sconf = ap_palloc(p, sizeof(*sconf));
+
+ sconf->files = ap_make_array(p, 20, sizeof(a_file));
+ sconf->inode_sorted = NULL;
+ return sconf;
+}
+#if 0
+static void pre_config(ap_pool_t *pconf, ap_pool_t *plog, ap_pool_t *ptemp)
+{
+ context = pconf;
+}
+#endif
+static ap_status_t open_file(ap_file_t **file, char* filename, int flg1, int flg2,
+ ap_pool_t *context)
+{
+ ap_status_t rv;
+#ifdef WIN32
+ /* The Windows file needs to be opened for overlapped i/o, which APR doesn't
+ * support.
+ */
+ HANDLE hFile;
+ hFile = CreateFile(filename, /* pointer to name of the file */
+ GENERIC_READ, /* access (read-write) mode */
+ FILE_SHARE_READ, /* share mode */
+ NULL, /* pointer to security attributes */
+ OPEN_EXISTING, /* how to create */
+ FILE_FLAG_OVERLAPPED | FILE_FLAG_SEQUENTIAL_SCAN, /* file attributes */
+ NULL); /* handle to file with attributes to copy */
+ if (hFile != INVALID_HANDLE_VALUE) {
+ rv = ap_put_os_file(file, &hFile, context);
+ }
+ else {
+ rv = GetLastError();
+ *file = NULL;
+ }
+#else
+ rv = ap_open(file, filename, flg1, flg2, context);
+#endif
+
+ return rv;
+}
+
+ap_status_t cleanup_mmap(void *sconfv)
+{
+ a_server_config *sconf = sconfv;
+ size_t n;
+ a_file *file;
+
+ n = sconf->files->nelts;
+ file = (a_file *)sconf->files->elts;
+ while(n) {
+#if 1
+ ap_close(file->file);
+#else
+ ap_mmap_delete(file->mm);
+#endif
+ ++file;
+ --n;
+ }
+ return APR_SUCCESS;
+}
+
+static const char *cachefile(cmd_parms *cmd, void *dummy, char *filename)
+{
+ a_server_config *sconf;
+ a_file *new_file;
+ a_file tmp;
+ ap_file_t *fd = NULL;
+#if 0
+ caddr_t mm;
+#endif
+ ap_status_t rc;
+ /* canonicalize the file name */
+ /* os_canonical... */
+ if (ap_stat(&tmp.finfo, filename, NULL) != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_WARNING, errno, cmd->server,
+ "file_cache: unable to stat(%s), skipping", filename);
+ return NULL;
+ }
+ if (tmp.finfo.filetype != APR_REG) {
+ ap_log_error(APLOG_MARK, APLOG_WARNING, errno, cmd->server,
+ "file_cache: %s isn't a regular file, skipping", filename);
+ return NULL;
+ }
+ /* Note: open_file should call ap_open for Unix and CreateFile for Windows.
+ * The Windows file needs to be opened for async I/O to allow multiple threads
+ * to serve it up at once.
+ */
+ rc = open_file(&fd, filename, APR_READ, APR_OS_DEFAULT, cmd->pool); //context);
+ if (rc != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_WARNING, rc, cmd->server,
+ "file_cache: unable to open(%s, O_RDONLY), skipping", filename);
+ return NULL;
+ }
+#if 1
+ tmp.file = fd;
+#else
+ if (ap_mmap_create(&tmp.mm, fd, 0, tmp.finfo.st_size, context) != APR_SUCCESS) {
+ int save_errno = errno;
+ ap_close(fd);
+ errno = save_errno;
+ ap_log_error(APLOG_MARK, APLOG_WARNING, errno, cmd->server,
+ "file_cache: unable to mmap %s, skipping", filename);
+ return NULL;
+ }
+ ap_close(fd);
+#endif
+ tmp.filename = ap_pstrdup(cmd->pool, filename);
+ sconf = ap_get_module_config(cmd->server->module_config, &file_cache_module);
+ new_file = ap_push_array(sconf->files);
+ *new_file = tmp;
+ if (sconf->files->nelts == 1) {
+ /* first one, register the cleanup */
+ ap_register_cleanup(cmd->pool, sconf, cleanup_mmap, ap_null_cleanup);
+ }
+ return NULL;
+}
+
+#ifdef WIN32
+/* Windows doesn't have inodes. This ifdef should be changed to
+ * something like HAVE_INODES
+ */
+static int file_compare(const void *av, const void *bv)
+{
+ const a_file *a = av;
+ const a_file *b = bv;
+
+ return strcmp(a->filename, b->filename);
+}
+#else
+static int inode_compare(const void *av, const void *bv)
+{
+ const a_file *a = *(a_file **)av;
+ const a_file *b = *(a_file **)bv;
+ long c;
+
+ c = a->finfo.st_ino - b->finfo.st_ino;
+ if (c == 0) {
+ return a->finfo.st_dev - b->finfo.st_dev;
+ }
+ return c;
+}
+#endif
+static void file_cache_post_config(ap_pool_t *p, ap_pool_t *plog,
+ ap_pool_t *ptemp, server_rec *s)
+{
+ a_server_config *sconf;
+ ap_array_header_t *inodes;
+ a_file *elts;
+ int nelts;
+ int i;
+
+ context = p;
+ /* sort the elements of the main_server, by filename */
+ sconf = ap_get_module_config(s->module_config, &file_cache_module);
+ elts = (a_file *)sconf->files->elts;
+ nelts = sconf->files->nelts;
+ qsort(elts, nelts, sizeof(a_file), file_compare);
+
+ /* build an index by inode as well, speeds up the search in the handler */
+#ifndef WIN32
+ inodes = ap_make_array(p, nelts, sizeof(a_file *));
+ sconf->inode_sorted = inodes;
+ for (i = 0; i < nelts; ++i) {
+ *(a_file **)ap_push_array(inodes) = &elts[i];
+ }
+ qsort(inodes->elts, nelts, sizeof(a_file *), inode_compare);
+#endif
+ /* and make the virtualhosts share the same thing */
+ for (s = s->next; s; s = s->next) {
+ ap_set_module_config(s->module_config, &file_cache_module, sconf);
+ }
+}
+
+/* If it's one of ours, fill in r->finfo now to avoid extra stat()... this is a
+ * bit of a kludge, because we really want to run after core_translate runs.
+ */
+int core_translate_copy(request_rec *r)
+{
+ void *sconf = r->server->module_config;
+ core_server_config *conf = ap_get_module_config(sconf, &core_module);
+
+ if (r->proxyreq) {
+ return HTTP_FORBIDDEN;
+ }
+ if ((r->uri[0] != '/') && strcmp(r->uri, "*")) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
+ "Invalid URI in request %s", r->the_request);
+ return BAD_REQUEST;
+ }
+
+ if (r->server->path
+ && !strncmp(r->uri, r->server->path, r->server->pathlen)
+ && (r->server->path[r->server->pathlen - 1] == '/'
+ || r->uri[r->server->pathlen] == '/'
+ || r->uri[r->server->pathlen] == '\0')) {
+ r->filename = ap_pstrcat(r->pool, conf->ap_document_root,
+ (r->uri + r->server->pathlen), NULL);
+ }
+ else {
+ /*
+ * Make sure that we do not mess up the translation by adding two
+ * /'s in a row. This happens under windows when the document
+ * root ends with a /
+ */
+ if ((conf->ap_document_root[strlen(conf->ap_document_root)-1] == '/')
+ && (*(r->uri) == '/')) {
+ r->filename = ap_pstrcat(r->pool, conf->ap_document_root, r->uri+1,
+ NULL);
+ }
+ else {
+ r->filename = ap_pstrcat(r->pool, conf->ap_document_root, r->uri,
+ NULL);
+ }
+
+ return OK;
+ }
+}
+static int file_cache_xlat(request_rec *r)
+{
+ a_server_config *sconf;
+ a_file tmp;
+ a_file *match;
+ int res;
+
+#ifdef WIN32
+/*
+ * This is really broken on Windows. The call to get the core_module config
+ * in core_translate_copy seg faults because 'core_module' is not exported
+ * properly and needs a thunk.
+ * Will be fixed when we get API_VAR_EXPORTS working correctly again
+ */
+ return DECLINED;
+#endif
+
+ sconf = ap_get_module_config(r->server->module_config, &file_cache_module);
+
+ /* we only operate when at least one cachefile directive was used */
+ if (ap_is_empty_table(sconf->files))
+ return DECLINED;
+
+ res = core_translate_copy(r);
+ if (res == DECLINED || !r->filename) {
+ return res;
+ }
+ if (!r->filename)
+ return DECLINED;
+ tmp.filename = r->filename;
+ match = (a_file *)bsearch(&tmp, sconf->files->elts, sconf->files->nelts,
+ sizeof(a_file), file_compare);
+ if (match == NULL)
+ return DECLINED;
+
+ /* shortcircuit the get_path_info() stat() calls and stuff */
+ r->finfo = match->finfo;
+ return OK;
+}
+
+
+static int file_cache_handler(request_rec *r)
+{
+ a_server_config *sconf;
+ a_file tmp;
+ a_file *ptmp;
+ a_file **pmatch;
+ a_file *match;
+ int rangestatus, errstatus;
+
+ /* we don't handle anything but GET */
+ if (r->method_number != M_GET) return DECLINED;
+
+ /* file doesn't exist, we won't be dealing with it */
+ if (r->finfo.protection == 0) return DECLINED;
+
+ sconf = ap_get_module_config(r->server->module_config, &file_cache_module);
+#ifdef WIN32
+ tmp.filename = r->filename;
+#else
+ tmp.finfo.st_dev = r->finfo.st_dev;
+ tmp.finfo.st_ino = r->finfo.st_ino;
+#endif
+ ptmp = &tmp;
+#ifdef WIN32
+ match = (a_file *)bsearch(ptmp, sconf->files->elts,
+ sconf->files->nelts, sizeof(a_file), file_compare);
+ if (match == NULL) {
+ return DECLINED;
+ }
+#else
+ pmatch = (a_file **)bsearch(&ptmp, sconf->inode_sorted->elts,
+ sconf->inode_sorted->nelts, sizeof(a_file *), inode_compare);
+ if (pmatch == NULL) {
+ return DECLINED;
+ }
+ match = *pmatch;
+#endif
+
+ /* note that we would handle GET on this resource */
+ r->allowed |= (1 << M_GET);
+
+ /* This handler has no use for a request body (yet), but we still
+ * need to read and discard it if the client sent one.
+ */
+ if ((errstatus = ap_discard_request_body(r)) != OK)
+ return errstatus;
+
+ ap_update_mtime(r, match->finfo.mtime);
+ ap_set_last_modified(r);
+ ap_set_etag(r);
+ if (((errstatus = ap_meets_conditions(r)) != OK)
+ || (errstatus = ap_set_content_length (r, match->finfo.size))) {
+ return errstatus;
+ }
+
+ rangestatus = ap_set_byterange(r);
+ ap_send_http_header(r);
+
+ if (!r->header_only) {
+ long length = match->finfo.size;
+ ap_off_t offset = 0;
+#if 1
+ /* ap_bflush(r->connection->client->); */
+ struct iovec iov;
+ ap_hdtr_t hdtr;
+ ap_hdtr_t *phdtr = &hdtr;
+
+ /* frob the client buffer */
+ iov.iov_base = r->connection->client->outbase;
+ iov.iov_len = r->connection->client->outcnt;
+ r->connection->client->outcnt = 0;
+
+ /* initialize the ap_hdtr_t struct */
+ phdtr->headers = &iov;
+ phdtr->numheaders = 1;
+ phdtr->trailers = NULL;
+ phdtr->numtrailers = 0;
+
+ if (!rangestatus) {
+ iol_sendfile(r->connection->client->iol,
+ match->file,
+ phdtr,
+ &offset,
+ &length,
+ 0);
+ }
+ else {
+ while (ap_each_byterange(r, &offset, &length)) {
+ iol_sendfile(r->connection->client->iol,
+ match->file,
+ phdtr,
+ &offset,
+ &length,
+ 0);
+ phdtr = NULL;
+ }
+ }
+#else
+ if (!rangestatus) {
+ ap_send_mmap (match->mm, r, 0, match->finfo.st_size);
+ }
+ else {
+ while (ap_each_byterange(r, &offset, &length)) {
+ ap_send_mmap(match->mm, r, offset, length);
+ }
+ }
+#endif
+ }
+
+ return OK;
+}
+
+static command_rec mmap_cmds[] =
+{
+ {"cachefile", cachefile, NULL, RSRC_CONF, ITERATE,
+ "A space seperated list of files to mmap at config time"},
+ {NULL}
+};
+
+static void register_hooks(void)
+{
+ /* static const char* const aszPre[]={"http_core.c",NULL}; */
+ /* ap_hook_pre_config(pre_config,NULL,NULL,HOOK_MIDDLE); */
+ ap_hook_post_config(file_cache_post_config, NULL, NULL, HOOK_MIDDLE);
+ ap_hook_translate_name(file_cache_xlat, NULL, NULL, HOOK_MIDDLE);
+ /* This trick doesn't work apparently because the translate hooks
+ are single shot. If the core_hook returns OK, then our hook is
+ not called.
+ ap_hook_translate_name(file_cache_xlat, aszPre, NULL, HOOK_MIDDLE);
+ */
+
+};
+
+static const handler_rec file_cache_handlers[] =
+{
+ { "*/*", file_cache_handler },
+ { NULL }
+};
+
+module MODULE_VAR_EXPORT file_cache_module =
+{
+ STANDARD20_MODULE_STUFF,
+ NULL, /* create per-directory config structure */
+ NULL, /* merge per-directory config structures */
+ create_server_config, /* create per-server config structure */
+ NULL, /* merge per-server config structures */
+ mmap_cmds, /* command handlers */
+ file_cache_handlers, /* handlers */
+ register_hooks /* register hooks */
+};
diff --git a/modules/cache/mod_file_cache.dsp b/modules/cache/mod_file_cache.dsp
new file mode 100644
index 00000000000..f5a10bf4a61
--- /dev/null
+++ b/modules/cache/mod_file_cache.dsp
@@ -0,0 +1,99 @@
+# Microsoft Developer Studio Project File - Name="ApacheModuleFileCache" - Package Owner=<4>
+# Microsoft Developer Studio Generated Build File, Format Version 5.00
+# ** DO NOT EDIT **
+
+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102
+
+CFG=ApacheModuleFileCache - Win32 Debug
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,
+!MESSAGE use the Export Makefile command and run
+!MESSAGE
+!MESSAGE NMAKE /f "ApacheModuleFileCache.mak".
+!MESSAGE
+!MESSAGE You can specify a configuration when running NMAKE
+!MESSAGE by defining the macro CFG on the command line. For example:
+!MESSAGE
+!MESSAGE NMAKE /f "ApacheModuleFileCache.mak"\
+ CFG="ApacheModuleFileCache - Win32 Debug"
+!MESSAGE
+!MESSAGE Possible choices for configuration are:
+!MESSAGE
+!MESSAGE "ApacheModuleFileCache - Win32 Release" (based on\
+ "Win32 (x86) Dynamic-Link Library")
+!MESSAGE "ApacheModuleFileCache - Win32 Debug" (based on\
+ "Win32 (x86) Dynamic-Link Library")
+!MESSAGE
+
+# Begin Project
+# PROP Scc_ProjName ""
+# PROP Scc_LocalPath ""
+CPP=cl.exe
+MTL=midl.exe
+RSC=rc.exe
+
+!IF "$(CFG)" == "ApacheModuleFileCache - Win32 Release"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir "Release"
+# PROP BASE Intermediate_Dir "Release"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir ".\ApacheModuleFileCacheR"
+# PROP Intermediate_Dir ".\ApacheModuleFileCacheR"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c
+# ADD CPP /nologo /MT /W3 /GX /O2 /I "..\..\include" /I ".\\" /I "..\..\lib\apr\include" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "SHARED_MODULE" /FD /c
+# SUBTRACT CPP /YX
+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /o NUL /win32
+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /o NUL /win32
+# ADD BASE RSC /l 0x409 /d "NDEBUG"
+# ADD RSC /l 0x409 /d "NDEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /machine:I386
+# ADD LINK32 user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ApacheCore.lib aprlib.lib kernel32.lib /nologo /subsystem:windows /dll /map /machine:I386 /libpath:"..\..\CoreR" /libpath:"..\..\lib\apr\Release"
+
+!ELSEIF "$(CFG)" == "ApacheModuleFileCache - Win32 Debug"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 1
+# PROP BASE Output_Dir "Debug"
+# PROP BASE Intermediate_Dir "Debug"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 1
+# PROP Output_Dir ".\ApacheModuleFileCacheD"
+# PROP Intermediate_Dir ".\ApacheModuleFileCacheD"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /FD /c
+# ADD CPP /nologo /MTd /W3 /Gm /GX /Zi /Od /I "..\..\include" /I ".\\" /I "..\..\lib\apr\include" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "SHARED_MODULE" /FD /c
+# SUBTRACT CPP /YX
+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /o NUL /win32
+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /o NUL /win32
+# ADD BASE RSC /l 0x409 /d "_DEBUG"
+# ADD RSC /l 0x409 /d "_DEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /debug /machine:I386 /pdbtype:sept
+# ADD LINK32 ApacheCore.lib aprlib.lib kernel32.lib /nologo /subsystem:windows /dll /incremental:no /map /debug /machine:I386 /pdbtype:sept /libpath:"..\..\CoreD" /libpath:"..\..\lib\apr\Debug"
+
+!ENDIF
+
+# Begin Target
+
+# Name "ApacheModuleFileCache - Win32 Release"
+# Name "ApacheModuleFileCache - Win32 Debug"
+# Begin Source File
+
+SOURCE=..\..\modules\standard\mod_file_cache.c
+# End Source File
+# End Target
+# End Project
diff --git a/modules/echo/.indent.pro b/modules/echo/.indent.pro
new file mode 100644
index 00000000000..a9fbe9f9a1f
--- /dev/null
+++ b/modules/echo/.indent.pro
@@ -0,0 +1,54 @@
+-i4 -npsl -di0 -br -nce -d0 -cli0 -npcs -nfc1
+-TBUFF
+-TFILE
+-TTRANS
+-TUINT4
+-T_trans
+-Tallow_options_t
+-Tapache_sfio
+-Tarray_header
+-Tbool_int
+-Tbuf_area
+-Tbuff_struct
+-Tbuffy
+-Tcmd_how
+-Tcmd_parms
+-Tcommand_rec
+-Tcommand_struct
+-Tconn_rec
+-Tcore_dir_config
+-Tcore_server_config
+-Tdir_maker_func
+-Tevent
+-Tglobals_s
+-Thandler_func
+-Thandler_rec
+-Tjoblist_s
+-Tlisten_rec
+-Tmerger_func
+-Tmode_t
+-Tmodule
+-Tmodule_struct
+-Tmutex
+-Tn_long
+-Tother_child_rec
+-Toverrides_t
+-Tparent_score
+-Tpid_t
+-Tpiped_log
+-Tpool
+-Trequest_rec
+-Trequire_line
+-Trlim_t
+-Tscoreboard
+-Tsemaphore
+-Tserver_addr_rec
+-Tserver_rec
+-Tserver_rec_chain
+-Tshort_score
+-Ttable
+-Ttable_entry
+-Tthread
+-Tu_wide_int
+-Tvtime_t
+-Twide_int
diff --git a/modules/echo/mod_echo.c b/modules/echo/mod_echo.c
new file mode 100644
index 00000000000..210cfa708d4
--- /dev/null
+++ b/modules/echo/mod_echo.c
@@ -0,0 +1,82 @@
+#include "httpd.h"
+#include "http_config.h"
+#include "http_connection.h"
+
+API_VAR_EXPORT module echo_module;
+
+typedef struct
+ {
+ int bEnabled;
+ } EchoConfig;
+
+static void *create_echo_server_config(pool *p,server_rec *s)
+ {
+ EchoConfig *pConfig=ap_pcalloc(p,sizeof *pConfig);
+
+ pConfig->bEnabled=0;
+
+ return pConfig;
+ }
+
+static const char *echo_on(cmd_parms *cmd, void *dummy, char *arg)
+ {
+ EchoConfig *pConfig=ap_get_module_config(cmd->server->module_config,
+ &echo_module);
+ pConfig->bEnabled=1;
+
+ return NULL;
+ }
+
+static int process_echo_connection(conn_rec *c)
+ {
+ char buf[1024];
+ EchoConfig *pConfig=ap_get_module_config(c->base_server->module_config,
+ &echo_module);
+
+ if(!pConfig->bEnabled)
+ return DECLINED;
+
+ for( ; ; )
+ {
+ int w;
+ int r=ap_bread(c->client,buf,sizeof buf);
+ if(r <= 0)
+ break;
+ w=ap_bwrite(c->client,buf,r);
+ if(w != r)
+ break;
+ ap_bflush(c->client);
+ }
+ return OK;
+ }
+
+static const command_rec echo_cmds[] = {
+{ "ProtocolEcho", echo_on, NULL, RSRC_CONF, RAW_ARGS,
+ "Run an echo server on this host" },
+{ NULL }
+};
+
+static void register_hooks()
+ {
+ ap_hook_process_connection(process_echo_connection,NULL,NULL,HOOK_MIDDLE);
+ }
+
+API_VAR_EXPORT module echo_module = {
+ STANDARD20_MODULE_STUFF,
+ NULL, /* pre_command_line */
+ NULL, /* pre_config */
+ NULL, /* post_config */
+ NULL, /* open_logs */
+ NULL, /* child_init */
+ NULL, /* create per-directory config structure */
+ NULL, /* merge per-directory config structures */
+ create_echo_server_config, /* create per-server config structure */
+ NULL, /* merge per-server config structures */
+ echo_cmds, /* command table */
+ NULL, /* handlers */
+ NULL, /* check auth */
+ NULL, /* check access */
+ NULL, /* type_checker */
+ NULL, /* pre-run fixups */
+ register_hooks /* register hooks */
+};
diff --git a/modules/experimental/.cvsignore b/modules/experimental/.cvsignore
new file mode 100644
index 00000000000..8b4c6e3da42
--- /dev/null
+++ b/modules/experimental/.cvsignore
@@ -0,0 +1,3 @@
+Makefile
+*.lo
+*.so
diff --git a/modules/experimental/.indent.pro b/modules/experimental/.indent.pro
new file mode 100644
index 00000000000..a9fbe9f9a1f
--- /dev/null
+++ b/modules/experimental/.indent.pro
@@ -0,0 +1,54 @@
+-i4 -npsl -di0 -br -nce -d0 -cli0 -npcs -nfc1
+-TBUFF
+-TFILE
+-TTRANS
+-TUINT4
+-T_trans
+-Tallow_options_t
+-Tapache_sfio
+-Tarray_header
+-Tbool_int
+-Tbuf_area
+-Tbuff_struct
+-Tbuffy
+-Tcmd_how
+-Tcmd_parms
+-Tcommand_rec
+-Tcommand_struct
+-Tconn_rec
+-Tcore_dir_config
+-Tcore_server_config
+-Tdir_maker_func
+-Tevent
+-Tglobals_s
+-Thandler_func
+-Thandler_rec
+-Tjoblist_s
+-Tlisten_rec
+-Tmerger_func
+-Tmode_t
+-Tmodule
+-Tmodule_struct
+-Tmutex
+-Tn_long
+-Tother_child_rec
+-Toverrides_t
+-Tparent_score
+-Tpid_t
+-Tpiped_log
+-Tpool
+-Trequest_rec
+-Trequire_line
+-Trlim_t
+-Tscoreboard
+-Tsemaphore
+-Tserver_addr_rec
+-Tserver_rec
+-Tserver_rec_chain
+-Tshort_score
+-Ttable
+-Ttable_entry
+-Tthread
+-Tu_wide_int
+-Tvtime_t
+-Twide_int
diff --git a/modules/experimental/README b/modules/experimental/README
new file mode 100644
index 00000000000..77abc097c00
--- /dev/null
+++ b/modules/experimental/README
@@ -0,0 +1,53 @@
+README for Apache 1.2 Example Module
+[April, 1997]
+
+The files in the src/modules/example directory under the Apache
+distribution directory tree are provided as an example to those that
+wish to write modules that use the Apache API.
+
+The main file is mod_example.c, which illustrates all the different
+callback mechanisms and call syntaces. By no means does an add-on
+module need to include routines for all of the callbacks - quite the
+contrary!
+
+The example module is an actual working module. If you link it into
+your server, enable the "example-handler" handler for a location, and then
+browse to that location, you will see a display of some of the tracing
+the example module did as the various callbacks were made.
+
+To include the example module in your server, follow the steps below:
+
+ 1. Uncomment the "Module example_module" line near the bottom of
+ the src/Configuration file. If there isn't one, add it; it
+ should look like this:
+
+ Module example_module modules/example/mod_example.o
+
+ 2. Run the src/Configure script ("cd src; ./Configure"). This will
+ build the Makefile for the server itself, and update the
+ src/modules/Makefile for any additional modules you have
+ requested from beneath that subdirectory.
+
+ 3. Make the server (run "make" in the src directory).
+
+To add another module of your own:
+
+ A. mkdir src/modules/mymodule
+ B. cp src/modules/example/* src/modules/mymodule
+ C. Modify the files in the new directory
+ D. Follow steps [1] through [3] above, with appropriate changes.
+
+To activate the example module, include a block similar to the
+following in your srm.conf file:
+
+
+ SetHandler example-handler
+
+
+As an alternative, you can put the following into a .htaccess file and
+then request the file "test.example" from that location:
+
+ AddHandler example-handler .example
+
+After reloading/restarting your server, you should be able to browse
+to this location and see the brief display mentioned earlier.
diff --git a/modules/experimental/mod_example.c b/modules/experimental/mod_example.c
new file mode 100644
index 00000000000..68a6b06fe3a
--- /dev/null
+++ b/modules/experimental/mod_example.c
@@ -0,0 +1,1149 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+/*
+ * Apache example module. Provide demonstrations of how modules do things.
+ *
+ */
+
+#include "httpd.h"
+#include "http_config.h"
+#include "http_core.h"
+#include "http_log.h"
+#include "http_main.h"
+#include "http_protocol.h"
+#include "util_script.h"
+
+#include
+
+/*--------------------------------------------------------------------------*/
+/* */
+/* Data declarations. */
+/* */
+/* Here are the static cells and structure declarations private to our */
+/* module. */
+/* */
+/*--------------------------------------------------------------------------*/
+
+/*
+ * Sample configuration record. Used for both per-directory and per-server
+ * configuration data.
+ *
+ * It's perfectly reasonable to have two different structures for the two
+ * different environments. The same command handlers will be called for
+ * both, though, so the handlers need to be able to tell them apart. One
+ * possibility is for both structures to start with an int which is zero for
+ * one and 1 for the other.
+ *
+ * Note that while the per-directory and per-server configuration records are
+ * available to most of the module handlers, they should be treated as
+ * READ-ONLY by all except the command and merge handlers. Sometimes handlers
+ * are handed a record that applies to the current location by implication or
+ * inheritance, and modifying it will change the rules for other locations.
+ */
+typedef struct excfg {
+ int cmode; /* Environment to which record applies (directory,
+ * server, or combination).
+ */
+#define CONFIG_MODE_SERVER 1
+#define CONFIG_MODE_DIRECTORY 2
+#define CONFIG_MODE_COMBO 3 /* Shouldn't ever happen. */
+ int local; /* Boolean: "Example" directive declared here? */
+ int congenital; /* Boolean: did we inherit an "Example"? */
+ char *trace; /* Pointer to trace string. */
+ char *loc; /* Location to which this record applies. */
+} excfg;
+
+/*
+ * Let's set up a module-local static cell to point to the accreting callback
+ * trace. As each API callback is made to us, we'll tack on the particulars
+ * to whatever we've already recorded. To avoid massive memory bloat as
+ * directories are walked again and again, we record the routine/environment
+ * the first time (non-request context only), and ignore subsequent calls for
+ * the same routine/environment.
+ */
+static const char *trace = NULL;
+static table *static_calls_made = NULL;
+
+/*
+ * To avoid leaking memory from pools other than the per-request one, we
+ * allocate a module-private pool, and then use a sub-pool of that which gets
+ * freed each time we modify the trace. That way previous layers of trace
+ * data don't get lost.
+ */
+static pool *example_pool = NULL;
+static pool *example_subpool = NULL;
+
+/*
+ * Declare ourselves so the configuration routines can find and know us.
+ * We'll fill it in at the end of the module.
+ */
+module example_module;
+
+/*--------------------------------------------------------------------------*/
+/* */
+/* The following pseudo-prototype declarations illustrate the parameters */
+/* passed to command handlers for the different types of directive */
+/* syntax. If an argument was specified in the directive definition */
+/* (look for "command_rec" below), it's available to the command handler */
+/* via the (void *) info field in the cmd_parms argument passed to the */
+/* handler (cmd->info for the examples below). */
+/* */
+/*--------------------------------------------------------------------------*/
+
+/*
+ * Command handler for a NO_ARGS directive.
+ *
+ * static const char *handle_NO_ARGS(cmd_parms *cmd, void *mconfig);
+ */
+
+/*
+ * Command handler for a RAW_ARGS directive. The "args" argument is the text
+ * of the commandline following the directive itself.
+ *
+ * static const char *handle_RAW_ARGS(cmd_parms *cmd, void *mconfig,
+ * const char *args);
+ */
+
+/*
+ * Command handler for a FLAG directive. The single parameter is passed in
+ * "bool", which is either zero or not for Off or On respectively.
+ *
+ * static const char *handle_FLAG(cmd_parms *cmd, void *mconfig, int bool);
+ */
+
+/*
+ * Command handler for a TAKE1 directive. The single parameter is passed in
+ * "word1".
+ *
+ * static const char *handle_TAKE1(cmd_parms *cmd, void *mconfig,
+ * char *word1);
+ */
+
+/*
+ * Command handler for a TAKE2 directive. TAKE2 commands must always have
+ * exactly two arguments.
+ *
+ * static const char *handle_TAKE2(cmd_parms *cmd, void *mconfig,
+ * char *word1, char *word2);
+ */
+
+/*
+ * Command handler for a TAKE3 directive. Like TAKE2, these must have exactly
+ * three arguments, or the parser complains and doesn't bother calling us.
+ *
+ * static const char *handle_TAKE3(cmd_parms *cmd, void *mconfig,
+ * char *word1, char *word2, char *word3);
+ */
+
+/*
+ * Command handler for a TAKE12 directive. These can take either one or two
+ * arguments.
+ * - word2 is a NULL pointer if no second argument was specified.
+ *
+ * static const char *handle_TAKE12(cmd_parms *cmd, void *mconfig,
+ * char *word1, char *word2);
+ */
+
+/*
+ * Command handler for a TAKE123 directive. A TAKE123 directive can be given,
+ * as might be expected, one, two, or three arguments.
+ * - word2 is a NULL pointer if no second argument was specified.
+ * - word3 is a NULL pointer if no third argument was specified.
+ *
+ * static const char *handle_TAKE123(cmd_parms *cmd, void *mconfig,
+ * char *word1, char *word2, char *word3);
+ */
+
+/*
+ * Command handler for a TAKE13 directive. Either one or three arguments are
+ * permitted - no two-parameters-only syntax is allowed.
+ * - word2 and word3 are NULL pointers if only one argument was specified.
+ *
+ * static const char *handle_TAKE13(cmd_parms *cmd, void *mconfig,
+ * char *word1, char *word2, char *word3);
+ */
+
+/*
+ * Command handler for a TAKE23 directive. At least two and as many as three
+ * arguments must be specified.
+ * - word3 is a NULL pointer if no third argument was specified.
+ *
+ * static const char *handle_TAKE23(cmd_parms *cmd, void *mconfig,
+ * char *word1, char *word2, char *word3);
+ */
+
+/*
+ * Command handler for a ITERATE directive.
+ * - Handler is called once for each of n arguments given to the directive.
+ * - word1 points to each argument in turn.
+ *
+ * static const char *handle_ITERATE(cmd_parms *cmd, void *mconfig,
+ * char *word1);
+ */
+
+/*
+ * Command handler for a ITERATE2 directive.
+ * - Handler is called once for each of the second and subsequent arguments
+ * given to the directive.
+ * - word1 is the same for each call for a particular directive instance (the
+ * first argument).
+ * - word2 points to each of the second and subsequent arguments in turn.
+ *
+ * static const char *handle_ITERATE2(cmd_parms *cmd, void *mconfig,
+ * char *word1, char *word2);
+ */
+
+/*--------------------------------------------------------------------------*/
+/* */
+/* These routines are strictly internal to this module, and support its */
+/* operation. They are not referenced by any external portion of the */
+/* server. */
+/* */
+/*--------------------------------------------------------------------------*/
+
+/*
+ * Locate our directory configuration record for the current request.
+ */
+static excfg *our_dconfig(request_rec *r)
+{
+
+ return (excfg *) ap_get_module_config(r->per_dir_config, &example_module);
+}
+
+#if 0
+/*
+ * Locate our server configuration record for the specified server.
+ */
+static excfg *our_sconfig(server_rec *s)
+{
+
+ return (excfg *) ap_get_module_config(s->module_config, &example_module);
+}
+
+/*
+ * Likewise for our configuration record for the specified request.
+ */
+static excfg *our_rconfig(request_rec *r)
+{
+
+ return (excfg *) ap_get_module_config(r->request_config, &example_module);
+}
+#endif
+
+/*
+ * This routine sets up some module-wide cells if they haven't been already.
+ */
+static void setup_module_cells()
+{
+ /*
+ * If we haven't already allocated our module-private pool, do so now.
+ */
+ if (example_pool == NULL) {
+ example_pool = ap_make_sub_pool(NULL);
+ };
+ /*
+ * Likewise for the table of routine/environment pairs we visit outside of
+ * request context.
+ */
+ if (static_calls_made == NULL) {
+ static_calls_made = ap_make_table(example_pool, 16);
+ };
+}
+
+/*
+ * This routine is used to add a trace of a callback to the list. We're
+ * passed the server record (if available), the request record (if available),
+ * a pointer to our private configuration record (if available) for the
+ * environment to which the callback is supposed to apply, and some text. We
+ * turn this into a textual representation and add it to the tail of the list.
+ * The list can be displayed by the example_handler() routine.
+ *
+ * If the call occurs within a request context (i.e., we're passed a request
+ * record), we put the trace into the request pool and attach it to the
+ * request via the notes mechanism. Otherwise, the trace gets added
+ * to the static (non-request-specific) list.
+ *
+ * Note that the r->notes table is only for storing strings; if you need to
+ * maintain per-request data of any other type, you need to use another
+ * mechanism.
+ */
+
+#define TRACE_NOTE "example-trace"
+
+static void trace_add(server_rec *s, request_rec *r, excfg *mconfig,
+ const char *note)
+{
+
+ const char *sofar;
+ char *addon;
+ char *where;
+ pool *p;
+ const char *trace_copy;
+
+ /*
+ * Make sure our pools and tables are set up - we need 'em.
+ */
+ setup_module_cells();
+ /*
+ * Now, if we're in request-context, we use the request pool.
+ */
+ if (r != NULL) {
+ p = r->pool;
+ if ((trace_copy = ap_table_get(r->notes, TRACE_NOTE)) == NULL) {
+ trace_copy = "";
+ }
+ }
+ else {
+ /*
+ * We're not in request context, so the trace gets attached to our
+ * module-wide pool. We do the create/destroy every time we're called
+ * in non-request context; this avoids leaking memory in some of
+ * the subsequent calls that allocate memory only once (such as the
+ * key formation below).
+ *
+ * Make a new sub-pool and copy any existing trace to it. Point the
+ * trace cell at the copied value.
+ */
+ p = ap_make_sub_pool(example_pool);
+ if (trace != NULL) {
+ trace = ap_pstrdup(p, trace);
+ }
+ /*
+ * Now, if we have a sub-pool from before, nuke it and replace with
+ * the one we just allocated.
+ */
+ if (example_subpool != NULL) {
+ ap_destroy_pool(example_subpool);
+ }
+ example_subpool = p;
+ trace_copy = trace;
+ }
+ /*
+ * If we weren't passed a configuration record, we can't figure out to
+ * what location this call applies. This only happens for co-routines
+ * that don't operate in a particular directory or server context. If we
+ * got a valid record, extract the location (directory or server) to which
+ * it applies.
+ */
+ where = (mconfig != NULL) ? mconfig->loc : "nowhere";
+ where = (where != NULL) ? where : "";
+ /*
+ * Now, if we're not in request context, see if we've been called with
+ * this particular combination before. The table is allocated in the
+ * module's private pool, which doesn't get destroyed.
+ */
+ if (r == NULL) {
+ char *key;
+
+ key = ap_pstrcat(p, note, ":", where, NULL);
+ if (ap_table_get(static_calls_made, key) != NULL) {
+ /*
+ * Been here, done this.
+ */
+ return;
+ }
+ else {
+ /*
+ * First time for this combination of routine and environment -
+ * log it so we don't do it again.
+ */
+ ap_table_set(static_calls_made, key, "been here");
+ }
+ }
+ addon = ap_pstrcat(p, " - \n", "
\n", " - ",
+ note, "\n", "
\n", " - [",
+ where, "]\n", "
\n", " \n",
+ " \n", NULL);
+ sofar = (trace_copy == NULL) ? "" : trace_copy;
+ trace_copy = ap_pstrcat(p, sofar, addon, NULL);
+ if (r != NULL) {
+ ap_table_set(r->notes, TRACE_NOTE, trace_copy);
+ }
+ else {
+ trace = trace_copy;
+ }
+ /*
+ * You *could* change the following if you wanted to see the calling
+ * sequence reported in the server's error_log, but beware - almost all of
+ * these co-routines are called for every single request, and the impact
+ * on the size (and readability) of the error_log is considerable.
+ */
+#define EXAMPLE_LOG_EACH 0
+ if (EXAMPLE_LOG_EACH && (s != NULL)) {
+ ap_log_error(APLOG_MARK, APLOG_DEBUG, s, "mod_example: %s", note);
+ }
+}
+
+/*--------------------------------------------------------------------------*/
+/* We prototyped the various syntax for command handlers (routines that */
+/* are called when the configuration parser detects a directive declared */
+/* by our module) earlier. Now we actually declare a "real" routine that */
+/* will be invoked by the parser when our "real" directive is */
+/* encountered. */
+/* */
+/* If a command handler encounters a problem processing the directive, it */
+/* signals this fact by returning a non-NULL pointer to a string */
+/* describing the problem. */
+/* */
+/* The magic return value DECLINE_CMD is used to deal with directives */
+/* that might be declared by multiple modules. If the command handler */
+/* returns NULL, the directive was processed; if it returns DECLINE_CMD, */
+/* the next module (if any) that declares the directive is given a chance */
+/* at it. If it returns any other value, it's treated as the text of an */
+/* error message. */
+/*--------------------------------------------------------------------------*/
+/*
+ * Command handler for the NO_ARGS "Example" directive. All we do is mark the
+ * call in the trace log, and flag the applicability of the directive to the
+ * current location in that location's configuration record.
+ */
+static const char *cmd_example(cmd_parms *cmd, void *mconfig)
+{
+
+ excfg *cfg = (excfg *) mconfig;
+
+ /*
+ * "Example Wuz Here"
+ */
+ cfg->local = 1;
+ trace_add(cmd->server, NULL, cfg, "cmd_example()");
+ return NULL;
+}
+
+/*--------------------------------------------------------------------------*/
+/* */
+/* Now we declare our content handlers, which are invoked when the server */
+/* encounters a document which our module is supposed to have a chance to */
+/* see. (See mod_mime's SetHandler and AddHandler directives, and the */
+/* mod_info and mod_status examples, for more details.) */
+/* */
+/* Since content handlers are dumping data directly into the connexion */
+/* (using the r*() routines, such as rputs() and rprintf()) without */
+/* intervention by other parts of the server, they need to make */
+/* sure any accumulated HTTP headers are sent first. This is done by */
+/* calling send_http_header(). Otherwise, no header will be sent at all, */
+/* and the output sent to the client will actually be HTTP-uncompliant. */
+/*--------------------------------------------------------------------------*/
+/*
+ * Sample content handler. All this does is display the call list that has
+ * been built up so far.
+ *
+ * The return value instructs the caller concerning what happened and what to
+ * do next:
+ * OK ("we did our thing")
+ * DECLINED ("this isn't something with which we want to get involved")
+ * HTTP_mumble ("an error status should be reported")
+ */
+static int example_handler(request_rec *r)
+{
+
+ excfg *dcfg;
+
+ dcfg = our_dconfig(r);
+ trace_add(r->server, r, dcfg, "example_handler()");
+ /*
+ * We're about to start sending content, so we need to force the HTTP
+ * headers to be sent at this point. Otherwise, no headers will be sent
+ * at all. We can set any we like first, of course. **NOTE** Here's
+ * where you set the "Content-type" header, and you do so by putting it in
+ * r->content_type, *not* r->headers_out("Content-type"). If you don't
+ * set it, it will be filled in with the server's default type (typically
+ * "text/plain"). You *must* also ensure that r->content_type is lower
+ * case.
+ *
+ * We also need to start a timer so the server can know if the connexion
+ * is broken.
+ */
+ r->content_type = "text/html";
+ ap_soft_timeout("send example call trace", r);
+ ap_send_http_header(r);
+ /*
+ * If we're only supposed to send header information (HEAD request), we're
+ * already there.
+ */
+ if (r->header_only) {
+ ap_kill_timeout(r);
+ return OK;
+ }
+
+ /*
+ * Now send our actual output. Since we tagged this as being
+ * "text/html", we need to embed any HTML.
+ */
+ ap_rputs(DOCTYPE_HTML_3_2, r);
+ ap_rputs("\n", r);
+ ap_rputs(" \n", r);
+ ap_rputs(" mod_example Module Content-Handler Output\n", r);
+ ap_rputs(" \n", r);
+ ap_rputs(" \n", r);
+ ap_rputs(" \n", r);
+ ap_rputs(" mod_example Module Content-Handler Output\n", r);
+ ap_rputs(" \n", r);
+ ap_rputs(" \n", r);
+ ap_rprintf(r, " Apache HTTP Server version: \"%s\"\n",
+ ap_get_server_version());
+ ap_rputs(" \n", r);
+ ap_rprintf(r, " Server built: \"%s\"\n", ap_get_server_built());
+ ap_rputs(" \n", r);;
+ ap_rputs(" \n", r);
+ ap_rputs(" The format for the callback trace is:\n", r);
+ ap_rputs(" \n", r);
+ ap_rputs(" \n", r);
+ ap_rputs(" - n.<routine-name>", r);
+ ap_rputs("(<routine-data>)\n", r);
+ ap_rputs("
\n", r);
+ ap_rputs(" - [<applies-to>]\n", r);
+ ap_rputs("
\n", r);
+ ap_rputs(" \n", r);
+ ap_rputs(" \n", r);
+ ap_rputs(" The <routine-data> is supplied by\n", r);
+ ap_rputs(" the routine when it requests the trace,\n", r);
+ ap_rputs(" and the <applies-to> is extracted\n", r);
+ ap_rputs(" from the configuration record at the time of the trace.\n", r);
+ ap_rputs(" SVR() indicates a server environment\n", r);
+ ap_rputs(" (blank means the main or default server, otherwise it's\n", r);
+ ap_rputs(" the name of the VirtualHost); DIR()\n", r);
+ ap_rputs(" indicates a location in the URL or filesystem\n", r);
+ ap_rputs(" namespace.\n", r);
+ ap_rputs(" \n", r);
+ ap_rprintf(r, " Static callbacks so far:\n \n%s \n",
+ trace);
+ ap_rputs(" Request-specific callbacks so far:\n", r);
+ ap_rprintf(r, " \n%s \n", ap_table_get(r->notes, TRACE_NOTE));
+ ap_rputs(" Environment for this call:\n", r);
+ ap_rputs(" \n", r);
+ ap_rprintf(r, " - Applies-to: %s\n
\n", dcfg->loc);
+ ap_rprintf(r, " - \"Example\" directive declared here: %s\n
\n",
+ (dcfg->local ? "YES" : "NO"));
+ ap_rprintf(r, " - \"Example\" inherited: %s\n
\n",
+ (dcfg->congenital ? "YES" : "NO"));
+ ap_rputs(" \n", r);
+ ap_rputs(" \n", r);
+ ap_rputs("\n", r);
+ /*
+ * We're all done, so cancel the timeout we set. Since this is probably
+ * the end of the request we *could* assume this would be done during
+ * post-processing - but it's possible that another handler might be
+ * called and inherit our outstanding timer. Not good; to each its own.
+ */
+ ap_kill_timeout(r);
+ /*
+ * We did what we wanted to do, so tell the rest of the server we
+ * succeeded.
+ */
+ return OK;
+}
+
+/*--------------------------------------------------------------------------*/
+/* */
+/* Now let's declare routines for each of the callback phase in order. */
+/* (That's the order in which they're listed in the callback list, *not */
+/* the order in which the server calls them! See the command_rec */
+/* declaration near the bottom of this file.) Note that these may be */
+/* called for situations that don't relate primarily to our function - in */
+/* other words, the fixup handler shouldn't assume that the request has */
+/* to do with "example" stuff. */
+/* */
+/* With the exception of the content handler, all of our routines will be */
+/* called for each request, unless an earlier handler from another module */
+/* aborted the sequence. */
+/* */
+/* Handlers that are declared as "int" can return the following: */
+/* */
+/* OK Handler accepted the request and did its thing with it. */
+/* DECLINED Handler took no action. */
+/* HTTP_mumble Handler looked at request and found it wanting. */
+/* */
+/* What the server does after calling a module handler depends upon the */
+/* handler's return value. In all cases, if the handler returns */
+/* DECLINED, the server will continue to the next module with an handler */
+/* for the current phase. However, if the handler return a non-OK, */
+/* non-DECLINED status, the server aborts the request right there. If */
+/* the handler returns OK, the server's next action is phase-specific; */
+/* see the individual handler comments below for details. */
+/* */
+/*--------------------------------------------------------------------------*/
+/*
+ * This function is called during server initialisation. Any information
+ * that needs to be recorded must be in static cells, since there's no
+ * configuration record.
+ *
+ * There is no return value.
+ */
+
+/*
+ * All our module-initialiser does is add its trace to the log.
+ */
+static void example_init(server_rec *s, pool *p)
+{
+
+ char *note;
+ char *sname = s->server_hostname;
+
+ /*
+ * Set up any module cells that ought to be initialised.
+ */
+ setup_module_cells();
+ /*
+ * The arbitrary text we add to our trace entry indicates for which server
+ * we're being called.
+ */
+ sname = (sname != NULL) ? sname : "";
+ note = ap_pstrcat(p, "example_init(", sname, ")", NULL);
+ trace_add(s, NULL, NULL, note);
+}
+
+/*
+ * This function is called during server initialisation when an heavy-weight
+ * process (such as a child) is being initialised. As with the
+ * module-initialisation function, any information that needs to be recorded
+ * must be in static cells, since there's no configuration record.
+ *
+ * There is no return value.
+ */
+
+/*
+ * All our process-initialiser does is add its trace to the log.
+ */
+static void example_child_init(server_rec *s, pool *p)
+{
+
+ char *note;
+ char *sname = s->server_hostname;
+
+ /*
+ * Set up any module cells that ought to be initialised.
+ */
+ setup_module_cells();
+ /*
+ * The arbitrary text we add to our trace entry indicates for which server
+ * we're being called.
+ */
+ sname = (sname != NULL) ? sname : "";
+ note = ap_pstrcat(p, "example_child_init(", sname, ")", NULL);
+ trace_add(s, NULL, NULL, note);
+}
+
+/*
+ * This function is called when an heavy-weight process (such as a child) is
+ * being run down or destroyed. As with the child-initialisation function,
+ * any information that needs to be recorded must be in static cells, since
+ * there's no configuration record.
+ *
+ * There is no return value.
+ */
+
+/*
+ * All our process-death routine does is add its trace to the log.
+ */
+static void example_child_exit(server_rec *s, pool *p)
+{
+
+ char *note;
+ char *sname = s->server_hostname;
+
+ /*
+ * The arbitrary text we add to our trace entry indicates for which server
+ * we're being called.
+ */
+ sname = (sname != NULL) ? sname : "";
+ note = ap_pstrcat(p, "example_child_exit(", sname, ")", NULL);
+ trace_add(s, NULL, NULL, note);
+}
+
+/*
+ * This function gets called to create up a per-directory configuration
+ * record. This will be called for the "default" server environment, and for
+ * each directory for which the parser finds any of our directives applicable.
+ * If a directory doesn't have any of our directives involved (i.e., they
+ * aren't in the .htaccess file, or a , , or related
+ * block), this routine will *not* be called - the configuration for the
+ * closest ancestor is used.
+ *
+ * The return value is a pointer to the created module-specific
+ * structure.
+ */
+static void *example_create_dir_config(pool *p, char *dirspec)
+{
+
+ excfg *cfg;
+ char *dname = dirspec;
+
+ /*
+ * Allocate the space for our record from the pool supplied.
+ */
+ cfg = (excfg *) ap_pcalloc(p, sizeof(excfg));
+ /*
+ * Now fill in the defaults. If there are any `parent' configuration
+ * records, they'll get merged as part of a separate callback.
+ */
+ cfg->local = 0;
+ cfg->congenital = 0;
+ cfg->cmode = CONFIG_MODE_DIRECTORY;
+ /*
+ * Finally, add our trace to the callback list.
+ */
+ dname = (dname != NULL) ? dname : "";
+ cfg->loc = ap_pstrcat(p, "DIR(", dname, ")", NULL);
+ trace_add(NULL, NULL, cfg, "example_create_dir_config()");
+ return (void *) cfg;
+}
+
+/*
+ * This function gets called to merge two per-directory configuration
+ * records. This is typically done to cope with things like .htaccess files
+ * or directives for directories that are beneath one for which a
+ * configuration record was already created. The routine has the
+ * responsibility of creating a new record and merging the contents of the
+ * other two into it appropriately. If the module doesn't declare a merge
+ * routine, the record for the closest ancestor location (that has one) is
+ * used exclusively.
+ *
+ * The routine MUST NOT modify any of its arguments!
+ *
+ * The return value is a pointer to the created module-specific structure
+ * containing the merged values.
+ */
+static void *example_merge_dir_config(pool *p, void *parent_conf,
+ void *newloc_conf)
+{
+
+ excfg *merged_config = (excfg *) ap_pcalloc(p, sizeof(excfg));
+ excfg *pconf = (excfg *) parent_conf;
+ excfg *nconf = (excfg *) newloc_conf;
+ char *note;
+
+ /*
+ * Some things get copied directly from the more-specific record, rather
+ * than getting merged.
+ */
+ merged_config->local = nconf->local;
+ merged_config->loc = ap_pstrdup(p, nconf->loc);
+ /*
+ * Others, like the setting of the `congenital' flag, get ORed in. The
+ * setting of that particular flag, for instance, is TRUE if it was ever
+ * true anywhere in the upstream configuration.
+ */
+ merged_config->congenital = (pconf->congenital | pconf->local);
+ /*
+ * If we're merging records for two different types of environment (server
+ * and directory), mark the new record appropriately. Otherwise, inherit
+ * the current value.
+ */
+ merged_config->cmode =
+ (pconf->cmode == nconf->cmode) ? pconf->cmode : CONFIG_MODE_COMBO;
+ /*
+ * Now just record our being called in the trace list. Include the
+ * locations we were asked to merge.
+ */
+ note = ap_pstrcat(p, "example_merge_dir_config(\"", pconf->loc, "\",\"",
+ nconf->loc, "\")", NULL);
+ trace_add(NULL, NULL, merged_config, note);
+ return (void *) merged_config;
+}
+
+/*
+ * This function gets called to create a per-server configuration
+ * record. It will always be called for the "default" server.
+ *
+ * The return value is a pointer to the created module-specific
+ * structure.
+ */
+static void *example_create_server_config(pool *p, server_rec *s)
+{
+
+ excfg *cfg;
+ char *sname = s->server_hostname;
+
+ /*
+ * As with the example_create_dir_config() reoutine, we allocate and fill
+ * in an empty record.
+ */
+ cfg = (excfg *) ap_pcalloc(p, sizeof(excfg));
+ cfg->local = 0;
+ cfg->congenital = 0;
+ cfg->cmode = CONFIG_MODE_SERVER;
+ /*
+ * Note that we were called in the trace list.
+ */
+ sname = (sname != NULL) ? sname : "";
+ cfg->loc = ap_pstrcat(p, "SVR(", sname, ")", NULL);
+ trace_add(s, NULL, cfg, "example_create_server_config()");
+ return (void *) cfg;
+}
+
+/*
+ * This function gets called to merge two per-server configuration
+ * records. This is typically done to cope with things like virtual hosts and
+ * the default server configuration The routine has the responsibility of
+ * creating a new record and merging the contents of the other two into it
+ * appropriately. If the module doesn't declare a merge routine, the more
+ * specific existing record is used exclusively.
+ *
+ * The routine MUST NOT modify any of its arguments!
+ *
+ * The return value is a pointer to the created module-specific structure
+ * containing the merged values.
+ */
+static void *example_merge_server_config(pool *p, void *server1_conf,
+ void *server2_conf)
+{
+
+ excfg *merged_config = (excfg *) ap_pcalloc(p, sizeof(excfg));
+ excfg *s1conf = (excfg *) server1_conf;
+ excfg *s2conf = (excfg *) server2_conf;
+ char *note;
+
+ /*
+ * Our inheritance rules are our own, and part of our module's semantics.
+ * Basically, just note whence we came.
+ */
+ merged_config->cmode =
+ (s1conf->cmode == s2conf->cmode) ? s1conf->cmode : CONFIG_MODE_COMBO;
+ merged_config->local = s2conf->local;
+ merged_config->congenital = (s1conf->congenital | s1conf->local);
+ merged_config->loc = ap_pstrdup(p, s2conf->loc);
+ /*
+ * Trace our call, including what we were asked to merge.
+ */
+ note = ap_pstrcat(p, "example_merge_server_config(\"", s1conf->loc, "\",\"",
+ s2conf->loc, "\")", NULL);
+ trace_add(NULL, NULL, merged_config, note);
+ return (void *) merged_config;
+}
+
+/*
+ * This routine is called after the request has been read but before any other
+ * phases have been processed. This allows us to make decisions based upon
+ * the input header fields.
+ *
+ * The return value is OK, DECLINED, or HTTP_mumble. If we return OK, no
+ * further modules are called for this phase.
+ */
+static int example_post_read_request(request_rec *r)
+{
+
+ excfg *cfg;
+
+ cfg = our_dconfig(r);
+ /*
+ * We don't actually *do* anything here, except note the fact that we were
+ * called.
+ */
+ trace_add(r->server, r, cfg, "example_post_read_request()");
+ return DECLINED;
+}
+
+/*
+ * This routine gives our module an opportunity to translate the URI into an
+ * actual filename. If we don't do anything special, the server's default
+ * rules (Alias directives and the like) will continue to be followed.
+ *
+ * The return value is OK, DECLINED, or HTTP_mumble. If we return OK, no
+ * further modules are called for this phase.
+ */
+static int example_translate_handler(request_rec *r)
+{
+
+ excfg *cfg;
+
+ cfg = our_dconfig(r);
+ /*
+ * We don't actually *do* anything here, except note the fact that we were
+ * called.
+ */
+ trace_add(r->server, r, cfg, "example_translate_handler()");
+ return DECLINED;
+}
+
+/*
+ * This routine is called to check the authentication information sent with
+ * the request (such as looking up the user in a database and verifying that
+ * the [encrypted] password sent matches the one in the database).
+ *
+ * The return value is OK, DECLINED, or some HTTP_mumble error (typically
+ * HTTP_UNAUTHORIZED). If we return OK, no other modules are given a chance
+ * at the request during this phase.
+ */
+static int example_check_user_id(request_rec *r)
+{
+
+ excfg *cfg;
+
+ cfg = our_dconfig(r);
+ /*
+ * Don't do anything except log the call.
+ */
+ trace_add(r->server, r, cfg, "example_check_user_id()");
+ return DECLINED;
+}
+
+/*
+ * This routine is called to check to see if the resource being requested
+ * requires authorisation.
+ *
+ * The return value is OK, DECLINED, or HTTP_mumble. If we return OK, no
+ * other modules are called during this phase.
+ *
+ * If *all* modules return DECLINED, the request is aborted with a server
+ * error.
+ */
+static int example_auth_checker(request_rec *r)
+{
+
+ excfg *cfg;
+
+ cfg = our_dconfig(r);
+ /*
+ * Log the call and return OK, or access will be denied (even though we
+ * didn't actually do anything).
+ */
+ trace_add(r->server, r, cfg, "example_auth_checker()");
+ return DECLINED;
+}
+
+/*
+ * This routine is called to check for any module-specific restrictions placed
+ * upon the requested resource. (See the mod_access module for an example.)
+ *
+ * The return value is OK, DECLINED, or HTTP_mumble. All modules with an
+ * handler for this phase are called regardless of whether their predecessors
+ * return OK or DECLINED. The first one to return any other status, however,
+ * will abort the sequence (and the request) as usual.
+ */
+static int example_access_checker(request_rec *r)
+{
+
+ excfg *cfg;
+
+ cfg = our_dconfig(r);
+ trace_add(r->server, r, cfg, "example_access_checker()");
+ return DECLINED;
+}
+
+/*
+ * This routine is called to determine and/or set the various document type
+ * information bits, like Content-type (via r->content_type), language, et
+ * cetera.
+ *
+ * The return value is OK, DECLINED, or HTTP_mumble. If we return OK, no
+ * further modules are given a chance at the request for this phase.
+ */
+static int example_type_checker(request_rec *r)
+{
+
+ excfg *cfg;
+
+ cfg = our_dconfig(r);
+ /*
+ * Log the call, but don't do anything else - and report truthfully that
+ * we didn't do anything.
+ */
+ trace_add(r->server, r, cfg, "example_type_checker()");
+ return DECLINED;
+}
+
+/*
+ * This routine is called to perform any module-specific fixing of header
+ * fields, et cetera. It is invoked just before any content-handler.
+ *
+ * The return value is OK, DECLINED, or HTTP_mumble. If we return OK, the
+ * server will still call any remaining modules with an handler for this
+ * phase.
+ */
+static int example_fixer_upper(request_rec *r)
+{
+
+ excfg *cfg;
+
+ cfg = our_dconfig(r);
+ /*
+ * Log the call and exit.
+ */
+ trace_add(r->server, r, cfg, "example_fixer_upper()");
+ return OK;
+}
+
+/*
+ * This routine is called to perform any module-specific logging activities
+ * over and above the normal server things.
+ *
+ * The return value is OK, DECLINED, or HTTP_mumble. If we return OK, any
+ * remaining modules with an handler for this phase will still be called.
+ */
+static int example_logger(request_rec *r)
+{
+
+ excfg *cfg;
+
+ cfg = our_dconfig(r);
+ trace_add(r->server, r, cfg, "example_logger()");
+ return DECLINED;
+}
+
+/*
+ * This routine is called to give the module a chance to look at the request
+ * headers and take any appropriate specific actions early in the processing
+ * sequence.
+ *
+ * The return value is OK, DECLINED, or HTTP_mumble. If we return OK, any
+ * remaining modules with handlers for this phase will still be called.
+ */
+static int example_header_parser(request_rec *r)
+{
+
+ excfg *cfg;
+
+ cfg = our_dconfig(r);
+ trace_add(r->server, r, cfg, "example_header_parser()");
+ return DECLINED;
+}
+
+/*--------------------------------------------------------------------------*/
+/* */
+/* All of the routines have been declared now. Here's the list of */
+/* directives specific to our module, and information about where they */
+/* may appear and how the command parser should pass them to us for */
+/* processing. Note that care must be taken to ensure that there are NO */
+/* collisions of directive names between modules. */
+/* */
+/*--------------------------------------------------------------------------*/
+/*
+ * List of directives specific to our module.
+ */
+static const command_rec example_cmds[] =
+{
+ {
+ "Example", /* directive name */
+ cmd_example, /* config action routine */
+ NULL, /* argument to include in call */
+ OR_OPTIONS, /* where available */
+ NO_ARGS, /* arguments */
+ "Example directive - no arguments"
+ /* directive description */
+ },
+ {NULL}
+};
+
+/*--------------------------------------------------------------------------*/
+/* */
+/* Now the list of content handlers available from this module. */
+/* */
+/*--------------------------------------------------------------------------*/
+/*
+ * List of content handlers our module supplies. Each handler is defined by
+ * two parts: a name by which it can be referenced (such as by
+ * {Add,Set}Handler), and the actual routine name. The list is terminated by
+ * a NULL block, since it can be of variable length.
+ *
+ * Note that content-handlers are invoked on a most-specific to least-specific
+ * basis; that is, a handler that is declared for "text/plain" will be
+ * invoked before one that was declared for "text / *". Note also that
+ * if a content-handler returns anything except DECLINED, no other
+ * content-handlers will be called.
+ */
+static const handler_rec example_handlers[] =
+{
+ {"example-handler", example_handler},
+ {NULL}
+};
+
+/*--------------------------------------------------------------------------*/
+/* */
+/* Finally, the list of callback routines and data structures that */
+/* provide the hooks into our module from the other parts of the server. */
+/* */
+/*--------------------------------------------------------------------------*/
+/*
+ * Module definition for configuration. If a particular callback is not
+ * needed, replace its routine name below with the word NULL.
+ *
+ * The number in brackets indicates the order in which the routine is called
+ * during request processing. Note that not all routines are necessarily
+ * called (such as if a resource doesn't have access restrictions).
+ */
+module example_module =
+{
+ STANDARD_MODULE_STUFF,
+ example_init, /* module initializer */
+ example_create_dir_config, /* per-directory config creator */
+ example_merge_dir_config, /* dir config merger */
+ example_create_server_config, /* server config creator */
+ example_merge_server_config, /* server config merger */
+ example_cmds, /* command table */
+ example_handlers, /* [7] list of handlers */
+ example_translate_handler, /* [2] filename-to-URI translation */
+ example_check_user_id, /* [5] check/validate user_id */
+ example_auth_checker, /* [6] check user_id is valid *here* */
+ example_access_checker, /* [4] check access by host address */
+ example_type_checker, /* [7] MIME type checker/setter */
+ example_fixer_upper, /* [8] fixups */
+ example_logger, /* [10] logger */
+#if MODULE_MAGIC_NUMBER >= 19970103
+ example_header_parser, /* [3] header parser */
+#endif
+#if MODULE_MAGIC_NUMBER >= 19970719
+ example_child_init, /* process initializer */
+#endif
+#if MODULE_MAGIC_NUMBER >= 19970728
+ example_child_exit, /* process exit/cleanup */
+#endif
+#if MODULE_MAGIC_NUMBER >= 19970902
+ example_post_read_request /* [1] post read_request handling */
+#endif
+};
diff --git a/modules/filters/.indent.pro b/modules/filters/.indent.pro
new file mode 100644
index 00000000000..a9fbe9f9a1f
--- /dev/null
+++ b/modules/filters/.indent.pro
@@ -0,0 +1,54 @@
+-i4 -npsl -di0 -br -nce -d0 -cli0 -npcs -nfc1
+-TBUFF
+-TFILE
+-TTRANS
+-TUINT4
+-T_trans
+-Tallow_options_t
+-Tapache_sfio
+-Tarray_header
+-Tbool_int
+-Tbuf_area
+-Tbuff_struct
+-Tbuffy
+-Tcmd_how
+-Tcmd_parms
+-Tcommand_rec
+-Tcommand_struct
+-Tconn_rec
+-Tcore_dir_config
+-Tcore_server_config
+-Tdir_maker_func
+-Tevent
+-Tglobals_s
+-Thandler_func
+-Thandler_rec
+-Tjoblist_s
+-Tlisten_rec
+-Tmerger_func
+-Tmode_t
+-Tmodule
+-Tmodule_struct
+-Tmutex
+-Tn_long
+-Tother_child_rec
+-Toverrides_t
+-Tparent_score
+-Tpid_t
+-Tpiped_log
+-Tpool
+-Trequest_rec
+-Trequire_line
+-Trlim_t
+-Tscoreboard
+-Tsemaphore
+-Tserver_addr_rec
+-Tserver_rec
+-Tserver_rec_chain
+-Tshort_score
+-Ttable
+-Ttable_entry
+-Tthread
+-Tu_wide_int
+-Tvtime_t
+-Twide_int
diff --git a/modules/filters/mod_include.c b/modules/filters/mod_include.c
new file mode 100644
index 00000000000..3ee96db83b5
--- /dev/null
+++ b/modules/filters/mod_include.c
@@ -0,0 +1,2486 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+/*
+ * http_include.c: Handles the server-parsed HTML documents
+ *
+ * Original by Rob McCool; substantial fixups by David Robinson;
+ * incorporated into the Apache module framework by rst.
+ *
+ */
+/*
+ * sub key may be anything a Perl*Handler can be:
+ * subroutine name, package name (defaults to package::handler),
+ * Class->method call or anoymous sub {}
+ *
+ * Child accessed
+ * times.
+ *
+ *
+ *
+ * -Doug MacEachern
+ */
+
+#ifdef USE_PERL_SSI
+#include "config.h"
+#undef VOIDUSED
+#ifdef USE_SFIO
+#undef USE_SFIO
+#define USE_STDIO
+#endif
+#include "modules/perl/mod_perl.h"
+#else
+#include "httpd.h"
+#include "http_config.h"
+#include "http_request.h"
+#include "http_core.h"
+#include "http_protocol.h"
+#include "http_log.h"
+#include "http_main.h"
+#include "util_script.h"
+#endif
+
+#define STARTING_SEQUENCE ""
+#define DEFAULT_ERROR_MSG "[an error occurred while processing this directive]"
+#define DEFAULT_TIME_FORMAT "%A, %d-%b-%Y %H:%M:%S %Z"
+#define SIZEFMT_BYTES 0
+#define SIZEFMT_KMG 1
+#ifdef CHARSET_EBCDIC
+#define RAW_ASCII_CHAR(ch) os_toebcdic[(unsigned char)ch]
+#else /*CHARSET_EBCDIC*/
+#define RAW_ASCII_CHAR(ch) (ch)
+#endif /*CHARSET_EBCDIC*/
+
+module MODULE_VAR_EXPORT includes_module;
+
+/* just need some arbitrary non-NULL pointer which can't also be a request_rec */
+#define NESTED_INCLUDE_MAGIC (&includes_module)
+
+/* ------------------------ Environment function -------------------------- */
+
+/* XXX: could use ap_table_overlap here */
+static void add_include_vars(request_rec *r, char *timefmt)
+{
+#ifndef WIN32
+ struct passwd *pw;
+#endif /* ndef WIN32 */
+ table *e = r->subprocess_env;
+ char *t;
+ time_t date = r->request_time;
+
+ ap_table_setn(e, "DATE_LOCAL", ap_ht_time(r->pool, date, timefmt, 0));
+ ap_table_setn(e, "DATE_GMT", ap_ht_time(r->pool, date, timefmt, 1));
+ ap_table_setn(e, "LAST_MODIFIED",
+ ap_ht_time(r->pool, r->finfo.st_mtime, timefmt, 0));
+ ap_table_setn(e, "DOCUMENT_URI", r->uri);
+ ap_table_setn(e, "DOCUMENT_PATH_INFO", r->path_info);
+#ifndef WIN32
+ pw = getpwuid(r->finfo.st_uid);
+ if (pw) {
+ ap_table_setn(e, "USER_NAME", ap_pstrdup(r->pool, pw->pw_name));
+ }
+ else {
+ ap_table_setn(e, "USER_NAME", ap_psprintf(r->pool, "user#%lu",
+ (unsigned long) r->finfo.st_uid));
+ }
+#endif /* ndef WIN32 */
+
+ if ((t = strrchr(r->filename, '/'))) {
+ ap_table_setn(e, "DOCUMENT_NAME", ++t);
+ }
+ else {
+ ap_table_setn(e, "DOCUMENT_NAME", r->uri);
+ }
+ if (r->args) {
+ char *arg_copy = ap_pstrdup(r->pool, r->args);
+
+ ap_unescape_url(arg_copy);
+ ap_table_setn(e, "QUERY_STRING_UNESCAPED",
+ ap_escape_shell_cmd(r->pool, arg_copy));
+ }
+}
+
+
+
+/* --------------------------- Parser functions --------------------------- */
+
+#define OUTBUFSIZE 4096
+/* PUT_CHAR and FLUSH_BUF currently only work within the scope of
+ * find_string(); they are hacks to avoid calling rputc for each and
+ * every character output. A common set of buffering calls for this
+ * type of output SHOULD be implemented.
+ */
+#define PUT_CHAR(c,r) \
+ { \
+ outbuf[outind++] = c; \
+ if (outind == OUTBUFSIZE) { \
+ FLUSH_BUF(r) \
+ }; \
+ }
+
+/* there SHOULD be some error checking on the return value of
+ * rwrite, however it is unclear what the API for rwrite returning
+ * errors is and little can really be done to help the error in
+ * any case.
+ */
+#define FLUSH_BUF(r) \
+ { \
+ ap_rwrite(outbuf, outind, r); \
+ outind = 0; \
+ }
+
+/*
+ * f: file handle being read from
+ * c: character to read into
+ * ret: return value to use if input fails
+ * r: current request_rec
+ *
+ * This macro is redefined after find_string() for historical reasons
+ * to avoid too many code changes. This is one of the many things
+ * that should be fixed.
+ */
+#define GET_CHAR(f,c,ret,r) \
+ { \
+ int i = getc(f); \
+ if (i == EOF) { /* either EOF or error -- needs error handling if latter */ \
+ if (ferror(f)) { \
+ fprintf(stderr, "encountered error in GET_CHAR macro, " \
+ "mod_include.\n"); \
+ } \
+ FLUSH_BUF(r); \
+ ap_pfclose(r->pool, f); \
+ return ret; \
+ } \
+ c = (char)i; \
+ }
+
+static int find_string(FILE *in, const char *str, request_rec *r, int printing)
+{
+ int x, l = strlen(str), p;
+ char outbuf[OUTBUFSIZE];
+ int outind = 0;
+ char c;
+
+ p = 0;
+ while (1) {
+ GET_CHAR(in, c, 1, r);
+ if (c == str[p]) {
+ if ((++p) == l) {
+ FLUSH_BUF(r);
+ return 0;
+ }
+ }
+ else {
+ if (printing) {
+ for (x = 0; x < p; x++) {
+ PUT_CHAR(str[x], r);
+ }
+ PUT_CHAR(c, r);
+ }
+ p = 0;
+ }
+ }
+}
+
+#undef FLUSH_BUF
+#undef PUT_CHAR
+#undef GET_CHAR
+#define GET_CHAR(f,c,r,p) \
+ { \
+ int i = getc(f); \
+ if (i == EOF) { /* either EOF or error -- needs error handling if latter */ \
+ if (ferror(f)) { \
+ fprintf(stderr, "encountered error in GET_CHAR macro, " \
+ "mod_include.\n"); \
+ } \
+ ap_pfclose(p, f); \
+ return r; \
+ } \
+ c = (char)i; \
+ }
+
+/*
+ * decodes a string containing html entities or numeric character references.
+ * 's' is overwritten with the decoded string.
+ * If 's' is syntatically incorrect, then the followed fixups will be made:
+ * unknown entities will be left undecoded;
+ * references to unused numeric characters will be deleted.
+ * In particular, will not be decoded, but will be deleted.
+ *
+ * drtr
+ */
+
+/* maximum length of any ISO-LATIN-1 HTML entity name. */
+#define MAXENTLEN (6)
+
+/* The following is a shrinking transformation, therefore safe. */
+
+static void decodehtml(char *s)
+{
+ int val, i, j;
+ char *p = s;
+ const char *ents;
+ static const char * const entlist[MAXENTLEN + 1] =
+ {
+ NULL, /* 0 */
+ NULL, /* 1 */
+ "lt\074gt\076", /* 2 */
+ "amp\046ETH\320eth\360", /* 3 */
+ "quot\042Auml\304Euml\313Iuml\317Ouml\326Uuml\334auml\344euml\353\
+iuml\357ouml\366uuml\374yuml\377", /* 4 */
+ "Acirc\302Aring\305AElig\306Ecirc\312Icirc\316Ocirc\324Ucirc\333\
+THORN\336szlig\337acirc\342aring\345aelig\346ecirc\352icirc\356ocirc\364\
+ucirc\373thorn\376", /* 5 */
+ "Agrave\300Aacute\301Atilde\303Ccedil\307Egrave\310Eacute\311\
+Igrave\314Iacute\315Ntilde\321Ograve\322Oacute\323Otilde\325Oslash\330\
+Ugrave\331Uacute\332Yacute\335agrave\340aacute\341atilde\343ccedil\347\
+egrave\350eacute\351igrave\354iacute\355ntilde\361ograve\362oacute\363\
+otilde\365oslash\370ugrave\371uacute\372yacute\375" /* 6 */
+ };
+
+ for (; *s != '\0'; s++, p++) {
+ if (*s != '&') {
+ *p = *s;
+ continue;
+ }
+ /* find end of entity */
+ for (i = 1; s[i] != ';' && s[i] != '\0'; i++) {
+ continue;
+ }
+
+ if (s[i] == '\0') { /* treat as normal data */
+ *p = *s;
+ continue;
+ }
+
+ /* is it numeric ? */
+ if (s[1] == '#') {
+ for (j = 2, val = 0; j < i && ap_isdigit(s[j]); j++) {
+ val = val * 10 + s[j] - '0';
+ }
+ s += i;
+ if (j < i || val <= 8 || (val >= 11 && val <= 31) ||
+ (val >= 127 && val <= 160) || val >= 256) {
+ p--; /* no data to output */
+ }
+ else {
+ *p = RAW_ASCII_CHAR(val);
+ }
+ }
+ else {
+ j = i - 1;
+ if (j > MAXENTLEN || entlist[j] == NULL) {
+ /* wrong length */
+ *p = '&';
+ continue; /* skip it */
+ }
+ for (ents = entlist[j]; *ents != '\0'; ents += i) {
+ if (strncmp(s + 1, ents, j) == 0) {
+ break;
+ }
+ }
+
+ if (*ents == '\0') {
+ *p = '&'; /* unknown */
+ }
+ else {
+ *p = RAW_ASCII_CHAR(((const unsigned char *) ents)[j]);
+ s += i;
+ }
+ }
+ }
+
+ *p = '\0';
+}
+
+/*
+ * extract the next tag name and value.
+ * if there are no more tags, set the tag name to 'done'
+ * the tag value is html decoded if dodecode is non-zero
+ */
+
+static char *get_tag(pool *p, FILE *in, char *tag, int tagbuf_len, int dodecode)
+{
+ char *t = tag, *tag_val, c, term;
+
+ /* makes code below a little less cluttered */
+ --tagbuf_len;
+
+ do { /* skip whitespace */
+ GET_CHAR(in, c, NULL, p);
+ } while (ap_isspace(c));
+
+ /* tags can't start with - */
+ if (c == '-') {
+ GET_CHAR(in, c, NULL, p);
+ if (c == '-') {
+ do {
+ GET_CHAR(in, c, NULL, p);
+ } while (ap_isspace(c));
+ if (c == '>') {
+ ap_cpystrn(tag, "done", tagbuf_len);
+ return tag;
+ }
+ }
+ return NULL; /* failed */
+ }
+
+ /* find end of tag name */
+ while (1) {
+ if (t - tag == tagbuf_len) {
+ *t = '\0';
+ return NULL;
+ }
+ if (c == '=' || ap_isspace(c)) {
+ break;
+ }
+ *(t++) = ap_tolower(c);
+ GET_CHAR(in, c, NULL, p);
+ }
+
+ *t++ = '\0';
+ tag_val = t;
+
+ while (ap_isspace(c)) {
+ GET_CHAR(in, c, NULL, p); /* space before = */
+ }
+ if (c != '=') {
+ ungetc(c, in);
+ return NULL;
+ }
+
+ do {
+ GET_CHAR(in, c, NULL, p); /* space after = */
+ } while (ap_isspace(c));
+
+ /* we should allow a 'name' as a value */
+
+ if (c != '"' && c != '\'') {
+ return NULL;
+ }
+ term = c;
+ while (1) {
+ GET_CHAR(in, c, NULL, p);
+ if (t - tag == tagbuf_len) {
+ *t = '\0';
+ return NULL;
+ }
+/* Want to accept \" as a valid character within a string. */
+ if (c == '\\') {
+ *(t++) = c; /* Add backslash */
+ GET_CHAR(in, c, NULL, p);
+ if (c == term) { /* Only if */
+ *(--t) = c; /* Replace backslash ONLY for terminator */
+ }
+ }
+ else if (c == term) {
+ break;
+ }
+ *(t++) = c;
+ }
+ *t = '\0';
+ if (dodecode) {
+ decodehtml(tag_val);
+ }
+ return ap_pstrdup(p, tag_val);
+}
+
+static int get_directive(FILE *in, char *dest, size_t len, pool *p)
+{
+ char *d = dest;
+ char c;
+
+ /* make room for nul terminator */
+ --len;
+
+ /* skip initial whitespace */
+ while (1) {
+ GET_CHAR(in, c, 1, p);
+ if (!ap_isspace(c)) {
+ break;
+ }
+ }
+ /* now get directive */
+ while (1) {
+ if (d - dest == len) {
+ return 1;
+ }
+ *d++ = ap_tolower(c);
+ GET_CHAR(in, c, 1, p);
+ if (ap_isspace(c)) {
+ break;
+ }
+ }
+ *d = '\0';
+ return 0;
+}
+
+/*
+ * Do variable substitution on strings
+ */
+static void parse_string(request_rec *r, const char *in, char *out,
+ size_t length, int leave_name)
+{
+ char ch;
+ char *next = out;
+ char *end_out;
+
+ /* leave room for nul terminator */
+ end_out = out + length - 1;
+
+ while ((ch = *in++) != '\0') {
+ switch (ch) {
+ case '\\':
+ if (next == end_out) {
+ /* truncated */
+ *next = '\0';
+ return;
+ }
+ if (*in == '$') {
+ *next++ = *in++;
+ }
+ else {
+ *next++ = ch;
+ }
+ break;
+ case '$':
+ {
+ char var[MAX_STRING_LEN];
+ const char *start_of_var_name;
+ const char *end_of_var_name; /* end of var name + 1 */
+ const char *expansion;
+ const char *val;
+ size_t l;
+
+ /* guess that the expansion won't happen */
+ expansion = in - 1;
+ if (*in == '{') {
+ ++in;
+ start_of_var_name = in;
+ in = strchr(in, '}');
+ if (in == NULL) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR,
+ r, "Missing '}' on variable \"%s\"",
+ expansion);
+ *next = '\0';
+ return;
+ }
+ end_of_var_name = in;
+ ++in;
+ }
+ else {
+ start_of_var_name = in;
+ while (ap_isalnum(*in) || *in == '_') {
+ ++in;
+ }
+ end_of_var_name = in;
+ }
+ /* what a pain, too bad there's no table_getn where you can
+ * pass a non-nul terminated string */
+ l = end_of_var_name - start_of_var_name;
+ if (l != 0) {
+ l = (l > sizeof(var) - 1) ? (sizeof(var) - 1) : l;
+ memcpy(var, start_of_var_name, l);
+ var[l] = '\0';
+
+ val = ap_table_get(r->subprocess_env, var);
+ if (val) {
+ expansion = val;
+ l = strlen(expansion);
+ }
+ else if (leave_name) {
+ l = in - expansion;
+ }
+ else {
+ break; /* no expansion to be done */
+ }
+ }
+ else {
+ /* zero-length variable name causes just the $ to be copied */
+ l = 1;
+ }
+ l = (l > end_out - next) ? (end_out - next) : l;
+ memcpy(next, expansion, l);
+ next += l;
+ break;
+ }
+ default:
+ if (next == end_out) {
+ /* truncated */
+ *next = '\0';
+ return;
+ }
+ *next++ = ch;
+ break;
+ }
+ }
+ *next = '\0';
+ return;
+}
+
+/* --------------------------- Action handlers ---------------------------- */
+
+static int include_cgi(char *s, request_rec *r)
+{
+ request_rec *rr = ap_sub_req_lookup_uri(s, r);
+ int rr_status;
+
+ if (rr->status != HTTP_OK) {
+ return -1;
+ }
+
+ /* No hardwired path info or query allowed */
+
+ if ((rr->path_info && rr->path_info[0]) || rr->args) {
+ return -1;
+ }
+ if (rr->finfo.st_mode == 0) {
+ return -1;
+ }
+
+ /* Script gets parameters of the *document*, for back compatibility */
+
+ rr->path_info = r->path_info; /* hard to get right; see mod_cgi.c */
+ rr->args = r->args;
+
+ /* Force sub_req to be treated as a CGI request, even if ordinary
+ * typing rules would have called it something else.
+ */
+
+ rr->content_type = CGI_MAGIC_TYPE;
+
+ /* Run it. */
+
+ rr_status = ap_run_sub_req(rr);
+ if (ap_is_HTTP_REDIRECT(rr_status)) {
+ const char *location = ap_table_get(rr->headers_out, "Location");
+ location = ap_escape_html(rr->pool, location);
+ ap_rvputs(r, "", location, "", NULL);
+ }
+
+ ap_destroy_sub_req(rr);
+#ifndef WIN32
+ ap_chdir_file(r->filename);
+#endif
+
+ return 0;
+}
+
+/* ensure that path is relative, and does not contain ".." elements
+ * ensentially ensure that it does not match the regex:
+ * (^/|(^|/)\.\.(/|$))
+ * XXX: this needs os abstraction... consider c:..\foo in win32
+ */
+static int is_only_below(const char *path)
+{
+#ifdef HAVE_DRIVE_LETTERS
+ if (path[1] == ':')
+ return 0;
+#endif
+ if (path[0] == '/') {
+ return 0;
+ }
+ if (path[0] == '.' && path[1] == '.'
+ && (path[2] == '\0' || path[2] == '/')) {
+ return 0;
+ }
+ while (*path) {
+ if (*path == '/' && path[1] == '.' && path[2] == '.'
+ && (path[3] == '\0' || path[3] == '/')) {
+ return 0;
+ }
+ ++path;
+ }
+ return 1;
+}
+
+static int handle_include(FILE *in, request_rec *r, const char *error, int noexec)
+{
+ char tag[MAX_STRING_LEN];
+ char parsed_string[MAX_STRING_LEN];
+ char *tag_val;
+
+ while (1) {
+ if (!(tag_val = get_tag(r->pool, in, tag, sizeof(tag), 1))) {
+ return 1;
+ }
+ if (!strcmp(tag, "file") || !strcmp(tag, "virtual")) {
+ request_rec *rr = NULL;
+ char *error_fmt = NULL;
+
+ parse_string(r, tag_val, parsed_string, sizeof(parsed_string), 0);
+ if (tag[0] == 'f') {
+ /* be safe; only files in this directory or below allowed */
+ if (!is_only_below(parsed_string)) {
+ error_fmt = "unable to include file \"%s\" "
+ "in parsed file %s";
+ }
+ else {
+ rr = ap_sub_req_lookup_file(parsed_string, r);
+ }
+ }
+ else {
+ rr = ap_sub_req_lookup_uri(parsed_string, r);
+ }
+
+ if (!error_fmt && rr->status != HTTP_OK) {
+ error_fmt = "unable to include \"%s\" in parsed file %s";
+ }
+
+ if (!error_fmt && noexec && rr->content_type
+ && (strncmp(rr->content_type, "text/", 5))) {
+ error_fmt = "unable to include potential exec \"%s\" "
+ "in parsed file %s";
+ }
+ if (error_fmt == NULL) {
+ /* try to avoid recursive includes. We do this by walking
+ * up the r->main list of subrequests, and at each level
+ * walking back through any internal redirects. At each
+ * step, we compare the filenames and the URIs.
+ *
+ * The filename comparison catches a recursive include
+ * with an ever-changing URL, eg.
+ *
+ * which, although they would eventually be caught because
+ * we have a limit on the length of files, etc., can
+ * recurse for a while.
+ *
+ * The URI comparison catches the case where the filename
+ * is changed while processing the request, so the
+ * current name is never the same as any previous one.
+ * This can happen with "DocumentRoot /foo" when you
+ * request "/" on the server and it includes "/".
+ * This only applies to modules such as mod_dir that
+ * (somewhat improperly) mess with r->filename outside
+ * of a filename translation phase.
+ */
+ int founddupe = 0;
+ request_rec *p;
+ for (p = r; p != NULL && !founddupe; p = p->main) {
+ request_rec *q;
+ for (q = p; q != NULL; q = q->prev) {
+ if ( (strcmp(q->filename, rr->filename) == 0) ||
+ (strcmp(q->uri, rr->uri) == 0) ){
+ founddupe = 1;
+ break;
+ }
+ }
+ }
+
+ if (p != NULL) {
+ error_fmt = "Recursive include of \"%s\" "
+ "in parsed file %s";
+ }
+ }
+
+ /* see the Kludge in send_parsed_file for why */
+ if (rr)
+ ap_set_module_config(rr->request_config, &includes_module, r);
+
+ if (!error_fmt && ap_run_sub_req(rr)) {
+ error_fmt = "unable to include \"%s\" in parsed file %s";
+ }
+#ifndef WIN32
+ ap_chdir_file(r->filename);
+#endif
+ if (error_fmt) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR,
+ r, error_fmt, tag_val, r->filename);
+ ap_rputs(error, r);
+ }
+
+ /* destroy the sub request if it's not a nested include */
+ if (rr != NULL
+ && ap_get_module_config(rr->request_config, &includes_module)
+ != NESTED_INCLUDE_MAGIC) {
+ ap_destroy_sub_req(rr);
+ }
+ }
+ else if (!strcmp(tag, "done")) {
+ return 0;
+ }
+ else {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "unknown parameter \"%s\" to tag include in %s",
+ tag, r->filename);
+ ap_rputs(error, r);
+ }
+ }
+}
+
+typedef struct {
+#ifdef TPF
+ TPF_FORK_CHILD t;
+#endif
+ request_rec *r;
+ char *s;
+} include_cmd_arg;
+
+static int include_cmd_child(void *arg, child_info *pinfo)
+{
+ request_rec *r = ((include_cmd_arg *) arg)->r;
+ char *s = ((include_cmd_arg *) arg)->s;
+ table *env = r->subprocess_env;
+ int child_pid = 0;
+#ifdef DEBUG_INCLUDE_CMD
+#ifdef OS2
+ /* under OS/2 /dev/tty is referenced as con */
+ FILE *dbg = fopen("con", "w");
+#else
+ FILE *dbg = fopen("/dev/tty", "w");
+#endif
+#endif
+#ifndef WIN32
+ char err_string[MAX_STRING_LEN];
+#endif
+
+#ifdef DEBUG_INCLUDE_CMD
+ fprintf(dbg, "Attempting to include command '%s'\n", s);
+#endif
+
+ if (r->path_info && r->path_info[0] != '\0') {
+ request_rec *pa_req;
+
+ ap_table_setn(env, "PATH_INFO", ap_escape_shell_cmd(r->pool, r->path_info));
+
+ pa_req = ap_sub_req_lookup_uri(ap_escape_uri(r->pool, r->path_info), r);
+ if (pa_req->filename) {
+ ap_table_setn(env, "PATH_TRANSLATED",
+ ap_pstrcat(r->pool, pa_req->filename, pa_req->path_info,
+ NULL));
+ }
+ }
+
+ if (r->args) {
+ char *arg_copy = ap_pstrdup(r->pool, r->args);
+
+ ap_table_setn(env, "QUERY_STRING", r->args);
+ ap_unescape_url(arg_copy);
+ ap_table_setn(env, "QUERY_STRING_UNESCAPED",
+ ap_escape_shell_cmd(r->pool, arg_copy));
+ }
+
+ ap_error_log2stderr(r->server);
+
+#ifdef DEBUG_INCLUDE_CMD
+ fprintf(dbg, "Attempting to exec '%s'\n", s);
+#endif
+#ifdef TPF
+ return (0);
+#else
+ ap_cleanup_for_exec();
+ /* set shellcmd flag to pass arg to SHELL_PATH */
+ child_pid = ap_call_exec(r, pinfo, s, ap_create_environment(r->pool, env),
+ 1);
+#if defined(WIN32) || defined(OS2)
+ return (child_pid);
+#else
+ /* Oh, drat. We're still here. The log file descriptors are closed,
+ * so we have to whimper a complaint onto stderr...
+ */
+
+#ifdef DEBUG_INCLUDE_CMD
+ fprintf(dbg, "Exec failed\n");
+#endif
+ ap_snprintf(err_string, sizeof(err_string),
+ "exec of %s failed, reason: %s (errno = %d)\n",
+ SHELL_PATH, strerror(errno), errno);
+ write(STDERR_FILENO, err_string, strlen(err_string));
+ exit(0);
+ /* NOT REACHED */
+ return (child_pid);
+#endif /* WIN32 */
+#endif /* TPF */
+}
+
+static int include_cmd(char *s, request_rec *r)
+{
+ include_cmd_arg arg;
+ BUFF *script_in;
+
+ arg.r = r;
+ arg.s = s;
+#ifdef TPF
+ arg.t.filename = r->filename;
+ arg.t.subprocess_env = r->subprocess_env;
+ arg.t.prog_type = FORK_FILE;
+#endif
+
+ if (!ap_bspawn_child(r->pool, include_cmd_child, &arg,
+ kill_after_timeout, NULL, &script_in, NULL)) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
+ "couldn't spawn include command");
+ return -1;
+ }
+
+ ap_send_fb(script_in, r);
+ ap_bclose(script_in);
+ return 0;
+}
+
+static int handle_exec(FILE *in, request_rec *r, const char *error)
+{
+ char tag[MAX_STRING_LEN];
+ char *tag_val;
+ char *file = r->filename;
+ char parsed_string[MAX_STRING_LEN];
+
+ while (1) {
+ if (!(tag_val = get_tag(r->pool, in, tag, sizeof(tag), 1))) {
+ return 1;
+ }
+ if (!strcmp(tag, "cmd")) {
+ parse_string(r, tag_val, parsed_string, sizeof(parsed_string), 1);
+ if (include_cmd(parsed_string, r) == -1) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "execution failure for parameter \"%s\" "
+ "to tag exec in file %s",
+ tag, r->filename);
+ ap_rputs(error, r);
+ }
+ /* just in case some stooge changed directories */
+#ifndef WIN32
+ ap_chdir_file(r->filename);
+#endif
+ }
+ else if (!strcmp(tag, "cgi")) {
+ parse_string(r, tag_val, parsed_string, sizeof(parsed_string), 0);
+ if (include_cgi(parsed_string, r) == -1) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "invalid CGI ref \"%s\" in %s", tag_val, file);
+ ap_rputs(error, r);
+ }
+ /* grumble groan */
+#ifndef WIN32
+ ap_chdir_file(r->filename);
+#endif
+ }
+ else if (!strcmp(tag, "done")) {
+ return 0;
+ }
+ else {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "unknown parameter \"%s\" to tag exec in %s",
+ tag, file);
+ ap_rputs(error, r);
+ }
+ }
+
+}
+
+static int handle_echo(FILE *in, request_rec *r, const char *error)
+{
+ char tag[MAX_STRING_LEN];
+ char *tag_val;
+
+ while (1) {
+ if (!(tag_val = get_tag(r->pool, in, tag, sizeof(tag), 1))) {
+ return 1;
+ }
+ if (!strcmp(tag, "var")) {
+ const char *val = ap_table_get(r->subprocess_env, tag_val);
+
+ if (val) {
+ ap_rputs(val, r);
+ }
+ else {
+ ap_rputs("(none)", r);
+ }
+ }
+ else if (!strcmp(tag, "done")) {
+ return 0;
+ }
+ else {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "unknown parameter \"%s\" to tag echo in %s",
+ tag, r->filename);
+ ap_rputs(error, r);
+ }
+ }
+}
+
+#ifdef USE_PERL_SSI
+static int handle_perl(FILE *in, request_rec *r, const char *error)
+{
+ char tag[MAX_STRING_LEN];
+ char parsed_string[MAX_STRING_LEN];
+ char *tag_val;
+ SV *sub = Nullsv;
+ AV *av = newAV();
+
+ if (ap_allow_options(r) & OPT_INCNOEXEC) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "#perl SSI disallowed by IncludesNoExec in %s",
+ r->filename);
+ return DECLINED;
+ }
+ while (1) {
+ if (!(tag_val = get_tag(r->pool, in, tag, sizeof(tag), 1))) {
+ break;
+ }
+ if (strnEQ(tag, "sub", 3)) {
+ sub = newSVpv(tag_val, 0);
+ }
+ else if (strnEQ(tag, "arg", 3)) {
+ parse_string(r, tag_val, parsed_string, sizeof(parsed_string), 0);
+ av_push(av, newSVpv(parsed_string, 0));
+ }
+ else if (strnEQ(tag, "done", 4)) {
+ break;
+ }
+ }
+ perl_stdout2client(r);
+ perl_setup_env(r);
+ perl_call_handler(sub, r, av);
+ return OK;
+}
+#endif
+
+/* error and tf must point to a string with room for at
+ * least MAX_STRING_LEN characters
+ */
+static int handle_config(FILE *in, request_rec *r, char *error, char *tf,
+ int *sizefmt)
+{
+ char tag[MAX_STRING_LEN];
+ char *tag_val;
+ char parsed_string[MAX_STRING_LEN];
+ table *env = r->subprocess_env;
+
+ while (1) {
+ if (!(tag_val = get_tag(r->pool, in, tag, sizeof(tag), 0))) {
+ return 1;
+ }
+ if (!strcmp(tag, "errmsg")) {
+ parse_string(r, tag_val, error, MAX_STRING_LEN, 0);
+ }
+ else if (!strcmp(tag, "timefmt")) {
+ time_t date = r->request_time;
+
+ parse_string(r, tag_val, tf, MAX_STRING_LEN, 0);
+ ap_table_setn(env, "DATE_LOCAL", ap_ht_time(r->pool, date, tf, 0));
+ ap_table_setn(env, "DATE_GMT", ap_ht_time(r->pool, date, tf, 1));
+ ap_table_setn(env, "LAST_MODIFIED",
+ ap_ht_time(r->pool, r->finfo.st_mtime, tf, 0));
+ }
+ else if (!strcmp(tag, "sizefmt")) {
+ parse_string(r, tag_val, parsed_string, sizeof(parsed_string), 0);
+ decodehtml(parsed_string);
+ if (!strcmp(parsed_string, "bytes")) {
+ *sizefmt = SIZEFMT_BYTES;
+ }
+ else if (!strcmp(parsed_string, "abbrev")) {
+ *sizefmt = SIZEFMT_KMG;
+ }
+ }
+ else if (!strcmp(tag, "done")) {
+ return 0;
+ }
+ else {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "unknown parameter \"%s\" to tag config in %s",
+ tag, r->filename);
+ ap_rputs(error, r);
+ }
+ }
+}
+
+
+static int find_file(request_rec *r, const char *directive, const char *tag,
+ char *tag_val, struct stat *finfo, const char *error)
+{
+ char *to_send = tag_val;
+ request_rec *rr = NULL;
+ int ret=0;
+ char *error_fmt = NULL;
+
+ if (!strcmp(tag, "file")) {
+ /* be safe; only files in this directory or below allowed */
+ if (!is_only_below(tag_val)) {
+ error_fmt = "unable to access file \"%s\" "
+ "in parsed file %s";
+ }
+ else {
+ ap_getparents(tag_val); /* get rid of any nasties */
+ rr = ap_sub_req_lookup_file(tag_val, r);
+
+ if (rr->status == HTTP_OK && rr->finfo.st_mode != 0) {
+ to_send = rr->filename;
+ if (stat(to_send, finfo)) {
+ error_fmt = "unable to get information about \"%s\" "
+ "in parsed file %s";
+ }
+ }
+ else {
+ error_fmt = "unable to lookup information about \"%s\" "
+ "in parsed file %s";
+ }
+ }
+
+ if (error_fmt) {
+ ret = -1;
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, r, error_fmt, to_send, r->filename);
+ ap_rputs(error, r);
+ }
+
+ if (rr) ap_destroy_sub_req(rr);
+
+ return ret;
+ }
+ else if (!strcmp(tag, "virtual")) {
+ rr = ap_sub_req_lookup_uri(tag_val, r);
+
+ if (rr->status == HTTP_OK && rr->finfo.st_mode != 0) {
+ memcpy((char *) finfo, (const char *) &rr->finfo,
+ sizeof(struct stat));
+ ap_destroy_sub_req(rr);
+ return 0;
+ }
+ else {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "unable to get information about \"%s\" "
+ "in parsed file %s",
+ tag_val, r->filename);
+ ap_rputs(error, r);
+ ap_destroy_sub_req(rr);
+ return -1;
+ }
+ }
+ else {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "unknown parameter \"%s\" to tag %s in %s",
+ tag, directive, r->filename);
+ ap_rputs(error, r);
+ return -1;
+ }
+}
+
+
+static int handle_fsize(FILE *in, request_rec *r, const char *error, int sizefmt)
+{
+ char tag[MAX_STRING_LEN];
+ char *tag_val;
+ struct stat finfo;
+ char parsed_string[MAX_STRING_LEN];
+
+ while (1) {
+ if (!(tag_val = get_tag(r->pool, in, tag, sizeof(tag), 1))) {
+ return 1;
+ }
+ else if (!strcmp(tag, "done")) {
+ return 0;
+ }
+ else {
+ parse_string(r, tag_val, parsed_string, sizeof(parsed_string), 0);
+ if (!find_file(r, "fsize", tag, parsed_string, &finfo, error)) {
+ if (sizefmt == SIZEFMT_KMG) {
+ ap_send_size(finfo.st_size, r);
+ }
+ else {
+ int l, x;
+#if defined(AP_OFF_T_IS_QUAD)
+ ap_snprintf(tag, sizeof(tag), "%qd", finfo.st_size);
+#else
+ ap_snprintf(tag, sizeof(tag), "%ld", finfo.st_size);
+#endif
+ l = strlen(tag); /* grrr */
+ for (x = 0; x < l; x++) {
+ if (x && (!((l - x) % 3))) {
+ ap_rputc(',', r);
+ }
+ ap_rputc(tag[x], r);
+ }
+ }
+ }
+ }
+ }
+}
+
+static int handle_flastmod(FILE *in, request_rec *r, const char *error, const char *tf)
+{
+ char tag[MAX_STRING_LEN];
+ char *tag_val;
+ struct stat finfo;
+ char parsed_string[MAX_STRING_LEN];
+
+ while (1) {
+ if (!(tag_val = get_tag(r->pool, in, tag, sizeof(tag), 1))) {
+ return 1;
+ }
+ else if (!strcmp(tag, "done")) {
+ return 0;
+ }
+ else {
+ parse_string(r, tag_val, parsed_string, sizeof(parsed_string), 0);
+ if (!find_file(r, "flastmod", tag, parsed_string, &finfo, error)) {
+ ap_rputs(ap_ht_time(r->pool, finfo.st_mtime, tf, 0), r);
+ }
+ }
+ }
+}
+
+static int re_check(request_rec *r, char *string, char *rexp)
+{
+ regex_t *compiled;
+ int regex_error;
+
+ compiled = ap_pregcomp(r->pool, rexp, REG_EXTENDED | REG_NOSUB);
+ if (compiled == NULL) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "unable to compile pattern \"%s\"", rexp);
+ return -1;
+ }
+ regex_error = ap_regexec(compiled, string, 0, (regmatch_t *) NULL, 0);
+ ap_pregfree(r->pool, compiled);
+ return (!regex_error);
+}
+
+enum token_type {
+ token_string,
+ token_and, token_or, token_not, token_eq, token_ne,
+ token_rbrace, token_lbrace, token_group,
+ token_ge, token_le, token_gt, token_lt
+};
+struct token {
+ enum token_type type;
+ char value[MAX_STRING_LEN];
+};
+
+/* there is an implicit assumption here that string is at most MAX_STRING_LEN-1
+ * characters long...
+ */
+static const char *get_ptoken(request_rec *r, const char *string, struct token *token)
+{
+ char ch;
+ int next = 0;
+ int qs = 0;
+
+ /* Skip leading white space */
+ if (string == (char *) NULL) {
+ return (char *) NULL;
+ }
+ while ((ch = *string++)) {
+ if (!ap_isspace(ch)) {
+ break;
+ }
+ }
+ if (ch == '\0') {
+ return (char *) NULL;
+ }
+
+ token->type = token_string; /* the default type */
+ switch (ch) {
+ case '(':
+ token->type = token_lbrace;
+ return (string);
+ case ')':
+ token->type = token_rbrace;
+ return (string);
+ case '=':
+ token->type = token_eq;
+ return (string);
+ case '!':
+ if (*string == '=') {
+ token->type = token_ne;
+ return (string + 1);
+ }
+ else {
+ token->type = token_not;
+ return (string);
+ }
+ case '\'':
+ token->type = token_string;
+ qs = 1;
+ break;
+ case '|':
+ if (*string == '|') {
+ token->type = token_or;
+ return (string + 1);
+ }
+ break;
+ case '&':
+ if (*string == '&') {
+ token->type = token_and;
+ return (string + 1);
+ }
+ break;
+ case '>':
+ if (*string == '=') {
+ token->type = token_ge;
+ return (string + 1);
+ }
+ else {
+ token->type = token_gt;
+ return (string);
+ }
+ case '<':
+ if (*string == '=') {
+ token->type = token_le;
+ return (string + 1);
+ }
+ else {
+ token->type = token_lt;
+ return (string);
+ }
+ default:
+ token->type = token_string;
+ break;
+ }
+ /* We should only be here if we are in a string */
+ if (!qs) {
+ token->value[next++] = ch;
+ }
+
+ /*
+ * Yes I know that goto's are BAD. But, c doesn't allow me to
+ * exit a loop from a switch statement. Yes, I could use a flag,
+ * but that is (IMHO) even less readable/maintainable than the goto.
+ */
+ /*
+ * I used the ++string throughout this section so that string
+ * ends up pointing to the next token and I can just return it
+ */
+ for (ch = *string; ch != '\0'; ch = *++string) {
+ if (ch == '\\') {
+ if ((ch = *++string) == '\0') {
+ goto TOKEN_DONE;
+ }
+ token->value[next++] = ch;
+ continue;
+ }
+ if (!qs) {
+ if (ap_isspace(ch)) {
+ goto TOKEN_DONE;
+ }
+ switch (ch) {
+ case '(':
+ goto TOKEN_DONE;
+ case ')':
+ goto TOKEN_DONE;
+ case '=':
+ goto TOKEN_DONE;
+ case '!':
+ goto TOKEN_DONE;
+ case '|':
+ if (*(string + 1) == '|') {
+ goto TOKEN_DONE;
+ }
+ break;
+ case '&':
+ if (*(string + 1) == '&') {
+ goto TOKEN_DONE;
+ }
+ break;
+ case '<':
+ goto TOKEN_DONE;
+ case '>':
+ goto TOKEN_DONE;
+ }
+ token->value[next++] = ch;
+ }
+ else {
+ if (ch == '\'') {
+ qs = 0;
+ ++string;
+ goto TOKEN_DONE;
+ }
+ token->value[next++] = ch;
+ }
+ }
+ TOKEN_DONE:
+ /* If qs is still set, I have an unmatched ' */
+ if (qs) {
+ ap_rputs("\nUnmatched '\n", r);
+ next = 0;
+ }
+ token->value[next] = '\0';
+ return (string);
+}
+
+
+/*
+ * Hey I still know that goto's are BAD. I don't think that I've ever
+ * used two in the same project, let alone the same file before. But,
+ * I absolutely want to make sure that I clean up the memory in all
+ * cases. And, without rewriting this completely, the easiest way
+ * is to just branch to the return code which cleans it up.
+ */
+/* there is an implicit assumption here that expr is at most MAX_STRING_LEN-1
+ * characters long...
+ */
+static int parse_expr(request_rec *r, const char *expr, const char *error)
+{
+ struct parse_node {
+ struct parse_node *left, *right, *parent;
+ struct token token;
+ int value, done;
+ } *root, *current, *new;
+ const char *parse;
+ char buffer[MAX_STRING_LEN];
+ pool *expr_pool;
+ int retval = 0;
+
+ if ((parse = expr) == (char *) NULL) {
+ return (0);
+ }
+ root = current = (struct parse_node *) NULL;
+ expr_pool = ap_make_sub_pool(r->pool);
+
+ /* Create Parse Tree */
+ while (1) {
+ new = (struct parse_node *) ap_palloc(expr_pool,
+ sizeof(struct parse_node));
+ new->parent = new->left = new->right = (struct parse_node *) NULL;
+ new->done = 0;
+ if ((parse = get_ptoken(r, parse, &new->token)) == (char *) NULL) {
+ break;
+ }
+ switch (new->token.type) {
+
+ case token_string:
+#ifdef DEBUG_INCLUDE
+ ap_rvputs(r, " Token: string (", new->token.value, ")\n", NULL);
+#endif
+ if (current == (struct parse_node *) NULL) {
+ root = current = new;
+ break;
+ }
+ switch (current->token.type) {
+ case token_string:
+ if (current->token.value[0] != '\0') {
+ strncat(current->token.value, " ",
+ sizeof(current->token.value)
+ - strlen(current->token.value) - 1);
+ }
+ strncat(current->token.value, new->token.value,
+ sizeof(current->token.value)
+ - strlen(current->token.value) - 1);
+ current->token.value[sizeof(current->token.value) - 1] = '\0';
+ break;
+ case token_eq:
+ case token_ne:
+ case token_and:
+ case token_or:
+ case token_lbrace:
+ case token_not:
+ case token_ge:
+ case token_gt:
+ case token_le:
+ case token_lt:
+ new->parent = current;
+ current = current->right = new;
+ break;
+ default:
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Invalid expression \"%s\" in file %s",
+ expr, r->filename);
+ ap_rputs(error, r);
+ goto RETURN;
+ }
+ break;
+
+ case token_and:
+ case token_or:
+#ifdef DEBUG_INCLUDE
+ ap_rputs(" Token: and/or\n", r);
+#endif
+ if (current == (struct parse_node *) NULL) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Invalid expression \"%s\" in file %s",
+ expr, r->filename);
+ ap_rputs(error, r);
+ goto RETURN;
+ }
+ /* Percolate upwards */
+ while (current != (struct parse_node *) NULL) {
+ switch (current->token.type) {
+ case token_string:
+ case token_group:
+ case token_not:
+ case token_eq:
+ case token_ne:
+ case token_and:
+ case token_or:
+ case token_ge:
+ case token_gt:
+ case token_le:
+ case token_lt:
+ current = current->parent;
+ continue;
+ case token_lbrace:
+ break;
+ default:
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Invalid expression \"%s\" in file %s",
+ expr, r->filename);
+ ap_rputs(error, r);
+ goto RETURN;
+ }
+ break;
+ }
+ if (current == (struct parse_node *) NULL) {
+ new->left = root;
+ new->left->parent = new;
+ new->parent = (struct parse_node *) NULL;
+ root = new;
+ }
+ else {
+ new->left = current->right;
+ current->right = new;
+ new->parent = current;
+ }
+ current = new;
+ break;
+
+ case token_not:
+#ifdef DEBUG_INCLUDE
+ ap_rputs(" Token: not\n", r);
+#endif
+ if (current == (struct parse_node *) NULL) {
+ root = current = new;
+ break;
+ }
+ /* Percolate upwards */
+ while (current != (struct parse_node *) NULL) {
+ switch (current->token.type) {
+ case token_not:
+ case token_eq:
+ case token_ne:
+ case token_and:
+ case token_or:
+ case token_lbrace:
+ case token_ge:
+ case token_gt:
+ case token_le:
+ case token_lt:
+ break;
+ default:
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Invalid expression \"%s\" in file %s",
+ expr, r->filename);
+ ap_rputs(error, r);
+ goto RETURN;
+ }
+ break;
+ }
+ if (current == (struct parse_node *) NULL) {
+ new->left = root;
+ new->left->parent = new;
+ new->parent = (struct parse_node *) NULL;
+ root = new;
+ }
+ else {
+ new->left = current->right;
+ current->right = new;
+ new->parent = current;
+ }
+ current = new;
+ break;
+
+ case token_eq:
+ case token_ne:
+ case token_ge:
+ case token_gt:
+ case token_le:
+ case token_lt:
+#ifdef DEBUG_INCLUDE
+ ap_rputs(" Token: eq/ne/ge/gt/le/lt\n", r);
+#endif
+ if (current == (struct parse_node *) NULL) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Invalid expression \"%s\" in file %s",
+ expr, r->filename);
+ ap_rputs(error, r);
+ goto RETURN;
+ }
+ /* Percolate upwards */
+ while (current != (struct parse_node *) NULL) {
+ switch (current->token.type) {
+ case token_string:
+ case token_group:
+ current = current->parent;
+ continue;
+ case token_lbrace:
+ case token_and:
+ case token_or:
+ break;
+ case token_not:
+ case token_eq:
+ case token_ne:
+ case token_ge:
+ case token_gt:
+ case token_le:
+ case token_lt:
+ default:
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Invalid expression \"%s\" in file %s",
+ expr, r->filename);
+ ap_rputs(error, r);
+ goto RETURN;
+ }
+ break;
+ }
+ if (current == (struct parse_node *) NULL) {
+ new->left = root;
+ new->left->parent = new;
+ new->parent = (struct parse_node *) NULL;
+ root = new;
+ }
+ else {
+ new->left = current->right;
+ current->right = new;
+ new->parent = current;
+ }
+ current = new;
+ break;
+
+ case token_rbrace:
+#ifdef DEBUG_INCLUDE
+ ap_rputs(" Token: rbrace\n", r);
+#endif
+ while (current != (struct parse_node *) NULL) {
+ if (current->token.type == token_lbrace) {
+ current->token.type = token_group;
+ break;
+ }
+ current = current->parent;
+ }
+ if (current == (struct parse_node *) NULL) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Unmatched ')' in \"%s\" in file %s",
+ expr, r->filename);
+ ap_rputs(error, r);
+ goto RETURN;
+ }
+ break;
+
+ case token_lbrace:
+#ifdef DEBUG_INCLUDE
+ ap_rputs(" Token: lbrace\n", r);
+#endif
+ if (current == (struct parse_node *) NULL) {
+ root = current = new;
+ break;
+ }
+ /* Percolate upwards */
+ while (current != (struct parse_node *) NULL) {
+ switch (current->token.type) {
+ case token_not:
+ case token_eq:
+ case token_ne:
+ case token_and:
+ case token_or:
+ case token_lbrace:
+ case token_ge:
+ case token_gt:
+ case token_le:
+ case token_lt:
+ break;
+ case token_string:
+ case token_group:
+ default:
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Invalid expression \"%s\" in file %s",
+ expr, r->filename);
+ ap_rputs(error, r);
+ goto RETURN;
+ }
+ break;
+ }
+ if (current == (struct parse_node *) NULL) {
+ new->left = root;
+ new->left->parent = new;
+ new->parent = (struct parse_node *) NULL;
+ root = new;
+ }
+ else {
+ new->left = current->right;
+ current->right = new;
+ new->parent = current;
+ }
+ current = new;
+ break;
+ default:
+ break;
+ }
+ }
+
+ /* Evaluate Parse Tree */
+ current = root;
+ while (current != (struct parse_node *) NULL) {
+ switch (current->token.type) {
+ case token_string:
+#ifdef DEBUG_INCLUDE
+ ap_rputs(" Evaluate string\n", r);
+#endif
+ parse_string(r, current->token.value, buffer, sizeof(buffer), 0);
+ ap_cpystrn(current->token.value, buffer, sizeof(current->token.value));
+ current->value = (current->token.value[0] != '\0');
+ current->done = 1;
+ current = current->parent;
+ break;
+
+ case token_and:
+ case token_or:
+#ifdef DEBUG_INCLUDE
+ ap_rputs(" Evaluate and/or\n", r);
+#endif
+ if (current->left == (struct parse_node *) NULL ||
+ current->right == (struct parse_node *) NULL) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Invalid expression \"%s\" in file %s",
+ expr, r->filename);
+ ap_rputs(error, r);
+ goto RETURN;
+ }
+ if (!current->left->done) {
+ switch (current->left->token.type) {
+ case token_string:
+ parse_string(r, current->left->token.value,
+ buffer, sizeof(buffer), 0);
+ ap_cpystrn(current->left->token.value, buffer,
+ sizeof(current->left->token.value));
+ current->left->value = (current->left->token.value[0] != '\0');
+ current->left->done = 1;
+ break;
+ default:
+ current = current->left;
+ continue;
+ }
+ }
+ if (!current->right->done) {
+ switch (current->right->token.type) {
+ case token_string:
+ parse_string(r, current->right->token.value,
+ buffer, sizeof(buffer), 0);
+ ap_cpystrn(current->right->token.value, buffer,
+ sizeof(current->right->token.value));
+ current->right->value = (current->right->token.value[0] != '\0');
+ current->right->done = 1;
+ break;
+ default:
+ current = current->right;
+ continue;
+ }
+ }
+#ifdef DEBUG_INCLUDE
+ ap_rvputs(r, " Left: ", current->left->value ? "1" : "0",
+ "\n", NULL);
+ ap_rvputs(r, " Right: ", current->right->value ? "1" : "0",
+ "\n", NULL);
+#endif
+ if (current->token.type == token_and) {
+ current->value = current->left->value && current->right->value;
+ }
+ else {
+ current->value = current->left->value || current->right->value;
+ }
+#ifdef DEBUG_INCLUDE
+ ap_rvputs(r, " Returning ", current->value ? "1" : "0",
+ "\n", NULL);
+#endif
+ current->done = 1;
+ current = current->parent;
+ break;
+
+ case token_eq:
+ case token_ne:
+#ifdef DEBUG_INCLUDE
+ ap_rputs(" Evaluate eq/ne\n", r);
+#endif
+ if ((current->left == (struct parse_node *) NULL) ||
+ (current->right == (struct parse_node *) NULL) ||
+ (current->left->token.type != token_string) ||
+ (current->right->token.type != token_string)) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Invalid expression \"%s\" in file %s",
+ expr, r->filename);
+ ap_rputs(error, r);
+ goto RETURN;
+ }
+ parse_string(r, current->left->token.value,
+ buffer, sizeof(buffer), 0);
+ ap_cpystrn(current->left->token.value, buffer,
+ sizeof(current->left->token.value));
+ parse_string(r, current->right->token.value,
+ buffer, sizeof(buffer), 0);
+ ap_cpystrn(current->right->token.value, buffer,
+ sizeof(current->right->token.value));
+ if (current->right->token.value[0] == '/') {
+ int len;
+ len = strlen(current->right->token.value);
+ if (current->right->token.value[len - 1] == '/') {
+ current->right->token.value[len - 1] = '\0';
+ }
+ else {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Invalid rexp \"%s\" in file %s",
+ current->right->token.value, r->filename);
+ ap_rputs(error, r);
+ goto RETURN;
+ }
+#ifdef DEBUG_INCLUDE
+ ap_rvputs(r, " Re Compare (", current->left->token.value,
+ ") with /", ¤t->right->token.value[1], "/\n", NULL);
+#endif
+ current->value =
+ re_check(r, current->left->token.value,
+ ¤t->right->token.value[1]);
+ }
+ else {
+#ifdef DEBUG_INCLUDE
+ ap_rvputs(r, " Compare (", current->left->token.value,
+ ") with (", current->right->token.value, ")\n", NULL);
+#endif
+ current->value =
+ (strcmp(current->left->token.value,
+ current->right->token.value) == 0);
+ }
+ if (current->token.type == token_ne) {
+ current->value = !current->value;
+ }
+#ifdef DEBUG_INCLUDE
+ ap_rvputs(r, " Returning ", current->value ? "1" : "0",
+ "\n", NULL);
+#endif
+ current->done = 1;
+ current = current->parent;
+ break;
+ case token_ge:
+ case token_gt:
+ case token_le:
+ case token_lt:
+#ifdef DEBUG_INCLUDE
+ ap_rputs(" Evaluate ge/gt/le/lt\n", r);
+#endif
+ if ((current->left == (struct parse_node *) NULL) ||
+ (current->right == (struct parse_node *) NULL) ||
+ (current->left->token.type != token_string) ||
+ (current->right->token.type != token_string)) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Invalid expression \"%s\" in file %s",
+ expr, r->filename);
+ ap_rputs(error, r);
+ goto RETURN;
+ }
+ parse_string(r, current->left->token.value,
+ buffer, sizeof(buffer), 0);
+ ap_cpystrn(current->left->token.value, buffer,
+ sizeof(current->left->token.value));
+ parse_string(r, current->right->token.value,
+ buffer, sizeof(buffer), 0);
+ ap_cpystrn(current->right->token.value, buffer,
+ sizeof(current->right->token.value));
+#ifdef DEBUG_INCLUDE
+ ap_rvputs(r, " Compare (", current->left->token.value,
+ ") with (", current->right->token.value, ")\n", NULL);
+#endif
+ current->value =
+ strcmp(current->left->token.value,
+ current->right->token.value);
+ if (current->token.type == token_ge) {
+ current->value = current->value >= 0;
+ }
+ else if (current->token.type == token_gt) {
+ current->value = current->value > 0;
+ }
+ else if (current->token.type == token_le) {
+ current->value = current->value <= 0;
+ }
+ else if (current->token.type == token_lt) {
+ current->value = current->value < 0;
+ }
+ else {
+ current->value = 0; /* Don't return -1 if unknown token */
+ }
+#ifdef DEBUG_INCLUDE
+ ap_rvputs(r, " Returning ", current->value ? "1" : "0",
+ "\n", NULL);
+#endif
+ current->done = 1;
+ current = current->parent;
+ break;
+
+ case token_not:
+ if (current->right != (struct parse_node *) NULL) {
+ if (!current->right->done) {
+ current = current->right;
+ continue;
+ }
+ current->value = !current->right->value;
+ }
+ else {
+ current->value = 0;
+ }
+#ifdef DEBUG_INCLUDE
+ ap_rvputs(r, " Evaluate !: ", current->value ? "1" : "0",
+ "\n", NULL);
+#endif
+ current->done = 1;
+ current = current->parent;
+ break;
+
+ case token_group:
+ if (current->right != (struct parse_node *) NULL) {
+ if (!current->right->done) {
+ current = current->right;
+ continue;
+ }
+ current->value = current->right->value;
+ }
+ else {
+ current->value = 1;
+ }
+#ifdef DEBUG_INCLUDE
+ ap_rvputs(r, " Evaluate (): ", current->value ? "1" : "0",
+ "\n", NULL);
+#endif
+ current->done = 1;
+ current = current->parent;
+ break;
+
+ case token_lbrace:
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Unmatched '(' in \"%s\" in file %s",
+ expr, r->filename);
+ ap_rputs(error, r);
+ goto RETURN;
+
+ case token_rbrace:
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Unmatched ')' in \"%s\" in file %s",
+ expr, r->filename);
+ ap_rputs(error, r);
+ goto RETURN;
+
+ default:
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "bad token type");
+ ap_rputs(error, r);
+ goto RETURN;
+ }
+ }
+
+ retval = (root == (struct parse_node *) NULL) ? 0 : root->value;
+ RETURN:
+ ap_destroy_pool(expr_pool);
+ return (retval);
+}
+
+static int handle_if(FILE *in, request_rec *r, const char *error,
+ int *conditional_status, int *printing)
+{
+ char tag[MAX_STRING_LEN];
+ char *tag_val;
+ char *expr;
+
+ expr = NULL;
+ while (1) {
+ tag_val = get_tag(r->pool, in, tag, sizeof(tag), 0);
+ if (*tag == '\0') {
+ return 1;
+ }
+ else if (!strcmp(tag, "done")) {
+ if (expr == NULL) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "missing expr in if statement: %s",
+ r->filename);
+ ap_rputs(error, r);
+ return 1;
+ }
+ *printing = *conditional_status = parse_expr(r, expr, error);
+#ifdef DEBUG_INCLUDE
+ ap_rvputs(r, "**** if conditional_status=\"",
+ *conditional_status ? "1" : "0", "\"\n", NULL);
+#endif
+ return 0;
+ }
+ else if (!strcmp(tag, "expr")) {
+ expr = tag_val;
+#ifdef DEBUG_INCLUDE
+ ap_rvputs(r, "**** if expr=\"", expr, "\"\n", NULL);
+#endif
+ }
+ else {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "unknown parameter \"%s\" to tag if in %s",
+ tag, r->filename);
+ ap_rputs(error, r);
+ }
+ }
+}
+
+static int handle_elif(FILE *in, request_rec *r, const char *error,
+ int *conditional_status, int *printing)
+{
+ char tag[MAX_STRING_LEN];
+ char *tag_val;
+ char *expr;
+
+ expr = NULL;
+ while (1) {
+ tag_val = get_tag(r->pool, in, tag, sizeof(tag), 0);
+ if (*tag == '\0') {
+ return 1;
+ }
+ else if (!strcmp(tag, "done")) {
+#ifdef DEBUG_INCLUDE
+ ap_rvputs(r, "**** elif conditional_status=\"",
+ *conditional_status ? "1" : "0", "\"\n", NULL);
+#endif
+ if (*conditional_status) {
+ *printing = 0;
+ return (0);
+ }
+ if (expr == NULL) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "missing expr in elif statement: %s",
+ r->filename);
+ ap_rputs(error, r);
+ return 1;
+ }
+ *printing = *conditional_status = parse_expr(r, expr, error);
+#ifdef DEBUG_INCLUDE
+ ap_rvputs(r, "**** elif conditional_status=\"",
+ *conditional_status ? "1" : "0", "\"\n", NULL);
+#endif
+ return 0;
+ }
+ else if (!strcmp(tag, "expr")) {
+ expr = tag_val;
+#ifdef DEBUG_INCLUDE
+ ap_rvputs(r, "**** if expr=\"", expr, "\"\n", NULL);
+#endif
+ }
+ else {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "unknown parameter \"%s\" to tag if in %s",
+ tag, r->filename);
+ ap_rputs(error, r);
+ }
+ }
+}
+
+static int handle_else(FILE *in, request_rec *r, const char *error,
+ int *conditional_status, int *printing)
+{
+ char tag[MAX_STRING_LEN];
+
+ if (!get_tag(r->pool, in, tag, sizeof(tag), 1)) {
+ return 1;
+ }
+ else if (!strcmp(tag, "done")) {
+#ifdef DEBUG_INCLUDE
+ ap_rvputs(r, "**** else conditional_status=\"",
+ *conditional_status ? "1" : "0", "\"\n", NULL);
+#endif
+ *printing = !(*conditional_status);
+ *conditional_status = 1;
+ return 0;
+ }
+ else {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "else directive does not take tags in %s",
+ r->filename);
+ if (*printing) {
+ ap_rputs(error, r);
+ }
+ return -1;
+ }
+}
+
+static int handle_endif(FILE *in, request_rec *r, const char *error,
+ int *conditional_status, int *printing)
+{
+ char tag[MAX_STRING_LEN];
+
+ if (!get_tag(r->pool, in, tag, sizeof(tag), 1)) {
+ return 1;
+ }
+ else if (!strcmp(tag, "done")) {
+#ifdef DEBUG_INCLUDE
+ ap_rvputs(r, "**** endif conditional_status=\"",
+ *conditional_status ? "1" : "0", "\"\n", NULL);
+#endif
+ *printing = 1;
+ *conditional_status = 1;
+ return 0;
+ }
+ else {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "endif directive does not take tags in %s",
+ r->filename);
+ ap_rputs(error, r);
+ return -1;
+ }
+}
+
+static int handle_set(FILE *in, request_rec *r, const char *error)
+{
+ char tag[MAX_STRING_LEN];
+ char parsed_string[MAX_STRING_LEN];
+ char *tag_val;
+ char *var;
+
+ var = (char *) NULL;
+ while (1) {
+ if (!(tag_val = get_tag(r->pool, in, tag, sizeof(tag), 1))) {
+ return 1;
+ }
+ else if (!strcmp(tag, "done")) {
+ return 0;
+ }
+ else if (!strcmp(tag, "var")) {
+ var = tag_val;
+ }
+ else if (!strcmp(tag, "value")) {
+ if (var == (char *) NULL) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "variable must precede value in set directive in %s",
+ r->filename);
+ ap_rputs(error, r);
+ return -1;
+ }
+ parse_string(r, tag_val, parsed_string, sizeof(parsed_string), 0);
+ ap_table_setn(r->subprocess_env, var, ap_pstrdup(r->pool, parsed_string));
+ }
+ else {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Invalid tag for set directive in %s", r->filename);
+ ap_rputs(error, r);
+ return -1;
+ }
+ }
+}
+
+static int handle_printenv(FILE *in, request_rec *r, const char *error)
+{
+ char tag[MAX_STRING_LEN];
+ char *tag_val;
+ array_header *arr = ap_table_elts(r->subprocess_env);
+ table_entry *elts = (table_entry *) arr->elts;
+ int i;
+
+ if (!(tag_val = get_tag(r->pool, in, tag, sizeof(tag), 1))) {
+ return 1;
+ }
+ else if (!strcmp(tag, "done")) {
+ for (i = 0; i < arr->nelts; ++i) {
+ ap_rvputs(r, elts[i].key, "=", elts[i].val, "\n", NULL);
+ }
+ return 0;
+ }
+ else {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "printenv directive does not take tags in %s",
+ r->filename);
+ ap_rputs(error, r);
+ return -1;
+ }
+}
+
+
+
+/* -------------------------- The main function --------------------------- */
+
+/* This is a stub which parses a file descriptor. */
+
+static void send_parsed_content(FILE *f, request_rec *r)
+{
+ char directive[MAX_STRING_LEN], error[MAX_STRING_LEN];
+ char timefmt[MAX_STRING_LEN];
+ int noexec = ap_allow_options(r) & OPT_INCNOEXEC;
+ int ret, sizefmt;
+ int if_nesting;
+ int printing;
+ int conditional_status;
+
+ ap_cpystrn(error, DEFAULT_ERROR_MSG, sizeof(error));
+ ap_cpystrn(timefmt, DEFAULT_TIME_FORMAT, sizeof(timefmt));
+ sizefmt = SIZEFMT_KMG;
+
+/* Turn printing on */
+ printing = conditional_status = 1;
+ if_nesting = 0;
+
+#ifndef WIN32
+ ap_chdir_file(r->filename);
+#endif
+ if (r->args) { /* add QUERY stuff to env cause it ain't yet */
+ char *arg_copy = ap_pstrdup(r->pool, r->args);
+
+ ap_table_setn(r->subprocess_env, "QUERY_STRING", r->args);
+ ap_unescape_url(arg_copy);
+ ap_table_setn(r->subprocess_env, "QUERY_STRING_UNESCAPED",
+ ap_escape_shell_cmd(r->pool, arg_copy));
+ }
+
+ while (1) {
+ if (!find_string(f, STARTING_SEQUENCE, r, printing)) {
+ if (get_directive(f, directive, sizeof(directive), r->pool)) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "mod_include: error reading directive in %s",
+ r->filename);
+ ap_rputs(error, r);
+ return;
+ }
+ if (!strcmp(directive, "if")) {
+ if (!printing) {
+ if_nesting++;
+ }
+ else {
+ ret = handle_if(f, r, error, &conditional_status,
+ &printing);
+ if_nesting = 0;
+ }
+ continue;
+ }
+ else if (!strcmp(directive, "else")) {
+ if (!if_nesting) {
+ ret = handle_else(f, r, error, &conditional_status,
+ &printing);
+ }
+ continue;
+ }
+ else if (!strcmp(directive, "elif")) {
+ if (!if_nesting) {
+ ret = handle_elif(f, r, error, &conditional_status,
+ &printing);
+ }
+ continue;
+ }
+ else if (!strcmp(directive, "endif")) {
+ if (!if_nesting) {
+ ret = handle_endif(f, r, error, &conditional_status,
+ &printing);
+ }
+ else {
+ if_nesting--;
+ }
+ continue;
+ }
+ if (!printing) {
+ continue;
+ }
+ if (!strcmp(directive, "exec")) {
+ if (noexec) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "exec used but not allowed in %s",
+ r->filename);
+ if (printing) {
+ ap_rputs(error, r);
+ }
+ ret = find_string(f, ENDING_SEQUENCE, r, 0);
+ }
+ else {
+ ret = handle_exec(f, r, error);
+ }
+ }
+ else if (!strcmp(directive, "config")) {
+ ret = handle_config(f, r, error, timefmt, &sizefmt);
+ }
+ else if (!strcmp(directive, "set")) {
+ ret = handle_set(f, r, error);
+ }
+ else if (!strcmp(directive, "include")) {
+ ret = handle_include(f, r, error, noexec);
+ }
+ else if (!strcmp(directive, "echo")) {
+ ret = handle_echo(f, r, error);
+ }
+ else if (!strcmp(directive, "fsize")) {
+ ret = handle_fsize(f, r, error, sizefmt);
+ }
+ else if (!strcmp(directive, "flastmod")) {
+ ret = handle_flastmod(f, r, error, timefmt);
+ }
+ else if (!strcmp(directive, "printenv")) {
+ ret = handle_printenv(f, r, error);
+ }
+#ifdef USE_PERL_SSI
+ else if (!strcmp(directive, "perl")) {
+ ret = handle_perl(f, r, error);
+ }
+#endif
+ else {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "unknown directive \"%s\" "
+ "in parsed doc %s",
+ directive, r->filename);
+ if (printing) {
+ ap_rputs(error, r);
+ }
+ ret = find_string(f, ENDING_SEQUENCE, r, 0);
+ }
+ if (ret) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "premature EOF in parsed file %s",
+ r->filename);
+ return;
+ }
+ }
+ else {
+ return;
+ }
+ }
+}
+
+/*****************************************************************
+ *
+ * XBITHACK. Sigh... NB it's configurable per-directory; the compile-time
+ * option only changes the default.
+ */
+
+module includes_module;
+enum xbithack {
+ xbithack_off, xbithack_on, xbithack_full
+};
+
+#ifdef XBITHACK
+#define DEFAULT_XBITHACK xbithack_full
+#else
+#define DEFAULT_XBITHACK xbithack_off
+#endif
+
+static void *create_includes_dir_config(pool *p, char *dummy)
+{
+ enum xbithack *result = (enum xbithack *) ap_palloc(p, sizeof(enum xbithack));
+ *result = DEFAULT_XBITHACK;
+ return result;
+}
+
+static const char *set_xbithack(cmd_parms *cmd, void *xbp, char *arg)
+{
+ enum xbithack *state = (enum xbithack *) xbp;
+
+ if (!strcasecmp(arg, "off")) {
+ *state = xbithack_off;
+ }
+ else if (!strcasecmp(arg, "on")) {
+ *state = xbithack_on;
+ }
+ else if (!strcasecmp(arg, "full")) {
+ *state = xbithack_full;
+ }
+ else {
+ return "XBitHack must be set to Off, On, or Full";
+ }
+
+ return NULL;
+}
+
+static int send_parsed_file(request_rec *r)
+{
+ FILE *f;
+ enum xbithack *state =
+ (enum xbithack *) ap_get_module_config(r->per_dir_config, &includes_module);
+ int errstatus;
+ request_rec *parent;
+
+ if (!(ap_allow_options(r) & OPT_INCLUDES)) {
+ return DECLINED;
+ }
+ r->allowed |= (1 << M_GET);
+ if (r->method_number != M_GET) {
+ return DECLINED;
+ }
+ if (r->finfo.st_mode == 0) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "File does not exist: %s",
+ (r->path_info
+ ? ap_pstrcat(r->pool, r->filename, r->path_info, NULL)
+ : r->filename));
+ return HTTP_NOT_FOUND;
+ }
+
+ if (!(f = ap_pfopen(r->pool, r->filename, "r"))) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
+ "file permissions deny server access: %s", r->filename);
+ return HTTP_FORBIDDEN;
+ }
+
+ if ((*state == xbithack_full)
+#if !defined(OS2) && !defined(WIN32)
+ /* OS/2 dosen't support Groups. */
+ && (r->finfo.st_mode & S_IXGRP)
+#endif
+ ) {
+ ap_update_mtime(r, r->finfo.st_mtime);
+ ap_set_last_modified(r);
+ }
+ if ((errstatus = ap_meets_conditions(r)) != OK) {
+ return errstatus;
+ }
+
+ ap_send_http_header(r);
+
+ if (r->header_only) {
+ ap_pfclose(r->pool, f);
+ return OK;
+ }
+
+ if ((parent = ap_get_module_config(r->request_config, &includes_module))) {
+ /* Kludge --- for nested includes, we want to keep the subprocess
+ * environment of the base document (for compatibility); that means
+ * torquing our own last_modified date as well so that the
+ * LAST_MODIFIED variable gets reset to the proper value if the
+ * nested document resets .
+ * We also insist that the memory for this subrequest not be
+ * destroyed, that's dealt with in handle_include().
+ */
+ r->subprocess_env = parent->subprocess_env;
+ ap_pool_join(parent->pool, r->pool);
+ r->finfo.st_mtime = parent->finfo.st_mtime;
+ }
+ else {
+ /* we're not a nested include, so we create an initial
+ * environment */
+ ap_add_common_vars(r);
+ ap_add_cgi_vars(r);
+ add_include_vars(r, DEFAULT_TIME_FORMAT);
+ }
+ /* XXX: this is bogus, at some point we're going to do a subrequest,
+ * and when we do it we're going to be subjecting code that doesn't
+ * expect to be signal-ready to SIGALRM. There is no clean way to
+ * fix this, except to put alarm support into BUFF. -djg
+ */
+ ap_hard_timeout("send SSI", r);
+
+#ifdef CHARSET_EBCDIC
+ /* XXX:@@@ Is the generated/included output ALWAYS in text/ebcdic format? */
+ ap_bsetflag(r->connection->client, B_EBCDIC2ASCII, 1);
+#endif
+
+ send_parsed_content(f, r);
+
+ if (parent) {
+ /* signify that the sub request should not be killed */
+ ap_set_module_config(r->request_config, &includes_module,
+ NESTED_INCLUDE_MAGIC);
+ }
+
+ ap_kill_timeout(r);
+ return OK;
+}
+
+static int send_shtml_file(request_rec *r)
+{
+ r->content_type = "text/html";
+ return send_parsed_file(r);
+}
+
+static int xbithack_handler(request_rec *r)
+{
+#if defined(OS2) || defined(WIN32)
+ /* OS/2 dosen't currently support the xbithack. This is being worked on. */
+ return DECLINED;
+#else
+ enum xbithack *state;
+
+ if (!(r->finfo.st_mode & S_IXUSR)) {
+ return DECLINED;
+ }
+
+ state = (enum xbithack *) ap_get_module_config(r->per_dir_config,
+ &includes_module);
+
+ if (*state == xbithack_off) {
+ return DECLINED;
+ }
+ return send_parsed_file(r);
+#endif
+}
+
+static const command_rec includes_cmds[] =
+{
+ {"XBitHack", set_xbithack, NULL, OR_OPTIONS, TAKE1, "Off, On, or Full"},
+ {NULL}
+};
+
+static const handler_rec includes_handlers[] =
+{
+ {INCLUDES_MAGIC_TYPE, send_shtml_file},
+ {INCLUDES_MAGIC_TYPE3, send_shtml_file},
+ {"server-parsed", send_parsed_file},
+ {"text/html", xbithack_handler},
+ {NULL}
+};
+
+module MODULE_VAR_EXPORT includes_module =
+{
+ STANDARD_MODULE_STUFF,
+ NULL, /* initializer */
+ create_includes_dir_config, /* dir config creater */
+ NULL, /* dir merger --- default is to override */
+ NULL, /* server config */
+ NULL, /* merge server config */
+ includes_cmds, /* command table */
+ includes_handlers, /* handlers */
+ NULL, /* filename translation */
+ NULL, /* check_user_id */
+ NULL, /* check auth */
+ NULL, /* check access */
+ NULL, /* type_checker */
+ NULL, /* fixups */
+ NULL, /* logger */
+ NULL, /* header parser */
+ NULL, /* child_init */
+ NULL, /* child_exit */
+ NULL /* post read-request */
+};
diff --git a/modules/generators/.indent.pro b/modules/generators/.indent.pro
new file mode 100644
index 00000000000..a9fbe9f9a1f
--- /dev/null
+++ b/modules/generators/.indent.pro
@@ -0,0 +1,54 @@
+-i4 -npsl -di0 -br -nce -d0 -cli0 -npcs -nfc1
+-TBUFF
+-TFILE
+-TTRANS
+-TUINT4
+-T_trans
+-Tallow_options_t
+-Tapache_sfio
+-Tarray_header
+-Tbool_int
+-Tbuf_area
+-Tbuff_struct
+-Tbuffy
+-Tcmd_how
+-Tcmd_parms
+-Tcommand_rec
+-Tcommand_struct
+-Tconn_rec
+-Tcore_dir_config
+-Tcore_server_config
+-Tdir_maker_func
+-Tevent
+-Tglobals_s
+-Thandler_func
+-Thandler_rec
+-Tjoblist_s
+-Tlisten_rec
+-Tmerger_func
+-Tmode_t
+-Tmodule
+-Tmodule_struct
+-Tmutex
+-Tn_long
+-Tother_child_rec
+-Toverrides_t
+-Tparent_score
+-Tpid_t
+-Tpiped_log
+-Tpool
+-Trequest_rec
+-Trequire_line
+-Trlim_t
+-Tscoreboard
+-Tsemaphore
+-Tserver_addr_rec
+-Tserver_rec
+-Tserver_rec_chain
+-Tshort_score
+-Ttable
+-Ttable_entry
+-Tthread
+-Tu_wide_int
+-Tvtime_t
+-Twide_int
diff --git a/modules/generators/mod_asis.c b/modules/generators/mod_asis.c
new file mode 100644
index 00000000000..5e299df9268
--- /dev/null
+++ b/modules/generators/mod_asis.c
@@ -0,0 +1,145 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+#include "httpd.h"
+#include "http_config.h"
+#include "http_protocol.h"
+#include "http_log.h"
+#include "util_script.h"
+#include "http_main.h"
+#include "http_request.h"
+
+static int asis_handler(request_rec *r)
+{
+ FILE *f;
+ const char *location;
+
+ r->allowed |= (1 << M_GET);
+ if (r->method_number != M_GET)
+ return DECLINED;
+ if (r->finfo.st_mode == 0) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "File does not exist: %s", r->filename);
+ return NOT_FOUND;
+ }
+
+ f = ap_pfopen(r->pool, r->filename, "r");
+
+ if (f == NULL) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
+ "file permissions deny server access: %s", r->filename);
+ return FORBIDDEN;
+ }
+
+ ap_scan_script_header_err(r, f, NULL);
+ location = ap_table_get(r->headers_out, "Location");
+
+ if (location && location[0] == '/' &&
+ ((r->status == HTTP_OK) || ap_is_HTTP_REDIRECT(r->status))) {
+
+ ap_pfclose(r->pool, f);
+
+ /* Internal redirect -- fake-up a pseudo-request */
+ r->status = HTTP_OK;
+
+ /* This redirect needs to be a GET no matter what the original
+ * method was.
+ */
+ r->method = ap_pstrdup(r->pool, "GET");
+ r->method_number = M_GET;
+
+ ap_internal_redirect_handler(location, r);
+ return OK;
+ }
+
+ ap_send_http_header(r);
+ if (!r->header_only)
+ ap_send_fd(f, r);
+
+ ap_pfclose(r->pool, f);
+ return OK;
+}
+
+static const handler_rec asis_handlers[] =
+{
+ {ASIS_MAGIC_TYPE, asis_handler},
+ {"send-as-is", asis_handler},
+ {NULL}
+};
+
+module MODULE_VAR_EXPORT asis_module =
+{
+ STANDARD_MODULE_STUFF,
+ NULL, /* initializer */
+ NULL, /* create per-directory config structure */
+ NULL, /* merge per-directory config structures */
+ NULL, /* create per-server config structure */
+ NULL, /* merge per-server config structures */
+ NULL, /* command table */
+ asis_handlers, /* handlers */
+ NULL, /* translate_handler */
+ NULL, /* check_user_id */
+ NULL, /* check auth */
+ NULL, /* check access */
+ NULL, /* type_checker */
+ NULL, /* pre-run fixups */
+ NULL, /* logger */
+ NULL, /* header parser */
+ NULL, /* child_init */
+ NULL, /* child_exit */
+ NULL /* post read-request */
+};
diff --git a/modules/generators/mod_autoindex.c b/modules/generators/mod_autoindex.c
new file mode 100644
index 00000000000..9c28dc40864
--- /dev/null
+++ b/modules/generators/mod_autoindex.c
@@ -0,0 +1,1673 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+/*
+ * mod_autoindex.c: Handles the on-the-fly html index generation
+ *
+ * Rob McCool
+ * 3/23/93
+ *
+ * Adapted to Apache by rst.
+ */
+
+#include "httpd.h"
+#include "http_config.h"
+#include "http_core.h"
+#include "http_request.h"
+#include "http_protocol.h"
+#include "http_log.h"
+#include "http_main.h"
+#include "util_script.h"
+#include "fnmatch.h"
+
+module MODULE_VAR_EXPORT autoindex_module;
+
+/****************************************************************
+ *
+ * Handling configuration directives...
+ */
+
+#define HRULE 1
+#define NO_HRULE 0
+#define FRONT_MATTER 1
+#define END_MATTER 0
+
+#define FANCY_INDEXING 1 /* Indexing options */
+#define ICONS_ARE_LINKS 2
+#define SCAN_HTML_TITLES 4
+#define SUPPRESS_LAST_MOD 8
+#define SUPPRESS_SIZE 16
+#define SUPPRESS_DESC 32
+#define SUPPRESS_PREAMBLE 64
+#define SUPPRESS_COLSORT 128
+#define NO_OPTIONS 256
+
+#define K_PAD 1
+#define K_NOPAD 0
+
+#define K_NOADJUST 0
+#define K_ADJUST 1
+#define K_UNSET 2
+
+/*
+ * Define keys for sorting.
+ */
+#define K_NAME 'N' /* Sort by file name (default) */
+#define K_LAST_MOD 'M' /* Last modification date */
+#define K_SIZE 'S' /* Size (absolute, not as displayed) */
+#define K_DESC 'D' /* Description */
+
+#define D_ASCENDING 'A'
+#define D_DESCENDING 'D'
+
+/*
+ * These are the dimensions of the default icons supplied with Apache.
+ */
+#define DEFAULT_ICON_WIDTH 20
+#define DEFAULT_ICON_HEIGHT 22
+
+/*
+ * Other default dimensions.
+ */
+#define DEFAULT_NAME_WIDTH 23
+
+struct item {
+ char *type;
+ char *apply_to;
+ char *apply_path;
+ char *data;
+};
+
+typedef struct ai_desc_t {
+ char *pattern;
+ char *description;
+ int full_path;
+ int wildcards;
+} ai_desc_t;
+
+typedef struct autoindex_config_struct {
+
+ char *default_icon;
+ int opts;
+ int incremented_opts;
+ int decremented_opts;
+ int name_width;
+ int name_adjust;
+ int icon_width;
+ int icon_height;
+ char *default_order;
+
+ array_header *icon_list;
+ array_header *alt_list;
+ array_header *desc_list;
+ array_header *ign_list;
+ array_header *hdr_list;
+ array_header *rdme_list;
+
+} autoindex_config_rec;
+
+static char c_by_encoding, c_by_type, c_by_path;
+
+#define BY_ENCODING &c_by_encoding
+#define BY_TYPE &c_by_type
+#define BY_PATH &c_by_path
+
+/*
+ * Return true if the specified string refers to the parent directory (i.e.,
+ * matches ".." or "../"). Hopefully this one call is significantly less
+ * expensive than multiple strcmp() calls.
+ */
+static ap_inline int is_parent(const char *name)
+{
+ /*
+ * Now, IFF the first two bytes are dots, and the third byte is either
+ * EOS (\0) or a slash followed by EOS, we have a match.
+ */
+ if (((name[0] == '.') && (name[1] == '.'))
+ && ((name[2] == '\0')
+ || ((name[2] == '/') && (name[3] == '\0')))) {
+ return 1;
+ }
+ return 0;
+}
+
+/*
+ * This routine puts the standard HTML header at the top of the index page.
+ * We include the DOCTYPE because we may be using features therefrom (i.e.,
+ * HEIGHT and WIDTH attributes on the icons if we're FancyIndexing).
+ */
+static void emit_preamble(request_rec *r, char *title)
+{
+ ap_rvputs(r, DOCTYPE_HTML_3_2,
+ "\n \n Index of ", title,
+ "\n \n \n", NULL);
+}
+
+static void push_item(array_header *arr, char *type, char *to, char *path,
+ char *data)
+{
+ struct item *p = (struct item *) ap_push_array(arr);
+
+ if (!to) {
+ to = "";
+ }
+ if (!path) {
+ path = "";
+ }
+
+ p->type = type;
+ p->data = data ? ap_pstrdup(arr->pool, data) : NULL;
+ p->apply_path = ap_pstrcat(arr->pool, path, "*", NULL);
+
+ if ((type == BY_PATH) && (!ap_is_matchexp(to))) {
+ p->apply_to = ap_pstrcat(arr->pool, "*", to, NULL);
+ }
+ else if (to) {
+ p->apply_to = ap_pstrdup(arr->pool, to);
+ }
+ else {
+ p->apply_to = NULL;
+ }
+}
+
+static const char *add_alt(cmd_parms *cmd, void *d, char *alt, char *to)
+{
+ if (cmd->info == BY_PATH) {
+ if (!strcmp(to, "**DIRECTORY**")) {
+ to = "^^DIRECTORY^^";
+ }
+ }
+ if (cmd->info == BY_ENCODING) {
+ ap_str_tolower(to);
+ }
+
+ push_item(((autoindex_config_rec *) d)->alt_list, cmd->info, to,
+ cmd->path, alt);
+ return NULL;
+}
+
+static const char *add_icon(cmd_parms *cmd, void *d, char *icon, char *to)
+{
+ char *iconbak = ap_pstrdup(cmd->pool, icon);
+
+ if (icon[0] == '(') {
+ char *alt;
+ char *cl = strchr(iconbak, ')');
+
+ if (cl == NULL) {
+ return "missing closing paren";
+ }
+ alt = ap_getword_nc(cmd->pool, &iconbak, ',');
+ *cl = '\0'; /* Lose closing paren */
+ add_alt(cmd, d, &alt[1], to);
+ }
+ if (cmd->info == BY_PATH) {
+ if (!strcmp(to, "**DIRECTORY**")) {
+ to = "^^DIRECTORY^^";
+ }
+ }
+ if (cmd->info == BY_ENCODING) {
+ ap_str_tolower(to);
+ }
+
+ push_item(((autoindex_config_rec *) d)->icon_list, cmd->info, to,
+ cmd->path, iconbak);
+ return NULL;
+}
+
+/*
+ * Add description text for a filename pattern. If the pattern has
+ * wildcards already (or we need to add them), add leading and
+ * trailing wildcards to it to ensure substring processing. If the
+ * pattern contains a '/' anywhere, force wildcard matching mode,
+ * add a slash to the prefix so that "bar/bletch" won't be matched
+ * by "foobar/bletch", and make a note that there's a delimiter;
+ * the matching routine simplifies to just the actual filename
+ * whenever it can. This allows definitions in parent directories
+ * to be made for files in subordinate ones using relative paths.
+ */
+
+/*
+ * Absent a strcasestr() function, we have to force wildcards on
+ * systems for which "AAA" and "aaa" mean the same file.
+ */
+#ifdef CASE_BLIND_FILESYSTEM
+#define WILDCARDS_REQUIRED 1
+#else
+#define WILDCARDS_REQUIRED 0
+#endif
+
+static const char *add_desc(cmd_parms *cmd, void *d, char *desc, char *to)
+{
+ autoindex_config_rec *dcfg = (autoindex_config_rec *) d;
+ ai_desc_t *desc_entry;
+ char *prefix = "";
+
+ desc_entry = (ai_desc_t *) ap_push_array(dcfg->desc_list);
+ desc_entry->full_path = (strchr(to, '/') == NULL) ? 0 : 1;
+ desc_entry->wildcards = (WILDCARDS_REQUIRED
+ || desc_entry->full_path
+ || ap_is_fnmatch(to));
+ if (desc_entry->wildcards) {
+ prefix = desc_entry->full_path ? "*/" : "*";
+ desc_entry->pattern = ap_pstrcat(dcfg->desc_list->pool,
+ prefix, to, "*", NULL);
+ }
+ else {
+ desc_entry->pattern = ap_pstrdup(dcfg->desc_list->pool, to);
+ }
+ desc_entry->description = ap_pstrdup(dcfg->desc_list->pool, desc);
+ return NULL;
+}
+
+static const char *add_ignore(cmd_parms *cmd, void *d, char *ext)
+{
+ push_item(((autoindex_config_rec *) d)->ign_list, 0, ext, cmd->path, NULL);
+ return NULL;
+}
+
+static const char *add_header(cmd_parms *cmd, void *d, char *name)
+{
+ push_item(((autoindex_config_rec *) d)->hdr_list, 0, NULL, cmd->path,
+ name);
+ return NULL;
+}
+
+static const char *add_readme(cmd_parms *cmd, void *d, char *name)
+{
+ push_item(((autoindex_config_rec *) d)->rdme_list, 0, NULL, cmd->path,
+ name);
+ return NULL;
+}
+
+/* A legacy directive, FancyIndexing is superseded by the IndexOptions
+ * keyword. But for compatibility..
+ */
+static const char *fancy_indexing(cmd_parms *cmd, void *d, int arg)
+{
+ int curopts;
+ int newopts;
+ autoindex_config_rec *cfg;
+
+ cfg = (autoindex_config_rec *) d;
+ curopts = cfg->opts;
+ if (curopts & NO_OPTIONS) {
+ return "FancyIndexing directive conflicts with existing "
+ "IndexOptions None";
+ }
+ newopts = (arg ? (curopts | FANCY_INDEXING) : (curopts & ~FANCY_INDEXING));
+ cfg->opts = newopts;
+ return NULL;
+}
+
+static const char *add_opts(cmd_parms *cmd, void *d, const char *optstr)
+{
+ char *w;
+ int opts;
+ int opts_add;
+ int opts_remove;
+ char action;
+ autoindex_config_rec *d_cfg = (autoindex_config_rec *) d;
+
+ opts = d_cfg->opts;
+ opts_add = d_cfg->incremented_opts;
+ opts_remove = d_cfg->decremented_opts;
+ while (optstr[0]) {
+ int option = 0;
+
+ w = ap_getword_conf(cmd->pool, &optstr);
+ if ((*w == '+') || (*w == '-')) {
+ action = *(w++);
+ }
+ else {
+ action = '\0';
+ }
+ if (!strcasecmp(w, "FancyIndexing")) {
+ option = FANCY_INDEXING;
+ }
+ else if (!strcasecmp(w, "IconsAreLinks")) {
+ option = ICONS_ARE_LINKS;
+ }
+ else if (!strcasecmp(w, "ScanHTMLTitles")) {
+ option = SCAN_HTML_TITLES;
+ }
+ else if (!strcasecmp(w, "SuppressLastModified")) {
+ option = SUPPRESS_LAST_MOD;
+ }
+ else if (!strcasecmp(w, "SuppressSize")) {
+ option = SUPPRESS_SIZE;
+ }
+ else if (!strcasecmp(w, "SuppressDescription")) {
+ option = SUPPRESS_DESC;
+ }
+ else if (!strcasecmp(w, "SuppressHTMLPreamble")) {
+ option = SUPPRESS_PREAMBLE;
+ }
+ else if (!strcasecmp(w, "SuppressColumnSorting")) {
+ option = SUPPRESS_COLSORT;
+ }
+ else if (!strcasecmp(w, "None")) {
+ if (action != '\0') {
+ return "Cannot combine '+' or '-' with 'None' keyword";
+ }
+ opts = NO_OPTIONS;
+ opts_add = 0;
+ opts_remove = 0;
+ }
+ else if (!strcasecmp(w, "IconWidth")) {
+ if (action != '-') {
+ d_cfg->icon_width = DEFAULT_ICON_WIDTH;
+ }
+ else {
+ d_cfg->icon_width = 0;
+ }
+ }
+ else if (!strncasecmp(w, "IconWidth=", 10)) {
+ if (action == '-') {
+ return "Cannot combine '-' with IconWidth=n";
+ }
+ d_cfg->icon_width = atoi(&w[10]);
+ }
+ else if (!strcasecmp(w, "IconHeight")) {
+ if (action != '-') {
+ d_cfg->icon_height = DEFAULT_ICON_HEIGHT;
+ }
+ else {
+ d_cfg->icon_height = 0;
+ }
+ }
+ else if (!strncasecmp(w, "IconHeight=", 11)) {
+ if (action == '-') {
+ return "Cannot combine '-' with IconHeight=n";
+ }
+ d_cfg->icon_height = atoi(&w[11]);
+ }
+ else if (!strcasecmp(w, "NameWidth")) {
+ if (action != '-') {
+ return "NameWidth with no value may only appear as "
+ "'-NameWidth'";
+ }
+ d_cfg->name_width = DEFAULT_NAME_WIDTH;
+ d_cfg->name_adjust = K_NOADJUST;
+ }
+ else if (!strncasecmp(w, "NameWidth=", 10)) {
+ if (action == '-') {
+ return "Cannot combine '-' with NameWidth=n";
+ }
+ if (w[10] == '*') {
+ d_cfg->name_adjust = K_ADJUST;
+ }
+ else {
+ int width = atoi(&w[10]);
+
+ if (width < 5) {
+ return "NameWidth value must be greater than 5";
+ }
+ d_cfg->name_width = width;
+ d_cfg->name_adjust = K_NOADJUST;
+ }
+ }
+ else {
+ return "Invalid directory indexing option";
+ }
+ if (action == '\0') {
+ opts |= option;
+ opts_add = 0;
+ opts_remove = 0;
+ }
+ else if (action == '+') {
+ opts_add |= option;
+ opts_remove &= ~option;
+ }
+ else {
+ opts_remove |= option;
+ opts_add &= ~option;
+ }
+ }
+ if ((opts & NO_OPTIONS) && (opts & ~NO_OPTIONS)) {
+ return "Cannot combine other IndexOptions keywords with 'None'";
+ }
+ d_cfg->incremented_opts = opts_add;
+ d_cfg->decremented_opts = opts_remove;
+ d_cfg->opts = opts;
+ return NULL;
+}
+
+static const char *set_default_order(cmd_parms *cmd, void *m, char *direction,
+ char *key)
+{
+ char temp[4];
+ autoindex_config_rec *d_cfg = (autoindex_config_rec *) m;
+
+ ap_cpystrn(temp, "k=d", sizeof(temp));
+ if (!strcasecmp(direction, "Ascending")) {
+ temp[2] = D_ASCENDING;
+ }
+ else if (!strcasecmp(direction, "Descending")) {
+ temp[2] = D_DESCENDING;
+ }
+ else {
+ return "First keyword must be 'Ascending' or 'Descending'";
+ }
+
+ if (!strcasecmp(key, "Name")) {
+ temp[0] = K_NAME;
+ }
+ else if (!strcasecmp(key, "Date")) {
+ temp[0] = K_LAST_MOD;
+ }
+ else if (!strcasecmp(key, "Size")) {
+ temp[0] = K_SIZE;
+ }
+ else if (!strcasecmp(key, "Description")) {
+ temp[0] = K_DESC;
+ }
+ else {
+ return "Second keyword must be 'Name', 'Date', 'Size', or "
+ "'Description'";
+ }
+
+ if (d_cfg->default_order == NULL) {
+ d_cfg->default_order = ap_palloc(cmd->pool, 4);
+ d_cfg->default_order[3] = '\0';
+ }
+ ap_cpystrn(d_cfg->default_order, temp, sizeof(temp));
+ return NULL;
+}
+
+#define DIR_CMD_PERMS OR_INDEXES
+
+static const command_rec autoindex_cmds[] =
+{
+ {"AddIcon", add_icon, BY_PATH, DIR_CMD_PERMS, ITERATE2,
+ "an icon URL followed by one or more filenames"},
+ {"AddIconByType", add_icon, BY_TYPE, DIR_CMD_PERMS, ITERATE2,
+ "an icon URL followed by one or more MIME types"},
+ {"AddIconByEncoding", add_icon, BY_ENCODING, DIR_CMD_PERMS, ITERATE2,
+ "an icon URL followed by one or more content encodings"},
+ {"AddAlt", add_alt, BY_PATH, DIR_CMD_PERMS, ITERATE2,
+ "alternate descriptive text followed by one or more filenames"},
+ {"AddAltByType", add_alt, BY_TYPE, DIR_CMD_PERMS, ITERATE2,
+ "alternate descriptive text followed by one or more MIME types"},
+ {"AddAltByEncoding", add_alt, BY_ENCODING, DIR_CMD_PERMS, ITERATE2,
+ "alternate descriptive text followed by one or more content encodings"},
+ {"IndexOptions", add_opts, NULL, DIR_CMD_PERMS, RAW_ARGS,
+ "one or more index options"},
+ {"IndexOrderDefault", set_default_order, NULL, DIR_CMD_PERMS, TAKE2,
+ "{Ascending,Descending} {Name,Size,Description,Date}"},
+ {"IndexIgnore", add_ignore, NULL, DIR_CMD_PERMS, ITERATE,
+ "one or more file extensions"},
+ {"AddDescription", add_desc, BY_PATH, DIR_CMD_PERMS, ITERATE2,
+ "Descriptive text followed by one or more filenames"},
+ {"HeaderName", add_header, NULL, DIR_CMD_PERMS, TAKE1, "a filename"},
+ {"ReadmeName", add_readme, NULL, DIR_CMD_PERMS, TAKE1, "a filename"},
+ {"FancyIndexing", fancy_indexing, NULL, DIR_CMD_PERMS, FLAG,
+ "Limited to 'on' or 'off' (superseded by IndexOptions FancyIndexing)"},
+ {"DefaultIcon", ap_set_string_slot,
+ (void *) XtOffsetOf(autoindex_config_rec, default_icon),
+ DIR_CMD_PERMS, TAKE1, "an icon URL"},
+ {NULL}
+};
+
+static void *create_autoindex_config(pool *p, char *dummy)
+{
+ autoindex_config_rec *new =
+ (autoindex_config_rec *) ap_pcalloc(p, sizeof(autoindex_config_rec));
+
+ new->icon_width = 0;
+ new->icon_height = 0;
+ new->name_width = DEFAULT_NAME_WIDTH;
+ new->name_adjust = K_UNSET;
+ new->icon_list = ap_make_array(p, 4, sizeof(struct item));
+ new->alt_list = ap_make_array(p, 4, sizeof(struct item));
+ new->desc_list = ap_make_array(p, 4, sizeof(ai_desc_t));
+ new->ign_list = ap_make_array(p, 4, sizeof(struct item));
+ new->hdr_list = ap_make_array(p, 4, sizeof(struct item));
+ new->rdme_list = ap_make_array(p, 4, sizeof(struct item));
+ new->opts = 0;
+ new->incremented_opts = 0;
+ new->decremented_opts = 0;
+ new->default_order = NULL;
+
+ return (void *) new;
+}
+
+static void *merge_autoindex_configs(pool *p, void *basev, void *addv)
+{
+ autoindex_config_rec *new;
+ autoindex_config_rec *base = (autoindex_config_rec *) basev;
+ autoindex_config_rec *add = (autoindex_config_rec *) addv;
+
+ new = (autoindex_config_rec *) ap_pcalloc(p, sizeof(autoindex_config_rec));
+ new->default_icon = add->default_icon ? add->default_icon
+ : base->default_icon;
+ new->icon_height = add->icon_height ? add->icon_height : base->icon_height;
+ new->icon_width = add->icon_width ? add->icon_width : base->icon_width;
+
+ new->alt_list = ap_append_arrays(p, add->alt_list, base->alt_list);
+ new->ign_list = ap_append_arrays(p, add->ign_list, base->ign_list);
+ new->hdr_list = ap_append_arrays(p, add->hdr_list, base->hdr_list);
+ new->desc_list = ap_append_arrays(p, add->desc_list, base->desc_list);
+ new->icon_list = ap_append_arrays(p, add->icon_list, base->icon_list);
+ new->rdme_list = ap_append_arrays(p, add->rdme_list, base->rdme_list);
+ if (add->opts & NO_OPTIONS) {
+ /*
+ * If the current directory says 'no options' then we also
+ * clear any incremental mods from being inheritable further down.
+ */
+ new->opts = NO_OPTIONS;
+ new->incremented_opts = 0;
+ new->decremented_opts = 0;
+ }
+ else {
+ /*
+ * If there were any non-incremental options selected for
+ * this directory, they dominate and we don't inherit *anything.*
+ * Contrariwise, we *do* inherit if the only settings here are
+ * incremental ones.
+ */
+ if (add->opts == 0) {
+ new->incremented_opts = (base->incremented_opts
+ | add->incremented_opts)
+ & ~add->decremented_opts;
+ new->decremented_opts = (base->decremented_opts
+ | add->decremented_opts);
+ /*
+ * We may have incremental settings, so make sure we don't
+ * inadvertently inherit an IndexOptions None from above.
+ */
+ new->opts = (base->opts & ~NO_OPTIONS);
+ }
+ else {
+ /*
+ * There are local non-incremental settings, which clear
+ * all inheritance from above. They *are* the new base settings.
+ */
+ new->opts = add->opts;;
+ }
+ /*
+ * We're guaranteed that there'll be no overlap between
+ * the add-options and the remove-options.
+ */
+ new->opts |= new->incremented_opts;
+ new->opts &= ~new->decremented_opts;
+ }
+ /*
+ * Inherit the NameWidth settings if there aren't any specific to
+ * the new location; otherwise we'll end up using the defaults set in the
+ * config-rec creation routine.
+ */
+ if (add->name_adjust == K_UNSET) {
+ new->name_width = base->name_width;
+ new->name_adjust = base->name_adjust;
+ }
+ else {
+ new->name_width = add->name_width;
+ new->name_adjust = add->name_adjust;
+ }
+
+ new->default_order = (add->default_order != NULL)
+ ? add->default_order : base->default_order;
+ return new;
+}
+
+/****************************************************************
+ *
+ * Looking things up in config entries...
+ */
+
+/* Structure used to hold entries when we're actually building an index */
+
+struct ent {
+ char *name;
+ char *icon;
+ char *alt;
+ char *desc;
+ off_t size;
+ time_t lm;
+ struct ent *next;
+ int ascending;
+ char key;
+};
+
+static char *find_item(request_rec *r, array_header *list, int path_only)
+{
+ const char *content_type = r->content_type;
+ const char *content_encoding = r->content_encoding;
+ char *path = r->filename;
+
+ struct item *items = (struct item *) list->elts;
+ int i;
+
+ for (i = 0; i < list->nelts; ++i) {
+ struct item *p = &items[i];
+
+ /* Special cased for ^^DIRECTORY^^ and ^^BLANKICON^^ */
+ if ((path[0] == '^') || (!ap_strcmp_match(path, p->apply_path))) {
+ if (!*(p->apply_to)) {
+ return p->data;
+ }
+ else if (p->type == BY_PATH || path[0] == '^') {
+ if (!ap_strcmp_match(path, p->apply_to)) {
+ return p->data;
+ }
+ }
+ else if (!path_only) {
+ if (!content_encoding) {
+ if (p->type == BY_TYPE) {
+ if (content_type
+ && !ap_strcasecmp_match(content_type,
+ p->apply_to)) {
+ return p->data;
+ }
+ }
+ }
+ else {
+ if (p->type == BY_ENCODING) {
+ if (!ap_strcasecmp_match(content_encoding,
+ p->apply_to)) {
+ return p->data;
+ }
+ }
+ }
+ }
+ }
+ }
+ return NULL;
+}
+
+#define find_icon(d,p,t) find_item(p,d->icon_list,t)
+#define find_alt(d,p,t) find_item(p,d->alt_list,t)
+#define find_header(d,p) find_item(p,d->hdr_list,0)
+#define find_readme(d,p) find_item(p,d->rdme_list,0)
+
+static char *find_default_icon(autoindex_config_rec *d, char *bogus_name)
+{
+ request_rec r;
+
+ /* Bleah. I tried to clean up find_item, and it lead to this bit
+ * of ugliness. Note that the fields initialized are precisely
+ * those that find_item looks at...
+ */
+
+ r.filename = bogus_name;
+ r.content_type = r.content_encoding = NULL;
+
+ return find_item(&r, d->icon_list, 1);
+}
+
+/*
+ * Look through the list of pattern/description pairs and return the first one
+ * if any) that matches the filename in the request. If multiple patterns
+ * match, only the first one is used; since the order in the array is the
+ * same as the order in which directives were processed, earlier matching
+ * directives will dominate.
+ */
+
+#ifdef CASE_BLIND_FILESYSTEM
+#define MATCH_FLAGS FNM_CASE_BLIND
+#else
+#define MATCH_FLAGS 0
+#endif
+
+static char *find_desc(autoindex_config_rec *dcfg, request_rec *r)
+{
+ int i;
+ ai_desc_t *list = (ai_desc_t *) dcfg->desc_list->elts;
+ const char *filename_full = r->filename;
+ const char *filename_only;
+ const char *filename;
+
+ /*
+ * If the filename includes a path, extract just the name itself
+ * for the simple matches.
+ */
+ if ((filename_only = strrchr(filename_full, '/')) == NULL) {
+ filename_only = filename_full;
+ }
+ else {
+ filename_only++;
+ }
+ for (i = 0; i < dcfg->desc_list->nelts; ++i) {
+ ai_desc_t *tuple = &list[i];
+ int found;
+
+ /*
+ * Only use the full-path filename if the pattern contains '/'s.
+ */
+ filename = (tuple->full_path) ? filename_full : filename_only;
+ /*
+ * Make the comparison using the cheapest method; only do
+ * wildcard checking if we must.
+ */
+ if (tuple->wildcards) {
+ found = (ap_fnmatch(tuple->pattern, filename, MATCH_FLAGS) == 0);
+ }
+ else {
+ found = (strstr(filename, tuple->pattern) != NULL);
+ }
+ if (found) {
+ return tuple->description;
+ }
+ }
+ return NULL;
+}
+
+static int ignore_entry(autoindex_config_rec *d, char *path)
+{
+ array_header *list = d->ign_list;
+ struct item *items = (struct item *) list->elts;
+ char *tt;
+ int i;
+
+ if ((tt = strrchr(path, '/')) == NULL) {
+ tt = path;
+ }
+ else {
+ tt++;
+ }
+
+ for (i = 0; i < list->nelts; ++i) {
+ struct item *p = &items[i];
+ char *ap;
+
+ if ((ap = strrchr(p->apply_to, '/')) == NULL) {
+ ap = p->apply_to;
+ }
+ else {
+ ap++;
+ }
+
+#ifndef CASE_BLIND_FILESYSTEM
+ if (!ap_strcmp_match(path, p->apply_path)
+ && !ap_strcmp_match(tt, ap)) {
+ return 1;
+ }
+#else /* !CASE_BLIND_FILESYSTEM */
+ /*
+ * On some platforms, the match must be case-blind. This is really
+ * a factor of the filesystem involved, but we can't detect that
+ * reliably - so we have to granularise at the OS level.
+ */
+ if (!ap_strcasecmp_match(path, p->apply_path)
+ && !ap_strcasecmp_match(tt, ap)) {
+ return 1;
+ }
+#endif /* !CASE_BLIND_FILESYSTEM */
+ }
+ return 0;
+}
+
+/*****************************************************************
+ *
+ * Actually generating output
+ */
+
+/*
+ * Elements of the emitted document:
+ * Preamble
+ * Emitted unless SUPPRESS_PREAMBLE is set AND ap_run_sub_req
+ * succeeds for the (content_type == text/html) header file.
+ * Header file
+ * Emitted if found (and able).
+ * H1 tag line
+ * Emitted if a header file is NOT emitted.
+ * Directory stuff
+ * Always emitted.
+ * HR
+ * Emitted if FANCY_INDEXING is set.
+ * Readme file
+ * Emitted if found (and able).
+ * ServerSig
+ * Emitted if ServerSignature is not Off AND a readme file
+ * is NOT emitted.
+ * Postamble
+ * Emitted unless SUPPRESS_PREAMBLE is set AND ap_run_sub_req
+ * succeeds for the (content_type == text/html) readme file.
+ */
+
+
+/*
+ * emit a plain text file
+ */
+static void do_emit_plain(request_rec *r, FILE *f)
+{
+ char buf[IOBUFSIZE + 1];
+ int i, n, c, ch;
+
+ ap_rputs("\n", r);
+ while (!feof(f)) {
+ do {
+ n = fread(buf, sizeof(char), IOBUFSIZE, f);
+ }
+ while (n == -1 && ferror(f) && errno == EINTR);
+ if (n == -1 || n == 0) {
+ break;
+ }
+ buf[n] = '\0';
+ c = 0;
+ while (c < n) {
+ for (i = c; i < n; i++) {
+ if (buf[i] == '<' || buf[i] == '>' || buf[i] == '&') {
+ break;
+ }
+ }
+ ch = buf[i];
+ buf[i] = '\0';
+ ap_rputs(&buf[c], r);
+ if (ch == '<') {
+ ap_rputs("<", r);
+ }
+ else if (ch == '>') {
+ ap_rputs(">", r);
+ }
+ else if (ch == '&') {
+ ap_rputs("&", r);
+ }
+ c = i + 1;
+ }
+ }
+ ap_rputs(" \n", r);
+}
+
+/*
+ * Handle the preamble through the H1 tag line, inclusive. Locate
+ * the file with a subrequests. Process text/html documents by actually
+ * running the subrequest; text/xxx documents get copied verbatim,
+ * and any other content type is ignored. This means that a non-text
+ * document (such as HEADER.gif) might get multiviewed as the result
+ * instead of a text document, meaning nothing will be displayed, but
+ * oh well.
+ */
+static void emit_head(request_rec *r, char *header_fname, int suppress_amble,
+ char *title)
+{
+ FILE *f;
+ request_rec *rr = NULL;
+ int emit_amble = 1;
+ int emit_H1 = 1;
+
+ /*
+ * If there's a header file, send a subrequest to look for it. If it's
+ * found and a text file, handle it -- otherwise fall through and
+ * pretend there's nothing there.
+ */
+ if ((header_fname != NULL)
+ && (rr = ap_sub_req_lookup_uri(header_fname, r))
+ && (rr->status == HTTP_OK)
+ && (rr->filename != NULL)
+ && S_ISREG(rr->finfo.st_mode)) {
+ /*
+ * Check for the two specific cases we allow: text/html and
+ * text/anything-else. The former is allowed to be processed for
+ * SSIs.
+ */
+ if (rr->content_type != NULL) {
+ if (!strcasecmp(ap_field_noparam(r->pool, rr->content_type),
+ "text/html")) {
+ /* Hope everything will work... */
+ emit_amble = 0;
+ emit_H1 = 0;
+
+ if (! suppress_amble) {
+ emit_preamble(r, title);
+ }
+ /*
+ * If there's a problem running the subrequest, display the
+ * preamble if we didn't do it before -- the header file
+ * didn't get displayed.
+ */
+ if (ap_run_sub_req(rr) != OK) {
+ /* It didn't work */
+ emit_amble = suppress_amble;
+ emit_H1 = 1;
+ }
+ }
+ else if (!strncasecmp("text/", rr->content_type, 5)) {
+ /*
+ * If we can open the file, prefix it with the preamble
+ * regardless; since we'll be sending a block around
+ * the file's contents, any HTML header it had won't end up
+ * where it belongs.
+ */
+ if ((f = ap_pfopen(r->pool, rr->filename, "r")) != 0) {
+ emit_preamble(r, title);
+ emit_amble = 0;
+ do_emit_plain(r, f);
+ ap_pfclose(r->pool, f);
+ emit_H1 = 0;
+ }
+ }
+ }
+ }
+
+ if (emit_amble) {
+ emit_preamble(r, title);
+ }
+ if (emit_H1) {
+ ap_rvputs(r, "Index of ", title, "\n", NULL);
+ }
+ if (rr != NULL) {
+ ap_destroy_sub_req(rr);
+ }
+}
+
+
+/*
+ * Handle the Readme file through the postamble, inclusive. Locate
+ * the file with a subrequests. Process text/html documents by actually
+ * running the subrequest; text/xxx documents get copied verbatim,
+ * and any other content type is ignored. This means that a non-text
+ * document (such as FOOTER.gif) might get multiviewed as the result
+ * instead of a text document, meaning nothing will be displayed, but
+ * oh well.
+ */
+static void emit_tail(request_rec *r, char *readme_fname, int suppress_amble)
+{
+ FILE *f;
+ request_rec *rr = NULL;
+ int suppress_post = 0;
+ int suppress_sig = 0;
+
+ /*
+ * If there's a readme file, send a subrequest to look for it. If it's
+ * found and a text file, handle it -- otherwise fall through and
+ * pretend there's nothing there.
+ */
+ if ((readme_fname != NULL)
+ && (rr = ap_sub_req_lookup_uri(readme_fname, r))
+ && (rr->status == HTTP_OK)
+ && (rr->filename != NULL)
+ && S_ISREG(rr->finfo.st_mode)) {
+ /*
+ * Check for the two specific cases we allow: text/html and
+ * text/anything-else. The former is allowed to be processed for
+ * SSIs.
+ */
+ if (rr->content_type != NULL) {
+ if (!strcasecmp(ap_field_noparam(r->pool, rr->content_type),
+ "text/html")) {
+ if (ap_run_sub_req(rr) == OK) {
+ /* worked... */
+ suppress_sig = 1;
+ suppress_post = suppress_amble;
+ }
+ }
+ else if (!strncasecmp("text/", rr->content_type, 5)) {
+ /*
+ * If we can open the file, suppress the signature.
+ */
+ if ((f = ap_pfopen(r->pool, rr->filename, "r")) != 0) {
+ do_emit_plain(r, f);
+ ap_pfclose(r->pool, f);
+ suppress_sig = 1;
+ }
+ }
+ }
+ }
+
+ if (!suppress_sig) {
+ ap_rputs(ap_psignature("", r), r);
+ }
+ if (!suppress_post) {
+ ap_rputs("\n", r);
+ }
+ if (rr != NULL) {
+ ap_destroy_sub_req(rr);
+ }
+}
+
+
+static char *find_title(request_rec *r)
+{
+ char titlebuf[MAX_STRING_LEN], *find = "";
+ FILE *thefile = NULL;
+ int x, y, n, p;
+
+ if (r->status != HTTP_OK) {
+ return NULL;
+ }
+ if ((r->content_type != NULL)
+ && (!strcasecmp(ap_field_noparam(r->pool, r->content_type),
+ "text/html")
+ || !strcmp(r->content_type, INCLUDES_MAGIC_TYPE))
+ && !r->content_encoding) {
+ if (!(thefile = ap_pfopen(r->pool, r->filename, "r"))) {
+ return NULL;
+ }
+ n = fread(titlebuf, sizeof(char), MAX_STRING_LEN - 1, thefile);
+ if (n <= 0) {
+ ap_pfclose(r->pool, thefile);
+ return NULL;
+ }
+ titlebuf[n] = '\0';
+ for (x = 0, p = 0; titlebuf[x]; x++) {
+ if (ap_toupper(titlebuf[x]) == find[p]) {
+ if (!find[++p]) {
+ if ((p = ap_ind(&titlebuf[++x], '<')) != -1) {
+ titlebuf[x + p] = '\0';
+ }
+ /* Scan for line breaks for Tanmoy's secretary */
+ for (y = x; titlebuf[y]; y++) {
+ if ((titlebuf[y] == CR) || (titlebuf[y] == LF)) {
+ if (y == x) {
+ x++;
+ }
+ else {
+ titlebuf[y] = ' ';
+ }
+ }
+ }
+ ap_pfclose(r->pool, thefile);
+ return ap_pstrdup(r->pool, &titlebuf[x]);
+ }
+ }
+ else {
+ p = 0;
+ }
+ }
+ ap_pfclose(r->pool, thefile);
+ }
+ return NULL;
+}
+
+static struct ent *make_autoindex_entry(char *name, int autoindex_opts,
+ autoindex_config_rec *d,
+ request_rec *r, char keyid,
+ char direction)
+{
+ struct ent *p;
+
+ if ((name[0] == '.') && (!name[1])) {
+ return (NULL);
+ }
+
+ if (ignore_entry(d, ap_make_full_path(r->pool, r->filename, name))) {
+ return (NULL);
+ }
+
+ p = (struct ent *) ap_pcalloc(r->pool, sizeof(struct ent));
+ p->name = ap_pstrdup(r->pool, name);
+ p->size = -1;
+ p->icon = NULL;
+ p->alt = NULL;
+ p->desc = NULL;
+ p->lm = -1;
+ p->key = ap_toupper(keyid);
+ p->ascending = (ap_toupper(direction) == D_ASCENDING);
+
+ if (autoindex_opts & FANCY_INDEXING) {
+ request_rec *rr = ap_sub_req_lookup_file(name, r);
+
+ if (rr->finfo.st_mode != 0) {
+ p->lm = rr->finfo.st_mtime;
+ if (S_ISDIR(rr->finfo.st_mode)) {
+ if (!(p->icon = find_icon(d, rr, 1))) {
+ p->icon = find_default_icon(d, "^^DIRECTORY^^");
+ }
+ if (!(p->alt = find_alt(d, rr, 1))) {
+ p->alt = "DIR";
+ }
+ p->size = -1;
+ p->name = ap_pstrcat(r->pool, name, "/", NULL);
+ }
+ else {
+ p->icon = find_icon(d, rr, 0);
+ p->alt = find_alt(d, rr, 0);
+ p->size = rr->finfo.st_size;
+ }
+ }
+
+ p->desc = find_desc(d, rr);
+
+ if ((!p->desc) && (autoindex_opts & SCAN_HTML_TITLES)) {
+ p->desc = ap_pstrdup(r->pool, find_title(rr));
+ }
+
+ ap_destroy_sub_req(rr);
+ }
+ /*
+ * We don't need to take any special action for the file size key. If
+ * we did, it would go here.
+ */
+ if (keyid == K_LAST_MOD) {
+ if (p->lm < 0) {
+ p->lm = 0;
+ }
+ }
+ return (p);
+}
+
+static char *terminate_description(autoindex_config_rec *d, char *desc,
+ int autoindex_opts)
+{
+ int maxsize = 23;
+ register int x;
+
+ if (autoindex_opts & SUPPRESS_LAST_MOD) {
+ maxsize += 19;
+ }
+ if (autoindex_opts & SUPPRESS_SIZE) {
+ maxsize += 7;
+ }
+
+ for (x = 0; desc[x] && (maxsize > 0 || desc[x]=='<'); x++) {
+ if (desc[x] == '<') {
+ while (desc[x] != '>') {
+ if (!desc[x]) {
+ maxsize = 0;
+ break;
+ }
+ ++x;
+ }
+ }
+ else if (desc[x] == '&') {
+ /* entities like ä count as one character */
+ --maxsize;
+ for ( ; desc[x] != ';'; ++x) {
+ if (desc[x] == '\0') {
+ maxsize = 0;
+ break;
+ }
+ }
+ }
+ else {
+ --maxsize;
+ }
+ }
+ if (!maxsize && desc[x] != '\0') {
+ desc[x - 1] = '>'; /* Grump. */
+ desc[x] = '\0'; /* Double Grump! */
+ }
+ return desc;
+}
+
+/*
+ * Emit the anchor for the specified field. If a field is the key for the
+ * current request, the link changes its meaning to reverse the order when
+ * selected again. Non-active fields always start in ascending order.
+ */
+static void emit_link(request_rec *r, char *anchor, char fname, char curkey,
+ char curdirection, int nosort)
+{
+ char qvalue[5];
+ int reverse;
+
+ if (!nosort) {
+ qvalue[0] = '?';
+ qvalue[1] = fname;
+ qvalue[2] = '=';
+ qvalue[4] = '\0';
+ reverse = ((curkey == fname) && (curdirection == D_ASCENDING));
+ qvalue[3] = reverse ? D_DESCENDING : D_ASCENDING;
+ ap_rvputs(r, "", anchor, "", NULL);
+ }
+ else {
+ ap_rputs(anchor, r);
+ }
+}
+
+static void output_directories(struct ent **ar, int n,
+ autoindex_config_rec *d, request_rec *r,
+ int autoindex_opts, char keyid, char direction)
+{
+ int x;
+ char *name = r->uri;
+ char *tp;
+ int static_columns = (autoindex_opts & SUPPRESS_COLSORT);
+ pool *scratch = ap_make_sub_pool(r->pool);
+ int name_width;
+ char *name_scratch;
+ char *pad_scratch;
+
+ if (name[0] == '\0') {
+ name = "/";
+ }
+
+ name_width = d->name_width;
+ if (d->name_adjust == K_ADJUST) {
+ for (x = 0; x < n; x++) {
+ int t = strlen(ar[x]->name);
+ if (t > name_width) {
+ name_width = t;
+ }
+ }
+ }
+ name_scratch = ap_palloc(r->pool, name_width + 1);
+ pad_scratch = ap_palloc(r->pool, name_width + 1);
+ memset(pad_scratch, ' ', name_width);
+ pad_scratch[name_width] = '\0';
+
+ if (autoindex_opts & FANCY_INDEXING) {
+ ap_rputs("", r);
+ if ((tp = find_default_icon(d, "^^BLANKICON^^"))) {
+ ap_rvputs(r, " icon_width && d->icon_height) {
+ ap_rprintf
+ (
+ r,
+ " HEIGHT=\"%d\" WIDTH=\"%d\"",
+ d->icon_height,
+ d->icon_width
+ );
+ }
+ ap_rputs("> ", r);
+ }
+ emit_link(r, "Name", K_NAME, keyid, direction, static_columns);
+ ap_rputs(pad_scratch + 4, r);
+ /*
+ * Emit the guaranteed-at-least-one-space-between-columns byte.
+ */
+ ap_rputs(" ", r);
+ if (!(autoindex_opts & SUPPRESS_LAST_MOD)) {
+ emit_link(r, "Last modified", K_LAST_MOD, keyid, direction,
+ static_columns);
+ ap_rputs(" ", r);
+ }
+ if (!(autoindex_opts & SUPPRESS_SIZE)) {
+ emit_link(r, "Size", K_SIZE, keyid, direction, static_columns);
+ ap_rputs(" ", r);
+ }
+ if (!(autoindex_opts & SUPPRESS_DESC)) {
+ emit_link(r, "Description", K_DESC, keyid, direction,
+ static_columns);
+ }
+ ap_rputs("\n \n", r);
+ }
+ else {
+ ap_rputs(" ", r);
+ }
+
+ for (x = 0; x < n; x++) {
+ char *anchor, *t, *t2;
+ int nwidth;
+
+ ap_clear_pool(scratch);
+
+ if (is_parent(ar[x]->name)) {
+ t = ap_make_full_path(scratch, name, "../");
+ ap_getparents(t);
+ if (t[0] == '\0') {
+ t = "/";
+ }
+ t2 = "Parent Directory";
+ anchor = ap_escape_html(scratch, ap_os_escape_path(scratch, t, 0));
+ }
+ else {
+ t = ar[x]->name;
+ t2 = t;
+ anchor = ap_escape_html(scratch, ap_os_escape_path(scratch, t, 0));
+ }
+
+ if (autoindex_opts & FANCY_INDEXING) {
+ if (autoindex_opts & ICONS_ARE_LINKS) {
+ ap_rvputs(r, "", NULL);
+ }
+ if ((ar[x]->icon) || d->default_icon) {
+ ap_rvputs(r, " icon ? ar[x]->icon
+ : d->default_icon),
+ "\" ALT=\"[", (ar[x]->alt ? ar[x]->alt : " "),
+ "]\"", NULL);
+ if (d->icon_width && d->icon_height) {
+ ap_rprintf(r, " HEIGHT=\"%d\" WIDTH=\"%d\"",
+ d->icon_height, d->icon_width);
+ }
+ ap_rputs(">", r);
+ }
+ if (autoindex_opts & ICONS_ARE_LINKS) {
+ ap_rputs("", r);
+ }
+
+ nwidth = strlen(t2);
+ if (nwidth > name_width) {
+ memcpy(name_scratch, t2, name_width - 3);
+ name_scratch[name_width - 3] = '.';
+ name_scratch[name_width - 2] = '.';
+ name_scratch[name_width - 1] = '>';
+ name_scratch[name_width] = 0;
+ t2 = name_scratch;
+ nwidth = name_width;
+ }
+ ap_rvputs(r, " ",
+ ap_escape_html(scratch, t2), "", pad_scratch + nwidth,
+ NULL);
+ /*
+ * The blank before the storm.. er, before the next field.
+ */
+ ap_rputs(" ", r);
+ if (!(autoindex_opts & SUPPRESS_LAST_MOD)) {
+ if (ar[x]->lm != -1) {
+ char time_str[MAX_STRING_LEN];
+ struct tm *ts = localtime(&ar[x]->lm);
+ strftime(time_str, MAX_STRING_LEN, "%d-%b-%Y %H:%M ", ts);
+ ap_rputs(time_str, r);
+ }
+ else {
+ /*Length="22-Feb-1998 23:42 " (see 4 lines above) */
+ ap_rputs(" ", r);
+ }
+ }
+ if (!(autoindex_opts & SUPPRESS_SIZE)) {
+ ap_send_size(ar[x]->size, r);
+ ap_rputs(" ", r);
+ }
+ if (!(autoindex_opts & SUPPRESS_DESC)) {
+ if (ar[x]->desc) {
+ ap_rputs(terminate_description(d, ar[x]->desc,
+ autoindex_opts), r);
+ }
+ }
+ }
+ else {
+ ap_rvputs(r, "- ", t2,
+ "", NULL);
+ }
+ ap_rputc('\n', r);
+ }
+ if (autoindex_opts & FANCY_INDEXING) {
+ ap_rputs("
", r);
+ }
+ else {
+ ap_rputs("", r);
+ }
+}
+
+/*
+ * Compare two file entries according to the sort criteria. The return
+ * is essentially a signum function value.
+ */
+
+static int dsortf(struct ent **e1, struct ent **e2)
+{
+ struct ent *c1;
+ struct ent *c2;
+ int result = 0;
+
+ /*
+ * First, see if either of the entries is for the parent directory.
+ * If so, that *always* sorts lower than anything else.
+ */
+ if (is_parent((*e1)->name)) {
+ return -1;
+ }
+ if (is_parent((*e2)->name)) {
+ return 1;
+ }
+ /*
+ * All of our comparisons will be of the c1 entry against the c2 one,
+ * so assign them appropriately to take care of the ordering.
+ */
+ if ((*e1)->ascending) {
+ c1 = *e1;
+ c2 = *e2;
+ }
+ else {
+ c1 = *e2;
+ c2 = *e1;
+ }
+ switch (c1->key) {
+ case K_LAST_MOD:
+ if (c1->lm > c2->lm) {
+ return 1;
+ }
+ else if (c1->lm < c2->lm) {
+ return -1;
+ }
+ break;
+ case K_SIZE:
+ if (c1->size > c2->size) {
+ return 1;
+ }
+ else if (c1->size < c2->size) {
+ return -1;
+ }
+ break;
+ case K_DESC:
+ result = strcmp(c1->desc ? c1->desc : "", c2->desc ? c2->desc : "");
+ if (result) {
+ return result;
+ }
+ break;
+ }
+ return strcmp(c1->name, c2->name);
+}
+
+
+static int index_directory(request_rec *r,
+ autoindex_config_rec *autoindex_conf)
+{
+ char *title_name = ap_escape_html(r->pool, r->uri);
+ char *title_endp;
+ char *name = r->filename;
+
+ DIR *d;
+ struct DIR_TYPE *dstruct;
+ int num_ent = 0, x;
+ struct ent *head, *p;
+ struct ent **ar = NULL;
+ const char *qstring;
+ int autoindex_opts = autoindex_conf->opts;
+ char keyid;
+ char direction;
+
+ if (!(d = ap_popendir(r->pool, name))) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
+ "Can't open directory for index: %s", r->filename);
+ return HTTP_FORBIDDEN;
+ }
+
+ r->content_type = "text/html";
+
+ ap_send_http_header(r);
+
+ if (r->header_only) {
+ ap_pclosedir(r->pool, d);
+ return 0;
+ }
+ ap_hard_timeout("send directory", r);
+
+ /* Spew HTML preamble */
+
+ title_endp = title_name + strlen(title_name) - 1;
+
+ while (title_endp > title_name && *title_endp == '/') {
+ *title_endp-- = '\0';
+ }
+
+ emit_head(r, find_header(autoindex_conf, r),
+ autoindex_opts & SUPPRESS_PREAMBLE, title_name);
+
+ /*
+ * Figure out what sort of indexing (if any) we're supposed to use.
+ *
+ * If no QUERY_STRING was specified or column sorting has been
+ * explicitly disabled, we use the default specified by the
+ * IndexOrderDefault directive (if there is one); otherwise,
+ * we fall back to ascending by name.
+ */
+ qstring = r->args;
+ if ((autoindex_opts & SUPPRESS_COLSORT)
+ || ((qstring == NULL) || (*qstring == '\0'))) {
+ qstring = autoindex_conf->default_order;
+ }
+ /*
+ * If there is no specific ordering defined for this directory,
+ * default to ascending by filename.
+ */
+ if ((qstring == NULL) || (*qstring == '\0')) {
+ keyid = K_NAME;
+ direction = D_ASCENDING;
+ }
+ else {
+ keyid = *qstring;
+ ap_getword(r->pool, &qstring, '=');
+ if (qstring != '\0') {
+ direction = *qstring;
+ }
+ else {
+ direction = D_ASCENDING;
+ }
+ }
+
+ /*
+ * Since we don't know how many dir. entries there are, put them into a
+ * linked list and then arrayificate them so qsort can use them.
+ */
+ head = NULL;
+ while ((dstruct = readdir(d))) {
+ p = make_autoindex_entry(dstruct->d_name, autoindex_opts,
+ autoindex_conf, r, keyid, direction);
+ if (p != NULL) {
+ p->next = head;
+ head = p;
+ num_ent++;
+ }
+ }
+ if (num_ent > 0) {
+ ar = (struct ent **) ap_palloc(r->pool,
+ num_ent * sizeof(struct ent *));
+ p = head;
+ x = 0;
+ while (p) {
+ ar[x++] = p;
+ p = p->next;
+ }
+
+ qsort((void *) ar, num_ent, sizeof(struct ent *),
+ (int (*)(const void *, const void *)) dsortf);
+ }
+ output_directories(ar, num_ent, autoindex_conf, r, autoindex_opts, keyid,
+ direction);
+ ap_pclosedir(r->pool, d);
+
+ if (autoindex_opts & FANCY_INDEXING) {
+ ap_rputs(" \n", r);
+ }
+ emit_tail(r, find_readme(autoindex_conf, r),
+ autoindex_opts & SUPPRESS_PREAMBLE);
+
+ ap_kill_timeout(r);
+ return 0;
+}
+
+/* The formal handler... */
+
+static int handle_autoindex(request_rec *r)
+{
+ autoindex_config_rec *d;
+ int allow_opts = ap_allow_options(r);
+
+ d = (autoindex_config_rec *) ap_get_module_config(r->per_dir_config,
+ &autoindex_module);
+
+ r->allowed |= (1 << M_GET);
+ if (r->method_number != M_GET) {
+ return DECLINED;
+ }
+
+ /* OK, nothing easy. Trot out the heavy artillery... */
+
+ if (allow_opts & OPT_INDEXES) {
+ /* KLUDGE --- make the sub_req lookups happen in the right directory.
+ * Fixing this in the sub_req_lookup functions themselves is difficult,
+ * and would probably break virtual includes...
+ */
+
+ if (r->filename[strlen(r->filename) - 1] != '/') {
+ r->filename = ap_pstrcat(r->pool, r->filename, "/", NULL);
+ }
+ return index_directory(r, d);
+ }
+ else {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Directory index forbidden by rule: %s", r->filename);
+ return HTTP_FORBIDDEN;
+ }
+}
+
+
+static const handler_rec autoindex_handlers[] =
+{
+ {DIR_MAGIC_TYPE, handle_autoindex},
+ {NULL}
+};
+
+module MODULE_VAR_EXPORT autoindex_module =
+{
+ STANDARD_MODULE_STUFF,
+ NULL, /* initializer */
+ create_autoindex_config, /* dir config creater */
+ merge_autoindex_configs, /* dir merger --- default is to override */
+ NULL, /* server config */
+ NULL, /* merge server config */
+ autoindex_cmds, /* command table */
+ autoindex_handlers, /* handlers */
+ NULL, /* filename translation */
+ NULL, /* check_user_id */
+ NULL, /* check auth */
+ NULL, /* check access */
+ NULL, /* type_checker */
+ NULL, /* fixups */
+ NULL, /* logger */
+ NULL, /* header parser */
+ NULL, /* child_init */
+ NULL, /* child_exit */
+ NULL /* post read-request */
+};
diff --git a/modules/generators/mod_cgi.c b/modules/generators/mod_cgi.c
new file mode 100644
index 00000000000..392fb5a1f13
--- /dev/null
+++ b/modules/generators/mod_cgi.c
@@ -0,0 +1,609 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+/*
+ * http_script: keeps all script-related ramblings together.
+ *
+ * Compliant to CGI/1.1 spec
+ *
+ * Adapted by rst from original NCSA code by Rob McCool
+ *
+ * Apache adds some new env vars; REDIRECT_URL and REDIRECT_QUERY_STRING for
+ * custom error responses, and DOCUMENT_ROOT because we found it useful.
+ * It also adds SERVER_ADMIN - useful for scripts to know who to mail when
+ * they fail.
+ */
+
+#include "httpd.h"
+#include "http_config.h"
+#include "http_request.h"
+#include "http_core.h"
+#include "http_protocol.h"
+#include "http_main.h"
+#include "http_log.h"
+#include "util_script.h"
+#include "http_conf_globals.h"
+
+module MODULE_VAR_EXPORT cgi_module;
+
+/* KLUDGE --- for back-combatibility, we don't have to check ExecCGI
+ * in ScriptAliased directories, which means we need to know if this
+ * request came through ScriptAlias or not... so the Alias module
+ * leaves a note for us.
+ */
+
+static int is_scriptaliased(request_rec *r)
+{
+ const char *t = ap_table_get(r->notes, "alias-forced-type");
+ return t && (!strcasecmp(t, "cgi-script"));
+}
+
+/* Configuration stuff */
+
+#define DEFAULT_LOGBYTES 10385760
+#define DEFAULT_BUFBYTES 1024
+
+typedef struct {
+ char *logname;
+ long logbytes;
+ int bufbytes;
+} cgi_server_conf;
+
+static void *create_cgi_config(pool *p, server_rec *s)
+{
+ cgi_server_conf *c =
+ (cgi_server_conf *) ap_pcalloc(p, sizeof(cgi_server_conf));
+
+ c->logname = NULL;
+ c->logbytes = DEFAULT_LOGBYTES;
+ c->bufbytes = DEFAULT_BUFBYTES;
+
+ return c;
+}
+
+static void *merge_cgi_config(pool *p, void *basev, void *overridesv)
+{
+ cgi_server_conf *base = (cgi_server_conf *) basev, *overrides = (cgi_server_conf *) overridesv;
+
+ return overrides->logname ? overrides : base;
+}
+
+static const char *set_scriptlog(cmd_parms *cmd, void *dummy, char *arg)
+{
+ server_rec *s = cmd->server;
+ cgi_server_conf *conf =
+ (cgi_server_conf *) ap_get_module_config(s->module_config, &cgi_module);
+
+ conf->logname = arg;
+ return NULL;
+}
+
+static const char *set_scriptlog_length(cmd_parms *cmd, void *dummy, char *arg)
+{
+ server_rec *s = cmd->server;
+ cgi_server_conf *conf =
+ (cgi_server_conf *) ap_get_module_config(s->module_config, &cgi_module);
+
+ conf->logbytes = atol(arg);
+ return NULL;
+}
+
+static const char *set_scriptlog_buffer(cmd_parms *cmd, void *dummy, char *arg)
+{
+ server_rec *s = cmd->server;
+ cgi_server_conf *conf =
+ (cgi_server_conf *) ap_get_module_config(s->module_config, &cgi_module);
+
+ conf->bufbytes = atoi(arg);
+ return NULL;
+}
+
+static const command_rec cgi_cmds[] =
+{
+ {"ScriptLog", set_scriptlog, NULL, RSRC_CONF, TAKE1,
+ "the name of a log for script debugging info"},
+ {"ScriptLogLength", set_scriptlog_length, NULL, RSRC_CONF, TAKE1,
+ "the maximum length (in bytes) of the script debug log"},
+ {"ScriptLogBuffer", set_scriptlog_buffer, NULL, RSRC_CONF, TAKE1,
+ "the maximum size (in bytes) to record of a POST request"},
+ {NULL}
+};
+
+static int log_scripterror(request_rec *r, cgi_server_conf * conf, int ret,
+ int show_errno, char *error)
+{
+ FILE *f;
+ struct stat finfo;
+
+ ap_log_rerror(APLOG_MARK, show_errno|APLOG_ERR, r,
+ "%s: %s", error, r->filename);
+
+ if (!conf->logname ||
+ ((stat(ap_server_root_relative(r->pool, conf->logname), &finfo) == 0)
+ && (finfo.st_size > conf->logbytes)) ||
+ ((f = ap_pfopen(r->pool, ap_server_root_relative(r->pool, conf->logname),
+ "a")) == NULL)) {
+ return ret;
+ }
+
+ /* "%% [Wed Jun 19 10:53:21 1996] GET /cgi-bin/printenv HTTP/1.0" */
+ fprintf(f, "%%%% [%s] %s %s%s%s %s\n", ap_get_time(), r->method, r->uri,
+ r->args ? "?" : "", r->args ? r->args : "", r->protocol);
+ /* "%% 500 /usr/local/apache/cgi-bin */
+ fprintf(f, "%%%% %d %s\n", ret, r->filename);
+
+ fprintf(f, "%%error\n%s\n", error);
+
+ ap_pfclose(r->pool, f);
+ return ret;
+}
+
+static int log_script(request_rec *r, cgi_server_conf * conf, int ret,
+ char *dbuf, const char *sbuf, BUFF *script_in, BUFF *script_err)
+{
+ array_header *hdrs_arr = ap_table_elts(r->headers_in);
+ table_entry *hdrs = (table_entry *) hdrs_arr->elts;
+ char argsbuffer[HUGE_STRING_LEN];
+ FILE *f;
+ int i;
+ struct stat finfo;
+
+ if (!conf->logname ||
+ ((stat(ap_server_root_relative(r->pool, conf->logname), &finfo) == 0)
+ && (finfo.st_size > conf->logbytes)) ||
+ ((f = ap_pfopen(r->pool, ap_server_root_relative(r->pool, conf->logname),
+ "a")) == NULL)) {
+ /* Soak up script output */
+ while (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_in) > 0)
+ continue;
+#ifdef WIN32
+ /* Soak up stderr and redirect it to the error log.
+ * Script output to stderr is already directed to the error log
+ * on Unix, thanks to the magic of fork().
+ */
+ while (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_err) > 0) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, r,
+ "%s", argsbuffer);
+ }
+#else
+ while (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_err) > 0)
+ continue;
+#endif
+ return ret;
+ }
+
+ /* "%% [Wed Jun 19 10:53:21 1996] GET /cgi-bin/printenv HTTP/1.0" */
+ fprintf(f, "%%%% [%s] %s %s%s%s %s\n", ap_get_time(), r->method, r->uri,
+ r->args ? "?" : "", r->args ? r->args : "", r->protocol);
+ /* "%% 500 /usr/local/apache/cgi-bin" */
+ fprintf(f, "%%%% %d %s\n", ret, r->filename);
+
+ fputs("%request\n", f);
+ for (i = 0; i < hdrs_arr->nelts; ++i) {
+ if (!hdrs[i].key)
+ continue;
+ fprintf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
+ }
+ if ((r->method_number == M_POST || r->method_number == M_PUT)
+ && *dbuf) {
+ fprintf(f, "\n%s\n", dbuf);
+ }
+
+ fputs("%response\n", f);
+ hdrs_arr = ap_table_elts(r->err_headers_out);
+ hdrs = (table_entry *) hdrs_arr->elts;
+
+ for (i = 0; i < hdrs_arr->nelts; ++i) {
+ if (!hdrs[i].key)
+ continue;
+ fprintf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
+ }
+
+ if (sbuf && *sbuf)
+ fprintf(f, "%s\n", sbuf);
+
+ if (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_in) > 0) {
+ fputs("%stdout\n", f);
+ fputs(argsbuffer, f);
+ while (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_in) > 0)
+ fputs(argsbuffer, f);
+ fputs("\n", f);
+ }
+
+ if (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_err) > 0) {
+ fputs("%stderr\n", f);
+ fputs(argsbuffer, f);
+ while (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_err) > 0)
+ fputs(argsbuffer, f);
+ fputs("\n", f);
+ }
+
+ ap_bclose(script_in);
+ ap_bclose(script_err);
+
+ ap_pfclose(r->pool, f);
+ return ret;
+}
+
+/****************************************************************
+ *
+ * Actual CGI handling...
+ */
+
+
+struct cgi_child_stuff {
+#ifdef TPF
+ TPF_FORK_CHILD t;
+#endif
+ request_rec *r;
+ int nph;
+ int debug;
+ char *argv0;
+};
+
+static int cgi_child(void *child_stuff, child_info *pinfo)
+{
+ struct cgi_child_stuff *cld = (struct cgi_child_stuff *) child_stuff;
+ request_rec *r = cld->r;
+ char *argv0 = cld->argv0;
+ int child_pid;
+
+#ifdef DEBUG_CGI
+#ifdef OS2
+ /* Under OS/2 need to use device con. */
+ FILE *dbg = fopen("con", "w");
+#else
+ FILE *dbg = fopen("/dev/tty", "w");
+#endif
+ int i;
+#endif
+
+ char **env;
+
+ RAISE_SIGSTOP(CGI_CHILD);
+#ifdef DEBUG_CGI
+ fprintf(dbg, "Attempting to exec %s as %sCGI child (argv0 = %s)\n",
+ r->filename, cld->nph ? "NPH " : "", argv0);
+#endif
+
+ ap_add_cgi_vars(r);
+ env = ap_create_environment(r->pool, r->subprocess_env);
+
+#ifdef DEBUG_CGI
+ fprintf(dbg, "Environment: \n");
+ for (i = 0; env[i]; ++i)
+ fprintf(dbg, "'%s'\n", env[i]);
+#endif
+
+#ifndef WIN32
+ ap_chdir_file(r->filename);
+#endif
+ if (!cld->debug)
+ ap_error_log2stderr(r->server);
+
+ /* Transumute outselves into the script.
+ * NB only ISINDEX scripts get decoded arguments.
+ */
+
+#ifdef TPF
+ return (0);
+#else
+ ap_cleanup_for_exec();
+
+ child_pid = ap_call_exec(r, pinfo, argv0, env, 0);
+#if defined(WIN32) || defined(OS2)
+ return (child_pid);
+#else
+
+ /* Uh oh. Still here. Where's the kaboom? There was supposed to be an
+ * EARTH-shattering kaboom!
+ *
+ * Oh, well. Muddle through as best we can...
+ *
+ * Note that only stderr is available at this point, so don't pass in
+ * a server to aplog_error.
+ */
+
+ ap_log_error(APLOG_MARK, APLOG_ERR, NULL, "exec of %s failed", r->filename);
+ exit(0);
+ /* NOT REACHED */
+ return (0);
+#endif
+#endif /* TPF */
+}
+
+static int cgi_handler(request_rec *r)
+{
+ int retval, nph, dbpos = 0;
+ char *argv0, *dbuf = NULL;
+ BUFF *script_out, *script_in, *script_err;
+ char argsbuffer[HUGE_STRING_LEN];
+ int is_included = !strcmp(r->protocol, "INCLUDED");
+ void *sconf = r->server->module_config;
+ cgi_server_conf *conf =
+ (cgi_server_conf *) ap_get_module_config(sconf, &cgi_module);
+
+ struct cgi_child_stuff cld;
+
+ if (r->method_number == M_OPTIONS) {
+ /* 99 out of 100 CGI scripts, this is all they support */
+ r->allowed |= (1 << M_GET);
+ r->allowed |= (1 << M_POST);
+ return DECLINED;
+ }
+
+ if ((argv0 = strrchr(r->filename, '/')) != NULL)
+ argv0++;
+ else
+ argv0 = r->filename;
+
+ nph = !(strncmp(argv0, "nph-", 4));
+
+ if (!(ap_allow_options(r) & OPT_EXECCGI) && !is_scriptaliased(r))
+ return log_scripterror(r, conf, FORBIDDEN, APLOG_NOERRNO,
+ "Options ExecCGI is off in this directory");
+ if (nph && is_included)
+ return log_scripterror(r, conf, FORBIDDEN, APLOG_NOERRNO,
+ "attempt to include NPH CGI script");
+
+#if defined(OS2) || defined(WIN32)
+ /* Allow for cgi files without the .EXE extension on them under OS/2 */
+ if (r->finfo.st_mode == 0) {
+ struct stat statbuf;
+ char *newfile;
+
+ newfile = ap_pstrcat(r->pool, r->filename, ".EXE", NULL);
+
+ if ((stat(newfile, &statbuf) != 0) || (!S_ISREG(statbuf.st_mode))) {
+ return log_scripterror(r, conf, NOT_FOUND, 0,
+ "script not found or unable to stat");
+ } else {
+ r->filename = newfile;
+ }
+ }
+#else
+ if (r->finfo.st_mode == 0)
+ return log_scripterror(r, conf, NOT_FOUND, APLOG_NOERRNO,
+ "script not found or unable to stat");
+#endif
+ if (S_ISDIR(r->finfo.st_mode))
+ return log_scripterror(r, conf, FORBIDDEN, APLOG_NOERRNO,
+ "attempt to invoke directory as script");
+ if (!ap_suexec_enabled) {
+ if (!ap_can_exec(&r->finfo))
+ return log_scripterror(r, conf, FORBIDDEN, APLOG_NOERRNO,
+ "file permissions deny server execution");
+ }
+
+ if ((retval = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR)))
+ return retval;
+
+ ap_add_common_vars(r);
+ cld.argv0 = argv0;
+ cld.r = r;
+ cld.nph = nph;
+ cld.debug = conf->logname ? 1 : 0;
+#ifdef TPF
+ cld.t.filename = r->filename;
+ cld.t.subprocess_env = r->subprocess_env;
+ cld.t.prog_type = FORK_FILE;
+#endif /* TPF */
+
+#ifdef CHARSET_EBCDIC
+ /* XXX:@@@ Is the generated/included output ALWAYS in text/ebcdic format? */
+ /* Or must we check the Content-Type first? */
+ ap_bsetflag(r->connection->client, B_EBCDIC2ASCII, 1);
+#endif /*CHARSET_EBCDIC*/
+
+ /*
+ * we spawn out of r->main if it's there so that we can avoid
+ * waiting for free_proc_chain to cleanup in the middle of an
+ * SSI request -djg
+ */
+ if (!ap_bspawn_child(r->main ? r->main->pool : r->pool, cgi_child,
+ (void *) &cld, kill_after_timeout,
+ &script_out, &script_in, &script_err)) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
+ "couldn't spawn child process: %s", r->filename);
+ return HTTP_INTERNAL_SERVER_ERROR;
+ }
+
+ /* Transfer any put/post args, CERN style...
+ * Note that we already ignore SIGPIPE in the core server.
+ */
+
+ if (ap_should_client_block(r)) {
+ int dbsize, len_read;
+
+ if (conf->logname) {
+ dbuf = ap_pcalloc(r->pool, conf->bufbytes + 1);
+ dbpos = 0;
+ }
+
+ ap_hard_timeout("copy script args", r);
+
+ while ((len_read =
+ ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN)) > 0) {
+ if (conf->logname) {
+ if ((dbpos + len_read) > conf->bufbytes) {
+ dbsize = conf->bufbytes - dbpos;
+ }
+ else {
+ dbsize = len_read;
+ }
+ memcpy(dbuf + dbpos, argsbuffer, dbsize);
+ dbpos += dbsize;
+ }
+ ap_reset_timeout(r);
+ if (ap_bwrite(script_out, argsbuffer, len_read) < len_read) {
+ /* silly script stopped reading, soak up remaining message */
+ while (ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN) > 0) {
+ /* dump it */
+ }
+ break;
+ }
+ }
+
+ ap_bflush(script_out);
+
+ ap_kill_timeout(r);
+ }
+
+ ap_bclose(script_out);
+
+ /* Handle script return... */
+ if (script_in && !nph) {
+ const char *location;
+ char sbuf[MAX_STRING_LEN];
+ int ret;
+
+ if ((ret = ap_scan_script_header_err_buff(r, script_in, sbuf))) {
+ return log_script(r, conf, ret, dbuf, sbuf, script_in, script_err);
+ }
+
+#ifdef CHARSET_EBCDIC
+ /* Now check the Content-Type to decide if conversion is needed */
+ ap_checkconv(r);
+#endif /*CHARSET_EBCDIC*/
+
+ location = ap_table_get(r->headers_out, "Location");
+
+ if (location && location[0] == '/' && r->status == 200) {
+
+ /* Soak up all the script output */
+ ap_hard_timeout("read from script", r);
+ while (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_in) > 0) {
+ continue;
+ }
+ while (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_err) > 0) {
+ continue;
+ }
+ ap_kill_timeout(r);
+
+
+ /* This redirect needs to be a GET no matter what the original
+ * method was.
+ */
+ r->method = ap_pstrdup(r->pool, "GET");
+ r->method_number = M_GET;
+
+ /* We already read the message body (if any), so don't allow
+ * the redirected request to think it has one. We can ignore
+ * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
+ */
+ ap_table_unset(r->headers_in, "Content-Length");
+
+ ap_internal_redirect_handler(location, r);
+ return OK;
+ }
+ else if (location && r->status == 200) {
+ /* XX Note that if a script wants to produce its own Redirect
+ * body, it now has to explicitly *say* "Status: 302"
+ */
+ return REDIRECT;
+ }
+
+ ap_send_http_header(r);
+ if (!r->header_only) {
+ ap_send_fb(script_in, r);
+ }
+ ap_bclose(script_in);
+
+ ap_soft_timeout("soaking script stderr", r);
+ while (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_err) > 0) {
+ continue;
+ }
+ ap_kill_timeout(r);
+ ap_bclose(script_err);
+ }
+
+ if (script_in && nph) {
+ ap_send_fb(script_in, r);
+ }
+
+ return OK; /* NOT r->status, even if it has changed. */
+}
+
+static const handler_rec cgi_handlers[] =
+{
+ {CGI_MAGIC_TYPE, cgi_handler},
+ {"cgi-script", cgi_handler},
+ {NULL}
+};
+
+module MODULE_VAR_EXPORT cgi_module =
+{
+ STANDARD_MODULE_STUFF,
+ NULL, /* initializer */
+ NULL, /* dir config creater */
+ NULL, /* dir merger --- default is to override */
+ create_cgi_config, /* server config */
+ merge_cgi_config, /* merge server config */
+ cgi_cmds, /* command table */
+ cgi_handlers, /* handlers */
+ NULL, /* filename translation */
+ NULL, /* check_user_id */
+ NULL, /* check auth */
+ NULL, /* check access */
+ NULL, /* type_checker */
+ NULL, /* fixups */
+ NULL, /* logger */
+ NULL, /* header parser */
+ NULL, /* child_init */
+ NULL, /* child_exit */
+ NULL /* post read-request */
+};
diff --git a/modules/generators/mod_cgid.c b/modules/generators/mod_cgid.c
new file mode 100644
index 00000000000..ae90d763d47
--- /dev/null
+++ b/modules/generators/mod_cgid.c
@@ -0,0 +1,1006 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+/*
+ * http_script: keeps all script-related ramblings together.
+ *
+ * Compliant to cgi/1.1 spec
+ *
+ * Adapted by rst from original NCSA code by Rob McCool
+ *
+ * Apache adds some new env vars; REDIRECT_URL and REDIRECT_QUERY_STRING for
+ * custom error responses, and DOCUMENT_ROOT because we found it useful.
+ * It also adds SERVER_ADMIN - useful for scripts to know who to mail when
+ * they fail.
+ */
+
+
+
+#define CORE_PRIVATE
+
+#include "apr_lib.h"
+#include "apr_general.h"
+#include "apr_file_io.h"
+#include "apr_portable.h"
+#include "httpd.h"
+#include "http_config.h"
+#include "http_request.h"
+#include "http_core.h"
+#include "http_protocol.h"
+#include "http_main.h"
+#include "http_log.h"
+#include "util_script.h"
+#include "http_conf_globals.h"
+#include "buff.h"
+#include "ap_mpm.h"
+#include "iol_socket.h"
+
+#ifndef UNIX_PATH_MAX
+#define UNIX_PATH_MAX 108
+#endif
+
+#ifndef sockaddr_un
+struct sockaddr_un {
+ unsigned short sun_family;
+ char sun_path[UNIX_PATH_MAX];
+};
+#endif
+
+
+module MODULE_VAR_EXPORT cgid_module;
+
+static void cgid_init(ap_context_t *p, ap_context_t *plog, ap_context_t *ptemp, server_rec *main_server);
+static int once_through = 0;
+
+static ap_context_t *pcgi;
+
+/* KLUDGE --- for back-combatibility, we don't have to check Execcgid
+ * in ScriptAliased directories, which means we need to know if this
+ * request came through ScriptAlias or not... so the Alias module
+ * leaves a note for us.
+ */
+
+static int is_scriptaliased(request_rec *r)
+{
+ const char *t = ap_table_get(r->notes, "alias-forced-type");
+ return t && (!strcasecmp(t, "cgi-script"));
+}
+
+/* Configuration stuff */
+
+#define DEFAULT_LOGBYTES 10385760
+#define DEFAULT_BUFBYTES 1024
+#define DEFAULT_SOCKET "logs/cgisock"
+
+typedef struct {
+ const char *sockname;
+ char *logname;
+ long logbytes;
+ int bufbytes;
+ BUFF *bin;
+ BUFF *bout;
+ BUFF *berror;
+} cgid_server_conf;
+
+/* If a request includes query info in the URL (stuff after "?"), and
+ * the query info does not contain "=" (indicative of a FORM submission),
+ * then this routine is called to create the argument list to be passed
+ * to the CGI script. When suexec is enabled, the suexec path, user, and
+ * group are the first three arguments to be passed; if not, all three
+ * must be NULL. The query info is split into separate arguments, where
+ * "+" is the separator between keyword arguments.
+ *
+ * XXXX: note that the WIN32 code uses one of the suexec strings
+ * to pass an interpreter name. Remember this if changing the way they
+ * are handled in create_argv.
+ *
+ */
+static char **create_argv(ap_context_t *p, char *path, char *user, char *group,
+ char *av0, const char *args)
+{
+ int x, numwords;
+ char **av;
+ char *w;
+ int idx = 0;
+
+ /* count the number of keywords */
+
+ for (x = 0, numwords = 1; args[x]; x++) {
+ if (args[x] == '+') {
+ ++numwords;
+ }
+ }
+
+ if (numwords > APACHE_ARG_MAX - 5) {
+ numwords = APACHE_ARG_MAX - 5; /* Truncate args to prevent overrun */
+ }
+ av = (char **) ap_palloc(p, (numwords + 5) * sizeof(char *));
+
+ if (path) {
+ av[idx++] = path;
+ }
+ if (user) {
+ av[idx++] = user;
+ }
+ if (group) {
+ av[idx++] = group;
+ }
+
+ av[idx++] = av0;
+
+ for (x = 1; x <= numwords; x++) {
+ w = ap_getword_nulls(p, &args, '+');
+ ap_unescape_url(w);
+ av[idx++] = ap_escape_shell_cmd(p, w);
+ }
+ av[idx] = NULL;
+ return av;
+}
+
+static int call_exec(request_rec *r, char *argv0, char **env, int shellcmd)
+{
+ int pid = 0;
+ int errfileno = STDERR_FILENO;
+
+ /* the fd on r->server->error_log is closed, but we need somewhere to * put the error messages from the log_* functions. So, we use stderr,
+ * since that is better than allowing errors to go unnoticed.
+ */
+ ap_put_os_file(&r->server->error_log, &errfileno, r->pool);
+ /* TODO: reimplement suexec */
+#if 0
+ if (ap_suexec_enabled
+ && ((r->server->server_uid != ap_user_id)
+ || (r->server->server_gid != ap_group_id)
+ || (!strncmp("/~", r->uri, 2)))) {
+
+ char *execuser, *grpname;
+ struct passwd *pw;
+ struct group *gr;
+
+ if (!strncmp("/~", r->uri, 2)) {
+ gid_t user_gid;
+ char *username = ap_pstrdup(r->pool, r->uri + 2);
+ char *pos = strchr(username, '/');
+
+ if (pos) {
+ *pos = '\0';
+ }
+
+ if ((pw = getpwnam(username)) == NULL) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
+ "getpwnam: invalid username %s", username);
+ return (pid);
+ }
+ execuser = ap_pstrcat(r->pool, "~", pw->pw_name, NULL);
+ user_gid = pw->pw_gid;
+
+ if ((gr = getgrgid(user_gid)) == NULL) {
+ if ((grpname = ap_palloc(r->pool, 16)) == NULL) {
+ return (pid);
+ }
+ else {
+ ap_snprintf(grpname, 16, "%ld", (long) user_gid);
+ }
+ }
+ else {
+ grpname = gr->gr_name;
+ }
+ }
+ else {
+ if ((pw = getpwuid(r->server->server_uid)) == NULL) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
+ "getpwuid: invalid userid %ld",
+ (long) r->server->server_uid);
+ return (pid);
+ }
+ execuser = ap_pstrdup(r->pool, pw->pw_name);
+
+ if ((gr = getgrgid(r->server->server_gid)) == NULL) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
+ "getgrgid: invalid groupid %ld",
+ (long) r->server->server_gid);
+ return (pid);
+ }
+ grpname = gr->gr_name;
+ }
+
+ if (shellcmd) {
+ execle(SUEXEC_BIN, SUEXEC_BIN, execuser, grpname, argv0,
+ NULL, env);
+ }
+
+ else if ((!r->args) || (!r->args[0]) || strchr(r->args, '=')) {
+ execle(SUEXEC_BIN, SUEXEC_BIN, execuser, grpname, argv0,
+ NULL, env);
+ }
+
+ else {
+ execve(SUEXEC_BIN,
+ create_argv(r->pool, SUEXEC_BIN, execuser, grpname,
+ argv0, r->args),
+ env);
+ }
+ }
+ else {
+#endif
+ if (shellcmd) {
+ execle(SHELL_PATH, SHELL_PATH, "-c", argv0, NULL, env);
+ }
+
+ else if ((!r->args) || (!r->args[0]) || strchr(r->args, '=')) {
+ execle(r->filename, argv0, NULL, env);
+ }
+
+ else {
+ execve(r->filename,
+ create_argv(r->pool, NULL, NULL, NULL, argv0, r->args),
+ env);
+ }
+#if 0
+ }
+#endif
+ return (pid);
+}
+
+static void cgid_maint(int reason, void *data, ap_wait_t status)
+{
+#ifdef HAS_OTHER_CHILD
+ int *sd = data;
+ switch (reason) {
+ case OC_REASON_DEATH:
+ case OC_REASON_LOST:
+ /* stop gap to make sure everything else works. In the end,
+ * we'll just restart the cgid server. */
+ kill(getppid(), SIGWINCH);
+ break;
+ case OC_REASON_RESTART:
+ case OC_REASON_UNREGISTER:
+ kill(*sd, SIGHUP);
+ break;
+ }
+#endif
+}
+
+static void get_req(int fd, request_rec *r, char **filename, char **argv0, char ***env)
+{
+ int i, len, j;
+ unsigned char *data;
+ char **environ;
+ char temp[MAX_STRING_LEN];
+ core_dir_config *temp_core;
+ void **dconf;
+
+ r->server = ap_pcalloc(r->pool, sizeof(server_rec));
+
+ read(fd, &j, sizeof(int));
+ read(fd, &len, sizeof(int));
+ data = ap_pcalloc(r->pool, len);
+ i = read(fd, data, len);
+
+ r->filename = ap_getword(r->pool, (const char **)&data, '\n');
+ *argv0 = ap_getword(r->pool, (const char **)&data, '\n');
+
+ r->uri = ap_getword(r->pool, (const char **)&data, '\n');
+
+ environ = ap_pcalloc(r->pool, (j + 2) *sizeof(char *));
+ i = 0;
+ for (i = 0; i < j; i++) {
+ environ[i] = ap_getword(r->pool, (const char **)&data, '\n');
+ }
+ *env = environ;
+ r->args = ap_getword(r->pool, (const char **)&data, '\n');
+
+ read(fd, &r->server->server_uid, sizeof(uid_t));
+ read(fd, &r->server->server_gid, sizeof(gid_t));
+
+ read(fd, &i, sizeof(int));
+
+ /* add 1, so that if i == 0, we still malloc something. */
+ dconf = (void **)malloc(sizeof(void *) * i + 1);
+
+ temp_core = (core_dir_config *)malloc(sizeof(core_module));
+#if 0
+#ifdef RLIMIT_CPU
+ read(fd, &j, sizeof(int));
+ if (j) {
+ temp_core->limit_cpu = (struct rlimit *)malloc (sizeof(struct rlimit));
+ read(fd, temp_core->limit_cpu, sizeof(struct rlimit));
+ }
+ else {
+ temp_core->limit_cpu = NULL;
+ }
+#endif
+
+#if defined (RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
+ read(fd, &j, sizeof(int));
+ if (j) {
+ temp_core->limit_mem = (struct rlimit *)malloc (sizeof(struct rlimit));
+ read(fd, temp_core->limit_mem, sizeof(struct rlimit));
+ }
+ else {
+ temp_core->limit_mem = NULL;
+ }
+#endif
+
+#ifdef RLIMIT_NPROC
+ read(fd, &j, sizeof(int));
+ if (j) {
+ temp_core->limit_nproc = (struct rlimit *)malloc (sizeof(struct rlimit));
+ read(fd, temp_core->limit_nproc, sizeof(struct rlimit));
+ }
+ else {
+ temp_core->limit_nproc = NULL;
+ }
+#endif
+#endif
+ dconf[i] = (void *)temp_core;
+ r->per_dir_config = dconf;
+}
+
+
+
+static void send_req(int fd, request_rec *r, char *argv0, char **env)
+{
+ int len;
+ int rv;
+ int i = 0;
+ char *data;
+ core_dir_config *conf = ap_get_module_config(r->per_dir_config,
+ &core_module);
+
+ data = ap_pstrcat(r->pool, r->filename, "\n", argv0, "\n", r->uri, "\n",
+ NULL);
+
+ for (i =0; env[i]; i++) {
+ continue;
+ }
+
+ if (write(fd, &i, sizeof(int)) < 0) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
+ "write to cgi daemon process");
+ }
+
+ for (i = 0; env[i]; i++) {
+ data = ap_pstrcat(r->pool, data, env[i], "\n", NULL);
+ }
+ data = ap_pstrcat(r->pool, data, r->args, NULL);
+ len = strlen(data);
+ if (write(fd, &len, sizeof(int)) < 0) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
+ "write to cgi daemon process");
+ }
+ if (write(fd, data, len) < 0) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
+ "write to cgi daemon process");
+ }
+ if (write(fd, &r->server->server_uid, sizeof(uid_t)) < 0) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
+ "write to cgi daemon process");
+ }
+ if (write(fd, &r->server->server_gid, sizeof(gid_t)) < 0) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
+ "write to cgi daemon process");
+ }
+ if (write(fd, &core_module.module_index, sizeof(int)) < 0) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
+ "write to cgi daemon process");
+ }
+#if 0
+#ifdef RLIMIT_CPU
+ if (conf->limit_cpu) {
+ len = 1;
+ write(fd, &len, sizeof(int));
+ write(fd, conf->limit_cpu, sizeof(struct rlimit));
+ }
+ else {
+ len = 0;
+ write(fd, &len, sizeof(int));
+ }
+#endif
+
+#if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
+ if (conf->limit_mem) {
+ len = 1;
+ write(fd, &len, sizeof(int));
+ write(fd, conf->limit_mem, sizeof(struct rlimit));
+ }
+ else {
+ len = 0;
+ write(fd, &len, sizeof(int));
+ }
+#endif
+
+#ifdef RLIMIT_NPROC
+ if (conf->limit_nproc) {
+ len = 1;
+ write(fd, &len, sizeof(int));
+ write(fd, conf->limit_nproc, sizeof(struct rlimit));
+ }
+ else {
+ len = 0;
+ write(fd, &len, sizeof(int));
+ }
+#endif
+#endif
+}
+
+static int cgid_server_child(int sd)
+{
+ char *argv0;
+ char *filename;
+ char **env;
+ ap_context_t *p;
+ request_rec *r;
+
+ ap_create_context(&p, pcgi);
+ r = ap_pcalloc(p, sizeof(request_rec));
+ r->pool = p;
+ dup2(sd, STDIN_FILENO);
+ dup2(sd, STDOUT_FILENO);
+ get_req(sd, r, &filename, &argv0, &env);
+ call_exec(r, argv0, env, 0);
+ exit(-1); /* We should NEVER get here */
+}
+
+static int cgid_server(void *data)
+{
+ struct sockaddr_un unix_addr;
+ int pid;
+ int sd, sd2, len;
+ int errfile;
+ server_rec *main_server = data;
+ cgid_server_conf *sconf = (cgid_server_conf *)ap_get_module_config(
+ main_server->module_config, &cgid_module);
+
+ signal(SIGCHLD, SIG_IGN);
+ unlink(sconf->sockname);
+
+ if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
+ ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
+ "Couldn't create unix domain socket");
+ }
+
+ memset(&unix_addr, 0, sizeof(unix_addr));
+ unix_addr.sun_family = AF_UNIX;
+ strcpy(unix_addr.sun_path, sconf->sockname);
+
+ if (bind(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) < 0) {
+ ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
+ "Couldn't bind unix domain socket");
+ }
+ /* Most implementations silently enforce a value of 5 anyway.
+ * This way, it'll work the same everywhere. */
+ if (listen(sd, 5) < 0) {
+ ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
+ "Couldn't listen on unix domain socket");
+ }
+
+ while (1) {
+ sd2 = accept(sd, (struct sockaddr *)&unix_addr, &len);
+ if (sd2 < 0) {
+ ap_log_error(APLOG_MARK, APLOG_ERR, errno, (server_rec *)data,
+ "Error accepting on cgid socket.");
+ continue;
+ }
+
+ if ((pid = fork()) > 0) {
+ close(sd2);
+ }
+ else if (pid == 0) {
+ /* setup the STDERR here, because I have all the info
+ * for it. I'll do the STDIN and STDOUT later, but I can't
+ * do STDERR as easily.
+ */
+ if (sconf->logname) {
+ dup2(open(sconf->logname, O_WRONLY), STDERR_FILENO);
+ }
+ else {
+ ap_get_os_file(&errfile, main_server->error_log);
+ dup2(errfile, STDERR_FILENO);
+ }
+ cgid_server_child(sd2);
+ }
+ else {
+ ap_log_error(APLOG_MARK, APLOG_ERR, errno, (server_rec *)data,
+ "Couldn't fork cgi script");
+ }
+ }
+ return -1;
+}
+
+static void cgid_init(ap_context_t *p, ap_context_t *plog, ap_context_t *ptemp, server_rec *main_server)
+{
+ int pid;
+ int tempfd;
+
+ cgid_server_conf *sconf = (cgid_server_conf *)ap_get_module_config(
+ main_server->module_config, &cgid_module);
+
+ if (once_through > 0) {
+ ap_create_context(&pcgi, p);
+ tempfd = creat(sconf->sockname, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
+ close(tempfd);
+
+ if ((pid = fork()) < 0) {
+ ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
+ "Couldn't spawn cgid daemon process");
+ }
+ else if (pid == 0) {
+ cgid_server(main_server);
+ exit(-1);
+ }
+#ifdef HAS_OTHER_CHILD
+ ap_register_other_child(pid, cgid_maint, &pid, -1);
+#endif
+ }
+ else once_through++;
+}
+
+static void *create_cgid_config(ap_context_t *p, server_rec *s)
+{
+ cgid_server_conf *c =
+ (cgid_server_conf *) ap_pcalloc(p, sizeof(cgid_server_conf));
+
+ c->logname = NULL;
+ c->logbytes = DEFAULT_LOGBYTES;
+ c->bufbytes = DEFAULT_BUFBYTES;
+ c->sockname = ap_server_root_relative(p, DEFAULT_SOCKET);
+ c->bin = c->bout = c->berror = NULL;
+ return c;
+}
+
+static void *merge_cgid_config(ap_context_t *p, void *basev, void *overridesv)
+{
+ cgid_server_conf *base = (cgid_server_conf *) basev, *overrides = (cgid_server_conf *) overridesv;
+
+ return overrides->logname ? overrides : base;
+}
+
+static const char *set_scriptlog(cmd_parms *cmd, void *dummy, char *arg)
+{
+ server_rec *s = cmd->server;
+ cgid_server_conf *conf =
+ (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
+
+ conf->logname = arg;
+ return NULL;
+}
+
+static const char *set_scriptlog_length(cmd_parms *cmd, void *dummy, char *arg)
+{
+ server_rec *s = cmd->server;
+ cgid_server_conf *conf =
+ (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
+
+ conf->logbytes = atol(arg);
+ return NULL;
+}
+
+static const char *set_scriptlog_buffer(cmd_parms *cmd, void *dummy, char *arg)
+{
+ server_rec *s = cmd->server;
+ cgid_server_conf *conf =
+ (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
+
+ conf->bufbytes = atoi(arg);
+ return NULL;
+}
+
+static const char *set_script_socket(cmd_parms *cmd, void *dummy, char *arg)
+{
+ server_rec *s = cmd->server;
+ cgid_server_conf *conf =
+ (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
+
+ conf->sockname = ap_server_root_relative(cmd->pool, arg);
+ return NULL;
+}
+
+static const command_rec cgid_cmds[] =
+{
+ {"ScriptLog", set_scriptlog, NULL, RSRC_CONF, TAKE1,
+ "the name of a log for script debugging info"},
+ {"ScriptLogLength", set_scriptlog_length, NULL, RSRC_CONF, TAKE1,
+ "the maximum length (in bytes) of the script debug log"},
+ {"ScriptLogBuffer", set_scriptlog_buffer, NULL, RSRC_CONF, TAKE1,
+ "the maximum size (in bytes) to record of a POST request"},
+ {"Scriptsock", set_script_socket, NULL, RSRC_CONF, TAKE1,
+ "the name of the socket to use for communication with the cgi daemon."},
+ {NULL}
+};
+
+static int log_scripterror(request_rec *r, cgid_server_conf * conf, int ret,
+ int show_errno, char *error)
+{
+ ap_file_t *f;
+ struct stat finfo;
+
+ ap_log_rerror(APLOG_MARK, show_errno|APLOG_ERR, errno, r,
+ "%s: %s", error, r->filename);
+
+ if (!conf->logname ||
+ ((stat(ap_server_root_relative(r->pool, conf->logname), &finfo) == 0)
+ && (finfo.st_size > conf->logbytes)) ||
+ (ap_open(&f, ap_server_root_relative(r->pool, conf->logname),
+ APR_APPEND, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) {
+ return ret;
+ }
+
+ /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */
+ ap_fprintf(f, "%%%% [%s] %s %s%s%s %s\n", ap_get_time(), r->method, r->uri,
+ r->args ? "?" : "", r->args ? r->args : "", r->protocol);
+ /* "%% 500 /usr/local/apache/cgid-bin */
+ ap_fprintf(f, "%%%% %d %s\n", ret, r->filename);
+
+ ap_fprintf(f, "%%error\n%s\n", error);
+
+ ap_close(f);
+ return ret;
+}
+
+static int log_script(request_rec *r, cgid_server_conf * conf, int ret,
+ char *dbuf, const char *sbuf, BUFF *script_in, BUFF *script_err)
+{
+ ap_array_header_t *hdrs_arr = ap_table_elts(r->headers_in);
+ ap_table_entry_t *hdrs = (ap_table_entry_t *) hdrs_arr->elts;
+ char argsbuffer[HUGE_STRING_LEN];
+ ap_file_t *f;
+ int i;
+ struct stat finfo;
+
+ if (!conf->logname ||
+ ((stat(ap_server_root_relative(r->pool, conf->logname), &finfo) == 0)
+ && (finfo.st_size > conf->logbytes)) ||
+ (ap_open(&f, ap_server_root_relative(r->pool, conf->logname),
+ APR_APPEND, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) {
+ /* Soak up script output */
+ while (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_in) > 0)
+ continue;
+ while (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_err) > 0)
+ continue;
+ return ret;
+ }
+
+ /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */
+ ap_fprintf(f, "%%%% [%s] %s %s%s%s %s\n", ap_get_time(), r->method, r->uri,
+ r->args ? "?" : "", r->args ? r->args : "", r->protocol);
+ /* "%% 500 /usr/local/apache/cgid-bin" */
+ ap_fprintf(f, "%%%% %d %s\n", ret, r->filename);
+
+ ap_puts("%request\n", f);
+ for (i = 0; i < hdrs_arr->nelts; ++i) {
+ if (!hdrs[i].key)
+ continue;
+ ap_fprintf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
+ }
+ if ((r->method_number == M_POST || r->method_number == M_PUT)
+ && *dbuf) {
+ ap_fprintf(f, "\n%s\n", dbuf);
+ }
+
+ ap_puts("%response\n", f);
+ hdrs_arr = ap_table_elts(r->err_headers_out);
+ hdrs = (ap_table_entry_t *) hdrs_arr->elts;
+
+ for (i = 0; i < hdrs_arr->nelts; ++i) {
+ if (!hdrs[i].key)
+ continue;
+ ap_fprintf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
+ }
+
+ if (sbuf && *sbuf)
+ ap_fprintf(f, "%s\n", sbuf);
+
+ if (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_in) > 0) {
+ ap_puts("%stdout\n", f);
+ ap_puts(argsbuffer, f);
+ while (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_in) > 0)
+ ap_puts(argsbuffer, f);
+ ap_puts("\n", f);
+ }
+
+ if (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_err) > 0) {
+ ap_puts("%stderr\n", f);
+ ap_puts(argsbuffer, f);
+ while (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_err) > 0)
+ ap_puts(argsbuffer, f);
+ ap_puts("\n", f);
+ }
+
+ ap_bclose(script_in);
+ ap_bclose(script_err);
+
+ ap_close(f);
+ return ret;
+}
+
+
+
+/****************************************************************
+ *
+ * Actual cgid handling...
+ */
+static int cgid_handler(request_rec *r)
+{
+ int retval, nph, dbpos = 0;
+ char *argv0, *dbuf = NULL;
+ BUFF *script = NULL;
+ char argsbuffer[HUGE_STRING_LEN];
+ void *sconf = r->server->module_config;
+ cgid_server_conf *conf = (cgid_server_conf *) ap_get_module_config(sconf, &cgid_module);
+ int is_included = !strcmp(r->protocol, "INCLUDED");
+ int sd;
+ char **env;
+ struct sockaddr_un unix_addr;
+ ap_socket_t *tempsock = NULL;
+ int nbytes;
+ ap_iol *iol;
+ script = ap_bcreate(r->pool, B_RDWR);
+
+ if (r->method_number == M_OPTIONS) {
+ /* 99 out of 100 cgid scripts, this is all they support */
+ r->allowed |= (1 << M_GET);
+ r->allowed |= (1 << M_POST);
+ return DECLINED;
+ }
+
+ if ((argv0 = strrchr(r->filename, '/')) != NULL)
+ argv0++;
+ else
+ argv0 = r->filename;
+
+ nph = !(strncmp(argv0, "nph-", 4));
+
+ if ((argv0 = strrchr(r->filename, '/')) != NULL)
+ argv0++;
+ else
+ argv0 = r->filename;
+
+ if (!(ap_allow_options(r) & OPT_EXECCGI) && !is_scriptaliased(r))
+ return log_scripterror(r, conf, FORBIDDEN, APLOG_NOERRNO,
+ "Options ExecCGI is off in this directory");
+ if (nph && is_included)
+ return log_scripterror(r, conf, FORBIDDEN, APLOG_NOERRNO,
+ "attempt to include NPH CGI script");
+
+#if defined(OS2) || defined(WIN32)
+ /* Allow for cgid files without the .EXE extension on them under OS/2 */
+ if (r->finfo.st_mode == 0) {
+ struct stat statbuf;
+ char *newfile;
+
+ newfile = ap_pstrcat(r->pool, r->filename, ".EXE", NULL);
+
+ if ((stat(newfile, &statbuf) != 0) || (!S_ISREG(statbuf.st_mode))) {
+ return log_scripterror(r, conf, NOT_FOUND, 0,
+ "script not found or unable to stat");
+ } else {
+ r->filename = newfile;
+ }
+ }
+#else
+ if (r->finfo.st_mode == 0)
+ return log_scripterror(r, conf, NOT_FOUND, APLOG_NOERRNO,
+ "script not found or unable to stat");
+#endif
+ if (S_ISDIR(r->finfo.st_mode))
+ return log_scripterror(r, conf, FORBIDDEN, APLOG_NOERRNO,
+ "attempt to invoke directory as script");
+/*
+ if (!ap_suexec_enabled) {
+ if (!ap_can_exec(&r->finfo))
+ return log_scripterror(r, conf, FORBIDDEN, APLOG_NOERRNO,
+ "file permissions deny server execution");
+ }
+*/
+ ap_add_common_vars(r);
+ ap_add_cgi_vars(r);
+ env = ap_create_environment(r->pool, r->subprocess_env);
+
+ if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
+ return log_scripterror(r, conf, NOT_FOUND, 0,
+ "unable to create socket to cgi daemon");
+ }
+ memset(&unix_addr, 0, sizeof(unix_addr));
+ unix_addr.sun_family = AF_UNIX;
+ strcpy(unix_addr.sun_path, conf->sockname);
+
+ if (connect(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) < 0) {
+ return log_scripterror(r, conf, NOT_FOUND, 0,
+ "unable to connect to cgi daemon");
+ }
+
+ send_req(sd, r, argv0, env);
+
+ ap_put_os_sock(&tempsock, &sd, pcgi);
+
+ iol = unix_attach_socket(tempsock);
+
+ ap_bpush_iol(script, iol);
+
+ if ((retval = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR)))
+ return retval;
+
+ if ((argv0 = strrchr(r->filename, '/')) != NULL)
+ argv0++;
+ else
+ argv0 = r->filename;
+
+ /* Transfer any put/post args, CERN style...
+ * Note that we already ignore SIGPIPE in the core server.
+ */
+
+ if (ap_should_client_block(r)) {
+ int dbsize, len_read;
+
+ if (conf->logname) {
+ dbuf = ap_pcalloc(r->pool, conf->bufbytes + 1);
+ dbpos = 0;
+ }
+
+
+
+ while ((len_read =
+ ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN)) > 0) {
+ if (conf->logname) {
+ if ((dbpos + len_read) > conf->bufbytes) {
+ dbsize = conf->bufbytes - dbpos;
+ }
+ else {
+ dbsize = len_read;
+ }
+ memcpy(dbuf + dbpos, argsbuffer, dbsize);
+ dbpos += dbsize;
+ }
+ ap_bwrite(script, argsbuffer, len_read, &nbytes);
+ if (nbytes < len_read) {
+ /* silly script stopped reading, soak up remaining message */
+ while (ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN) > 0) {
+ /* dump it */
+ }
+ break;
+ }
+ }
+
+ ap_bflush(script);
+
+ }
+
+ /* Handle script return... */
+ if (script && !nph) {
+ const char *location;
+ char sbuf[MAX_STRING_LEN];
+ int ret;
+
+ if ((ret = ap_scan_script_header_err_buff(r, script, sbuf))) {
+ return log_script(r, conf, ret, dbuf, sbuf, script, NULL);
+ }
+
+#ifdef CHARSET_EBCDIC
+ /* Now check the Content-Type to decide if conversion is needed */
+ ap_checkconv(r);
+#endif /*CHARSET_EBCDIC*/
+
+ location = ap_table_get(r->headers_out, "Location");
+
+ if (location && location[0] == '/' && r->status == 200) {
+
+ /* Soak up all the script output */
+ while (ap_bgets(argsbuffer, HUGE_STRING_LEN, script) > 0) {
+ continue;
+ }
+ /* This redirect needs to be a GET no matter what the original
+ * method was.
+ */
+ r->method = ap_pstrdup(r->pool, "GET");
+ r->method_number = M_GET;
+
+ /* We already read the message body (if any), so don't allow
+ * the redirected request to think it has one. We can ignore
+ * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
+ */
+ ap_table_unset(r->headers_in, "Content-Length");
+
+ ap_internal_redirect_handler(location, r);
+ return OK;
+ }
+ else if (location && r->status == 200) {
+ /* XX Note that if a script wants to produce its own Redirect
+ * body, it now has to explicitly *say* "Status: 302"
+ */
+ return REDIRECT;
+ }
+
+ ap_send_http_header(r);
+ if (!r->header_only) {
+ ap_send_fb(script, r);
+ }
+ ap_bclose(script);
+ }
+
+ if (script && nph) {
+ ap_send_fb(script, r);
+ }
+
+ap_destroy_pool(pcgi);
+
+ return OK; /* NOT r->status, even if it has changed. */
+}
+
+static const handler_rec cgid_handlers[] =
+{
+ {CGI_MAGIC_TYPE, cgid_handler},
+ {"cgi-script", cgid_handler},
+ {NULL}
+};
+
+static void register_hook(void)
+{
+ ap_hook_post_config(cgid_init, NULL, NULL, HOOK_MIDDLE);
+}
+
+module MODULE_VAR_EXPORT cgid_module = {
+ STANDARD20_MODULE_STUFF,
+ NULL, /* dir config creater */
+ NULL, /* dir merger --- default is to override */
+ create_cgid_config, /* server config */
+ merge_cgid_config, /* merge server config */
+ cgid_cmds, /* command table */
+ cgid_handlers, /* handlers */
+ register_hook /* register_handlers */
+};
+
diff --git a/modules/generators/mod_info.c b/modules/generators/mod_info.c
new file mode 100644
index 00000000000..27995855780
--- /dev/null
+++ b/modules/generators/mod_info.c
@@ -0,0 +1,695 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+/*
+ * Info Module. Display configuration information for the server and
+ * all included modules.
+ *
+ *
+ * SetHandler server-info
+ *
+ *
+ * GET /server-info - Returns full configuration page for server and all modules
+ * GET /server-info?server - Returns server configuration only
+ * GET /server-info?module_name - Returns configuration for a single module
+ * GET /server-info?list - Returns quick list of included modules
+ *
+ * Rasmus Lerdorf , May 1996
+ *
+ * 05.01.96 Initial Version
+ *
+ * Lou Langholtz , July 1997
+ *
+ * 07.11.97 Addition of the AddModuleInfo directive
+ *
+ */
+
+#include "httpd.h"
+#include "http_config.h"
+#include "http_core.h"
+#include "http_log.h"
+#include "http_main.h"
+#include "http_protocol.h"
+#include "util_script.h"
+#include "http_conf_globals.h"
+
+typedef struct {
+ char *name; /* matching module name */
+ char *info; /* additional info */
+} info_entry;
+
+typedef struct {
+ array_header *more_info;
+} info_svr_conf;
+
+typedef struct info_cfg_lines {
+ char *cmd;
+ char *line;
+ struct info_cfg_lines *next;
+} info_cfg_lines;
+
+module MODULE_VAR_EXPORT info_module;
+extern module *top_module;
+
+static void *create_info_config(pool *p, server_rec *s)
+{
+ info_svr_conf *conf = (info_svr_conf *) ap_pcalloc(p, sizeof(info_svr_conf));
+
+ conf->more_info = ap_make_array(p, 20, sizeof(info_entry));
+ return conf;
+}
+
+static void *merge_info_config(pool *p, void *basev, void *overridesv)
+{
+ info_svr_conf *new = (info_svr_conf *) ap_pcalloc(p, sizeof(info_svr_conf));
+ info_svr_conf *base = (info_svr_conf *) basev;
+ info_svr_conf *overrides = (info_svr_conf *) overridesv;
+
+ new->more_info = ap_append_arrays(p, overrides->more_info, base->more_info);
+ return new;
+}
+
+static char *mod_info_html_cmd_string(const char *string, char *buf, size_t buf_len)
+{
+ const char *s;
+ char *t;
+ char *end_buf;
+
+ s = string;
+ t = buf;
+ /* keep space for \0 byte */
+ end_buf = buf + buf_len - 1;
+ while ((*s) && (t < end_buf)) {
+ if (*s == '<') {
+ strncpy(t, "<", end_buf - t);
+ t += 4;
+ }
+ else if (*s == '>') {
+ strncpy(t, ">", end_buf - t);
+ t += 4;
+ }
+ else if (*s == '&') {
+ strncpy(t, "&", end_buf - t);
+ t += 5;
+ }
+ else {
+ *t++ = *s;
+ }
+ s++;
+ }
+ /* oops, overflowed... don't overwrite */
+ if (t > end_buf) {
+ *end_buf = '\0';
+ }
+ else {
+ *t = '\0';
+ }
+ return (buf);
+}
+
+static info_cfg_lines *mod_info_load_config(pool *p, const char *filename,
+ request_rec *r)
+{
+ char s[MAX_STRING_LEN];
+ configfile_t *fp;
+ info_cfg_lines *new, *ret, *prev;
+ const char *t;
+
+ fp = ap_pcfg_openfile(p, filename);
+ if (!fp) {
+ ap_log_rerror(APLOG_MARK, APLOG_WARNING, r,
+ "mod_info: couldn't open config file %s",
+ filename);
+ return NULL;
+ }
+ ret = NULL;
+ prev = NULL;
+ while (!ap_cfg_getline(s, MAX_STRING_LEN, fp)) {
+ if (*s == '#') {
+ continue; /* skip comments */
+ }
+ new = ap_palloc(p, sizeof(struct info_cfg_lines));
+ new->next = NULL;
+ if (!ret) {
+ ret = new;
+ }
+ if (prev) {
+ prev->next = new;
+ }
+ t = s;
+ new->cmd = ap_getword_conf(p, &t);
+ if (*t) {
+ new->line = ap_pstrdup(p, t);
+ }
+ else {
+ new->line = NULL;
+ }
+ prev = new;
+ }
+ ap_cfg_closefile(fp);
+ return (ret);
+}
+
+static void mod_info_module_cmds(request_rec *r, info_cfg_lines *cfg,
+ const command_rec *cmds, char *label)
+{
+ const command_rec *cmd = cmds;
+ info_cfg_lines *li = cfg, *li_st = NULL, *li_se = NULL;
+ info_cfg_lines *block_start = NULL;
+ int lab = 0, nest = 0;
+ char buf[MAX_STRING_LEN];
+
+ while (li) {
+ if (!strncasecmp(li->cmd, "cmd, "cmd, "cmd, "next;
+ nest++;
+ continue;
+ }
+ else if (nest && (!strncasecmp(li->cmd, "cmd, "cmd, "cmd, "", r);
+ if (nest == 2) {
+ ap_rputs(" ", r);
+ }
+ ap_rputs(mod_info_html_cmd_string(li->cmd, buf, sizeof(buf)), r);
+ ap_rputs(" ", r);
+ if (li->line) {
+ ap_rputs(mod_info_html_cmd_string(li->line, buf, sizeof(buf)), r);
+ }
+ ap_rputs("\n", r);
+ nest--;
+ if (!nest) {
+ block_start = NULL;
+ li_st = NULL;
+ }
+ else {
+ block_start = li_st;
+ }
+ li_se = NULL;
+ }
+ else {
+ nest--;
+ if (!nest) {
+ li_st = NULL;
+ }
+ li_se = NULL;
+ }
+ }
+ else {
+ nest--;
+ if (!nest) {
+ li_st = NULL;
+ }
+ li_se = NULL;
+ }
+ li = li->next;
+ continue;
+ }
+ cmd = cmds;
+ while (cmd) {
+ if (cmd->name) {
+ if (!strcasecmp(cmd->name, li->cmd)) {
+ if (!lab) {
+ ap_rputs("- ", r);
+ ap_rputs(label, r);
+ ap_rputs("\n", r);
+ lab = 1;
+ }
+ if (((nest && block_start == NULL) ||
+ (nest == 2 && block_start == li_st)) &&
+ (strncasecmp(li->cmd, "cmd, "cmd, "cmd, "cmd, "cmd, "cmd, "
", r);
+ ap_rputs(mod_info_html_cmd_string(li_st->cmd, buf, sizeof(buf)), r);
+ ap_rputs(" ", r);
+ if (li_st->line) {
+ ap_rputs(mod_info_html_cmd_string(li_st->line, buf, sizeof(buf)), r);
+ }
+ ap_rputs("\n", r);
+ block_start = li_st;
+ if (li_se) {
+ ap_rputs("- ", r);
+ ap_rputs(mod_info_html_cmd_string(li_se->cmd, buf, sizeof(buf)), r);
+ ap_rputs(" ", r);
+ if (li_se->line) {
+ ap_rputs(mod_info_html_cmd_string(li_se->line, buf, sizeof(buf)), r);
+ }
+ ap_rputs("\n", r);
+ block_start = li_se;
+ }
+ }
+ ap_rputs("
- ", r);
+ if (nest) {
+ ap_rputs(" ", r);
+ }
+ if (nest == 2) {
+ ap_rputs(" ", r);
+ }
+ ap_rputs(mod_info_html_cmd_string(li->cmd, buf, sizeof(buf)), r);
+ if (li->line) {
+ ap_rputs(" ", r);
+ ap_rputs(mod_info_html_cmd_string(li->line, buf, sizeof(buf)), r);
+ ap_rputs("", r);
+ }
+ ap_rputs("", r);
+ }
+ }
+ else
+ break;
+ cmd++;
+ }
+ li = li->next;
+ }
+}
+
+static char *find_more_info(server_rec *s, const char *module_name)
+{
+ int i;
+ info_svr_conf *conf = (info_svr_conf *) ap_get_module_config(s->module_config,
+ &info_module);
+ info_entry *entry = (info_entry *) conf->more_info->elts;
+
+ if (!module_name) {
+ return 0;
+ }
+ for (i = 0; i < conf->more_info->nelts; i++) {
+ if (!strcmp(module_name, entry->name)) {
+ return entry->info;
+ }
+ entry++;
+ }
+ return 0;
+}
+
+static int display_info(request_rec *r)
+{
+ module *modp = NULL;
+ char buf[MAX_STRING_LEN], *cfname;
+ char *more_info;
+ const command_rec *cmd = NULL;
+ const handler_rec *hand = NULL;
+ server_rec *serv = r->server;
+ int comma = 0;
+ info_cfg_lines *mod_info_cfg_httpd = NULL;
+ info_cfg_lines *mod_info_cfg_srm = NULL;
+ info_cfg_lines *mod_info_cfg_access = NULL;
+
+ r->allowed |= (1 << M_GET);
+ if (r->method_number != M_GET)
+ return DECLINED;
+
+ r->content_type = "text/html";
+ ap_send_http_header(r);
+ if (r->header_only) {
+ return 0;
+ }
+ ap_hard_timeout("send server info", r);
+
+ ap_rputs(DOCTYPE_HTML_3_2
+ "Server Information\n", r);
+ ap_rputs("
Apache Server Information\n", r);
+ if (!r->args || strcasecmp(r->args, "list")) {
+ cfname = ap_server_root_relative(r->pool, ap_server_confname);
+ mod_info_cfg_httpd = mod_info_load_config(r->pool, cfname, r);
+ cfname = ap_server_root_relative(r->pool, serv->srm_confname);
+ mod_info_cfg_srm = mod_info_load_config(r->pool, cfname, r);
+ cfname = ap_server_root_relative(r->pool, serv->access_confname);
+ mod_info_cfg_access = mod_info_load_config(r->pool, cfname, r);
+ if (!r->args) {
+ ap_rputs("Server Settings, ", r);
+ for (modp = top_module; modp; modp = modp->next) {
+ ap_rprintf(r, "%s", modp->name, modp->name);
+ if (modp->next) {
+ ap_rputs(", ", r);
+ }
+ }
+ ap_rputs(" ", r);
+
+ }
+ if (!r->args || !strcasecmp(r->args, "server")) {
+ ap_rprintf(r, "Server Version: "
+ "%s \n",
+ ap_get_server_version());
+ ap_rprintf(r, "Server Built: "
+ "%s \n",
+ ap_get_server_built());
+ ap_rprintf(r, "API Version: "
+ "%d:%d \n",
+ MODULE_MAGIC_NUMBER_MAJOR, MODULE_MAGIC_NUMBER_MINOR);
+ ap_rprintf(r, "Run Mode: %s \n",
+ (ap_standalone ? "standalone" : "inetd"));
+ ap_rprintf(r, "User/Group: "
+ "%s(%d)/%d \n",
+ ap_user_name, (int) ap_user_id, (int) ap_group_id);
+ ap_rprintf(r, "Hostname/port: "
+ "%s:%u \n",
+ serv->server_hostname, serv->port);
+ ap_rprintf(r, "Daemons: "
+ "start: %d "
+ "min idle: %d "
+ "max idle: %d "
+ "max: %d \n",
+ ap_daemons_to_start, ap_daemons_min_free,
+ ap_daemons_max_free, ap_daemons_limit);
+ ap_rprintf(r, "Max Requests: "
+ "per child: %d "
+ "keep alive: %s "
+ "max per connection: %d \n",
+ ap_max_requests_per_child,
+ (serv->keep_alive ? "on" : "off"),
+ serv->keep_alive_max);
+ ap_rprintf(r, "Threads: "
+ "per child: %d \n",
+ ap_threads_per_child);
+ ap_rprintf(r, "Excess requests: "
+ "per child: %d \n",
+ ap_excess_requests_per_child);
+ ap_rprintf(r, "Timeouts: "
+ "connection: %d "
+ "keep-alive: %d ",
+ serv->timeout, serv->keep_alive_timeout);
+ ap_rprintf(r, "Server Root: "
+ "%s \n", ap_server_root);
+ ap_rprintf(r, "Config File: "
+ "%s \n", ap_server_confname);
+ ap_rprintf(r, "PID File: "
+ "%s \n", ap_pid_fname);
+ ap_rprintf(r, "Scoreboard File: "
+ "%s \n", ap_scoreboard_fname);
+ }
+ ap_rputs("
", r);
+ for (modp = top_module; modp; modp = modp->next) {
+ if (!r->args || !strcasecmp(modp->name, r->args)) {
+ ap_rprintf(r, "- Module Name: "
+ "%s\n",
+ modp->name, modp->name);
+ ap_rputs("
- Content handlers:", r);
+ hand = modp->handlers;
+ if (hand) {
+ while (hand) {
+ if (hand->content_type) {
+ ap_rprintf(r, " %s\n", hand->content_type);
+ }
+ else {
+ break;
+ }
+ hand++;
+ if (hand && hand->content_type) {
+ ap_rputs(",", r);
+ }
+ }
+ }
+ else {
+ ap_rputs(" none", r);
+ }
+ ap_rputs("
- Configuration Phase Participation: \n",
+ r);
+ if (modp->child_init) {
+ ap_rputs("Child Init", r);
+ comma = 1;
+ }
+ if (modp->create_dir_config) {
+ if (comma) {
+ ap_rputs(", ", r);
+ }
+ ap_rputs("Create Directory Config", r);
+ comma = 1;
+ }
+ if (modp->merge_dir_config) {
+ if (comma) {
+ ap_rputs(", ", r);
+ }
+ ap_rputs("Merge Directory Configs", r);
+ comma = 1;
+ }
+ if (modp->create_server_config) {
+ if (comma) {
+ ap_rputs(", ", r);
+ }
+ ap_rputs("Create Server Config", r);
+ comma = 1;
+ }
+ if (modp->merge_server_config) {
+ if (comma) {
+ ap_rputs(", ", r);
+ }
+ ap_rputs("Merge Server Configs", r);
+ comma = 1;
+ }
+ if (modp->child_exit) {
+ if (comma) {
+ ap_rputs(", ", r);
+ }
+ ap_rputs("Child Exit", r);
+ comma = 1;
+ }
+ if (!comma)
+ ap_rputs(" none", r);
+ comma = 0;
+ ap_rputs("
- Request Phase Participation: \n",
+ r);
+ if (modp->post_read_request) {
+ ap_rputs("Post-Read Request", r);
+ comma = 1;
+ }
+ if (modp->header_parser) {
+ if (comma) {
+ ap_rputs(", ", r);
+ }
+ ap_rputs("Header Parse", r);
+ comma = 1;
+ }
+ if (modp->translate_handler) {
+ if (comma) {
+ ap_rputs(", ", r);
+ }
+ ap_rputs("Translate Path", r);
+ comma = 1;
+ }
+ if (modp->access_checker) {
+ if (comma) {
+ ap_rputs(", ", r);
+ }
+ ap_rputs("Check Access", r);
+ comma = 1;
+ }
+ if (modp->ap_check_user_id) {
+ if (comma) {
+ ap_rputs(", ", r);
+ }
+ ap_rputs("Verify User ID", r);
+ comma = 1;
+ }
+ if (modp->auth_checker) {
+ if (comma) {
+ ap_rputs(", ", r);
+ }
+ ap_rputs("Verify User Access", r);
+ comma = 1;
+ }
+ if (modp->type_checker) {
+ if (comma) {
+ ap_rputs(", ", r);
+ }
+ ap_rputs("Check Type", r);
+ comma = 1;
+ }
+ if (modp->fixer_upper) {
+ if (comma) {
+ ap_rputs(", ", r);
+ }
+ ap_rputs("Fixups", r);
+ comma = 1;
+ }
+ if (modp->logger) {
+ if (comma) {
+ ap_rputs(", ", r);
+ }
+ ap_rputs("Logging", r);
+ comma = 1;
+ }
+ if (!comma)
+ ap_rputs(" none", r);
+ comma = 0;
+ ap_rputs("
- Module Directives: ", r);
+ cmd = modp->cmds;
+ if (cmd) {
+ while (cmd) {
+ if (cmd->name) {
+ ap_rprintf(r, "
- %s - ",
+ mod_info_html_cmd_string(cmd->name,
+ buf, sizeof(buf)));
+ if (cmd->errmsg) {
+ ap_rputs(cmd->errmsg, r);
+ }
+ ap_rputs("\n", r);
+ }
+ else {
+ break;
+ }
+ cmd++;
+ }
+ ap_rputs("
- Current Configuration:\n", r);
+ mod_info_module_cmds(r, mod_info_cfg_httpd, modp->cmds,
+ "httpd.conf");
+ mod_info_module_cmds(r, mod_info_cfg_srm, modp->cmds,
+ "srm.conf");
+ mod_info_module_cmds(r, mod_info_cfg_access, modp->cmds,
+ "access.conf");
+ }
+ else {
+ ap_rputs(" none\n", r);
+ }
+ more_info = find_more_info(serv, modp->name);
+ if (more_info) {
+ ap_rputs("
- Additional Information:\n
- ",
+ r);
+ ap_rputs(more_info, r);
+ }
+ ap_rputs("
\n", r);
+ if (r->args) {
+ break;
+ }
+ }
+ }
+ if (!modp && r->args && strcasecmp(r->args, "server")) {
+ ap_rputs("No such module\n", r);
+ }
+ }
+ else {
+ for (modp = top_module; modp; modp = modp->next) {
+ ap_rputs(modp->name, r);
+ if (modp->next) {
+ ap_rputs(" ", r);
+ }
+ }
+ }
+ ap_rputs(" \n", r);
+ ap_rputs(ap_psignature("",r), r);
+ ap_rputs("\n", r);
+ /* Done, turn off timeout, close file and return */
+ ap_kill_timeout(r);
+ return 0;
+}
+
+static const char *add_module_info(cmd_parms *cmd, void *dummy, char *name,
+ char *info)
+{
+ server_rec *s = cmd->server;
+ info_svr_conf *conf = (info_svr_conf *) ap_get_module_config(s->module_config,
+ &info_module);
+ info_entry *new = ap_push_array(conf->more_info);
+
+ new->name = name;
+ new->info = info;
+ return NULL;
+}
+
+static const command_rec info_cmds[] =
+{
+ {"AddModuleInfo", add_module_info, NULL, RSRC_CONF, TAKE2,
+ "a module name and additional information on that module"},
+ {NULL}
+};
+
+static const handler_rec info_handlers[] =
+{
+ {"server-info", display_info},
+ {NULL}
+};
+
+module MODULE_VAR_EXPORT info_module =
+{
+ STANDARD_MODULE_STUFF,
+ NULL, /* initializer */
+ NULL, /* dir config creater */
+ NULL, /* dir merger --- default is to override */
+ create_info_config, /* server config */
+ merge_info_config, /* merge server config */
+ info_cmds, /* command table */
+ info_handlers, /* handlers */
+ NULL, /* filename translation */
+ NULL, /* check_user_id */
+ NULL, /* check auth */
+ NULL, /* check access */
+ NULL, /* type_checker */
+ NULL, /* fixups */
+ NULL, /* logger */
+ NULL, /* header parser */
+ NULL, /* child_init */
+ NULL, /* child_exit */
+ NULL /* post read-request */
+};
diff --git a/modules/generators/mod_info.dsp b/modules/generators/mod_info.dsp
new file mode 100644
index 00000000000..cf856463352
--- /dev/null
+++ b/modules/generators/mod_info.dsp
@@ -0,0 +1,112 @@
+# Microsoft Developer Studio Project File - Name="ApacheModuleInfo" - Package Owner=<4>
+# Microsoft Developer Studio Generated Build File, Format Version 5.00
+# ** DO NOT EDIT **
+
+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102
+
+CFG=ApacheModuleInfo - Win32 Release
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,
+!MESSAGE use the Export Makefile command and run
+!MESSAGE
+!MESSAGE NMAKE /f "ApacheModuleInfo.mak".
+!MESSAGE
+!MESSAGE You can specify a configuration when running NMAKE
+!MESSAGE by defining the macro CFG on the command line. For example:
+!MESSAGE
+!MESSAGE NMAKE /f "ApacheModuleInfo.mak" CFG="ApacheModuleInfo - Win32 Release"
+!MESSAGE
+!MESSAGE Possible choices for configuration are:
+!MESSAGE
+!MESSAGE "ApacheModuleInfo - Win32 Release" (based on\
+ "Win32 (x86) Dynamic-Link Library")
+!MESSAGE "ApacheModuleInfo - Win32 Debug" (based on\
+ "Win32 (x86) Dynamic-Link Library")
+!MESSAGE
+
+# Begin Project
+# PROP Scc_ProjName ""
+# PROP Scc_LocalPath ""
+CPP=cl.exe
+MTL=midl.exe
+RSC=rc.exe
+
+!IF "$(CFG)" == "ApacheModuleInfo - Win32 Release"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir ".\Release"
+# PROP BASE Intermediate_Dir ".\Release"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir ".\ApacheModuleInfoR"
+# PROP Intermediate_Dir ".\ApacheModuleInfoR"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /c
+# ADD CPP /nologo /MD /W3 /GX /O2 /I "..\..\include" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "SHARED_MODULE" /YX /FD /c
+# ADD BASE MTL /nologo /D "NDEBUG" /win32
+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
+# ADD BASE RSC /l 0x809 /d "NDEBUG"
+# ADD RSC /l 0x809 /d "NDEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /machine:I386
+# ADD LINK32 ..\..\CoreR\ApacheCore.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /dll /machine:I386
+
+!ELSEIF "$(CFG)" == "ApacheModuleInfo - Win32 Debug"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 1
+# PROP BASE Output_Dir ".\Debug"
+# PROP BASE Intermediate_Dir ".\Debug"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 1
+# PROP Output_Dir ".\ApacheModuleInfoD"
+# PROP Intermediate_Dir ".\ApacheModuleInfoD"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /c
+# ADD CPP /nologo /MDd /W3 /Gm /GX /Zi /Od /I "..\..\include" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "SHARED_MODULE" /YX /FD /c
+# ADD BASE MTL /nologo /D "_DEBUG" /win32
+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
+# ADD BASE RSC /l 0x809 /d "_DEBUG"
+# ADD RSC /l 0x809 /d "_DEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /debug /machine:I386
+# ADD LINK32 ..\..\CoreD\ApacheCore.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /dll /debug /machine:I386
+
+!ENDIF
+
+# Begin Target
+
+# Name "ApacheModuleInfo - Win32 Release"
+# Name "ApacheModuleInfo - Win32 Debug"
+# Begin Group "Source Files"
+
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;hpj;bat;for;f90"
+# Begin Source File
+
+SOURCE=..\..\modules\standard\mod_info.c
+# End Source File
+# End Group
+# Begin Group "Header Files"
+
+# PROP Default_Filter "h;hpp;hxx;hm;inl;fi;fd"
+# Begin Source File
+
+SOURCE=.\readdir.h
+# End Source File
+# End Group
+# Begin Group "Resource Files"
+
+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe"
+# End Group
+# End Target
+# End Project
diff --git a/modules/generators/mod_status.c b/modules/generators/mod_status.c
new file mode 100644
index 00000000000..88fc0870908
--- /dev/null
+++ b/modules/generators/mod_status.c
@@ -0,0 +1,773 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+/* Status Module. Display lots of internal data about how Apache is
+ * performing and the state of all children processes.
+ *
+ * To enable this, add the following lines into any config file:
+ *
+ *
+ * SetHandler server-status
+ *
+ *
+ * You may want to protect this location by password or domain so no one
+ * else can look at it. Then you can access the statistics with a URL like:
+ *
+ * http://your_server_name/server-status
+ *
+ * /server-status - Returns page using tables
+ * /server-status?notable - Returns page for browsers without table support
+ * /server-status?refresh - Returns page with 1 second refresh
+ * /server-status?refresh=6 - Returns page with refresh every 6 seconds
+ * /server-status?auto - Returns page with data for automatic parsing
+ *
+ * Mark Cox, mark@ukweb.com, November 1995
+ *
+ * 12.11.95 Initial version for www.telescope.org
+ * 13.3.96 Updated to remove rprintf's [Mark]
+ * 18.3.96 Added CPU usage, process information, and tidied [Ben Laurie]
+ * 18.3.96 Make extra Scoreboard variables #definable
+ * 25.3.96 Make short report have full precision [Ben Laurie suggested]
+ * 25.3.96 Show uptime better [Mark/Ben Laurie]
+ * 29.3.96 Better HTML and explanation [Mark/Rob Hartill suggested]
+ * 09.4.96 Added message for non-STATUS compiled version
+ * 18.4.96 Added per child and per slot counters [Jim Jagielski]
+ * 01.5.96 Table format, cleanup, even more spiffy data [Chuck Murcko/Jim J.]
+ * 18.5.96 Adapted to use new rprintf() routine, incidentally fixing a missing
+ * piece in short reports [Ben Laurie]
+ * 21.5.96 Additional Status codes (DNS and LOGGING only enabled if
+ * extended STATUS is enabled) [George Burgyan/Jim J.]
+ * 10.8.98 Allow for extended status info at runtime (no more STATUS)
+ * [Jim J.]
+ */
+
+#define CORE_PRIVATE
+#include "httpd.h"
+#include "http_config.h"
+#include "http_core.h"
+#include "http_protocol.h"
+#include "http_conf_globals.h" /* for ap_extended_status */
+#include "http_main.h"
+#include "util_script.h"
+#include
+#include "scoreboard.h"
+#include "http_log.h"
+
+#ifdef NEXT
+#if (NX_CURRENT_COMPILER_RELEASE == 410)
+#ifdef m68k
+#define HZ 64
+#else
+#define HZ 100
+#endif
+#else
+#include
+#endif
+#endif /* NEXT */
+
+#define STATUS_MAXLINE 64
+
+#define KBYTE 1024
+#define MBYTE 1048576L
+#define GBYTE 1073741824L
+
+#ifndef DEFAULT_TIME_FORMAT
+#define DEFAULT_TIME_FORMAT "%A, %d-%b-%Y %H:%M:%S %Z"
+#endif
+
+module MODULE_VAR_EXPORT status_module;
+
+/*
+ *command-related code. This is here to prevent use of ExtendedStatus
+ * without status_module included.
+ */
+static const char *set_extended_status(cmd_parms *cmd, void *dummy, char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+ if (err != NULL) {
+ return err;
+ }
+ if (!strcasecmp(arg, "off") || !strcmp(arg, "0")) {
+ ap_extended_status = 0;
+ }
+ else {
+ ap_extended_status = 1;
+ }
+ return NULL;
+}
+
+static const command_rec status_module_cmds[] =
+{
+ { "ExtendedStatus", set_extended_status, NULL, RSRC_CONF, TAKE1,
+ "\"On\" to enable extended status information, \"Off\" to disable" },
+ {NULL}
+};
+
+/* Format the number of bytes nicely */
+static void format_byte_out(request_rec *r, unsigned long bytes)
+{
+ if (bytes < (5 * KBYTE))
+ ap_rprintf(r, "%d B", (int) bytes);
+ else if (bytes < (MBYTE / 2))
+ ap_rprintf(r, "%.1f kB", (float) bytes / KBYTE);
+ else if (bytes < (GBYTE / 2))
+ ap_rprintf(r, "%.1f MB", (float) bytes / MBYTE);
+ else
+ ap_rprintf(r, "%.1f GB", (float) bytes / GBYTE);
+}
+
+static void format_kbyte_out(request_rec *r, unsigned long kbytes)
+{
+ if (kbytes < KBYTE)
+ ap_rprintf(r, "%d kB", (int) kbytes);
+ else if (kbytes < MBYTE)
+ ap_rprintf(r, "%.1f MB", (float) kbytes / KBYTE);
+ else
+ ap_rprintf(r, "%.1f GB", (float) kbytes / MBYTE);
+}
+
+static void show_time(request_rec *r, time_t tsecs)
+{
+ long days, hrs, mins, secs;
+
+ secs = tsecs % 60;
+ tsecs /= 60;
+ mins = tsecs % 60;
+ tsecs /= 60;
+ hrs = tsecs % 24;
+ days = tsecs / 24;
+ if (days)
+ ap_rprintf(r, " %ld day%s", days, days == 1 ? "" : "s");
+ if (hrs)
+ ap_rprintf(r, " %ld hour%s", hrs, hrs == 1 ? "" : "s");
+ if (mins)
+ ap_rprintf(r, " %ld minute%s", mins, mins == 1 ? "" : "s");
+ if (secs)
+ ap_rprintf(r, " %ld second%s", secs, secs == 1 ? "" : "s");
+}
+
+/* Main handler for x-httpd-status requests */
+
+/* ID values for command table */
+
+#define STAT_OPT_END -1
+#define STAT_OPT_REFRESH 0
+#define STAT_OPT_NOTABLE 1
+#define STAT_OPT_AUTO 2
+
+struct stat_opt {
+ int id;
+ const char *form_data_str;
+ const char *hdr_out_str;
+};
+
+static const struct stat_opt status_options[] = /* see #defines above */
+{
+ {STAT_OPT_REFRESH, "refresh", "Refresh"},
+ {STAT_OPT_NOTABLE, "notable", NULL},
+ {STAT_OPT_AUTO, "auto", NULL},
+ {STAT_OPT_END, NULL, NULL}
+};
+
+static char status_flags[SERVER_NUM_STATUS];
+
+static int status_handler(request_rec *r)
+{
+ char *loc;
+ time_t nowtime = time(NULL);
+ time_t up_time;
+ int i, res;
+ int ready = 0;
+ int busy = 0;
+ unsigned long count = 0;
+ unsigned long lres, bytes;
+ unsigned long my_lres, my_bytes, conn_bytes;
+ unsigned short conn_lres;
+ unsigned long bcount = 0;
+ unsigned long kbcount = 0;
+ long req_time;
+#ifndef NO_TIMES
+#ifdef _SC_CLK_TCK
+ float tick = sysconf(_SC_CLK_TCK);
+#else
+ float tick = HZ;
+#endif
+#endif
+ int short_report = 0;
+ int no_table_report = 0;
+ short_score score_record;
+ parent_score ps_record;
+ char stat_buffer[HARD_SERVER_LIMIT];
+ int pid_buffer[HARD_SERVER_LIMIT];
+ clock_t tu, ts, tcu, tcs;
+ server_rec *vhost;
+
+ tu = ts = tcu = tcs = 0;
+
+ if (!ap_exists_scoreboard_image()) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Server status unavailable in inetd mode");
+ return HTTP_INTERNAL_SERVER_ERROR;
+ }
+ r->allowed = (1 << M_GET);
+ if (r->method_number != M_GET)
+ return DECLINED;
+
+ r->content_type = "text/html";
+
+ /*
+ * Simple table-driven form data set parser that lets you alter the header
+ */
+
+ if (r->args) {
+ i = 0;
+ while (status_options[i].id != STAT_OPT_END) {
+ if ((loc = strstr(r->args, status_options[i].form_data_str)) != NULL) {
+ switch (status_options[i].id) {
+ case STAT_OPT_REFRESH:
+ if (*(loc + strlen(status_options[i].form_data_str)) == '=')
+ ap_table_set(r->headers_out,
+ status_options[i].hdr_out_str,
+ loc + strlen(status_options[i].hdr_out_str) + 1);
+ else
+ ap_table_set(r->headers_out,
+ status_options[i].hdr_out_str, "1");
+ break;
+ case STAT_OPT_NOTABLE:
+ no_table_report = 1;
+ break;
+ case STAT_OPT_AUTO:
+ r->content_type = "text/plain";
+ short_report = 1;
+ break;
+ }
+ }
+ i++;
+ }
+ }
+
+ ap_send_http_header(r);
+
+ if (r->header_only)
+ return 0;
+
+ ap_sync_scoreboard_image();
+ for (i = 0; i < HARD_SERVER_LIMIT; ++i) {
+ score_record = ap_scoreboard_image->servers[i];
+ ps_record = ap_scoreboard_image->parent[i];
+ res = score_record.status;
+ stat_buffer[i] = status_flags[res];
+ pid_buffer[i] = (int) ps_record.pid;
+ if (res == SERVER_READY)
+ ready++;
+ else if (res != SERVER_DEAD)
+ busy++;
+ if (ap_extended_status) {
+ lres = score_record.access_count;
+ bytes = score_record.bytes_served;
+ if (lres != 0 || (res != SERVER_READY && res != SERVER_DEAD)) {
+#ifndef NO_TIMES
+ tu += score_record.times.tms_utime;
+ ts += score_record.times.tms_stime;
+ tcu += score_record.times.tms_cutime;
+ tcs += score_record.times.tms_cstime;
+#endif /* NO_TIMES */
+ count += lres;
+ bcount += bytes;
+ if (bcount >= KBYTE) {
+ kbcount += (bcount >> 10);
+ bcount = bcount & 0x3ff;
+ }
+ }
+ }
+ }
+
+ up_time = nowtime - ap_restart_time;
+
+ ap_hard_timeout("send status info", r);
+
+ if (!short_report) {
+ ap_rputs(DOCTYPE_HTML_3_2
+ "\nApache Status\n\n",
+ r);
+ ap_rputs("Apache Server Status for ", r);
+ ap_rvputs(r, ap_get_server_name(r), "\n\n", NULL);
+ ap_rvputs(r, "Server Version: ",
+ ap_get_server_version(), " \n", NULL);
+ ap_rvputs(r, "Server Built: ",
+ ap_get_server_built(), " \n \n", NULL);
+ ap_rvputs(r, "Current Time: ",
+ ap_ht_time(r->pool, nowtime, DEFAULT_TIME_FORMAT, 0), " \n", NULL);
+ ap_rvputs(r, "Restart Time: ",
+ ap_ht_time(r->pool, ap_restart_time, DEFAULT_TIME_FORMAT, 0),
+ " \n", NULL);
+ ap_rprintf(r, "Parent Server Generation: %d \n", (int) ap_my_generation);
+ ap_rputs("Server uptime: ", r);
+ show_time(r, up_time);
+ ap_rputs(" \n", r);
+ }
+
+ if (ap_extended_status) {
+ if (short_report) {
+ ap_rprintf(r, "Total Accesses: %lu\nTotal kBytes: %lu\n",
+ count, kbcount);
+
+#ifndef NO_TIMES
+ /* Allow for OS/2 not having CPU stats */
+ if (ts || tu || tcu || tcs)
+ ap_rprintf(r, "CPULoad: %g\n",
+ (tu + ts + tcu + tcs) / tick / up_time * 100.);
+#endif
+
+ ap_rprintf(r, "Uptime: %ld\n", (long) (up_time));
+ if (up_time > 0)
+ ap_rprintf(r, "ReqPerSec: %g\n",
+ (float) count / (float) up_time);
+
+ if (up_time > 0)
+ ap_rprintf(r, "BytesPerSec: %g\n",
+ KBYTE * (float) kbcount / (float) up_time);
+
+ if (count > 0)
+ ap_rprintf(r, "BytesPerReq: %g\n",
+ KBYTE * (float) kbcount / (float) count);
+ }
+ else { /* !short_report */
+ ap_rprintf(r, "Total accesses: %lu - Total Traffic: ", count);
+ format_kbyte_out(r, kbcount);
+
+#ifndef NO_TIMES
+ /* Allow for OS/2 not having CPU stats */
+ ap_rputs(" \n", r);
+ ap_rprintf(r, "CPU Usage: u%g s%g cu%g cs%g",
+ tu / tick, ts / tick, tcu / tick, tcs / tick);
+
+ if (ts || tu || tcu || tcs)
+ ap_rprintf(r, " - %.3g%% CPU load",
+ (tu + ts + tcu + tcs) / tick / up_time * 100.);
+#endif
+
+ ap_rputs(" \n", r);
+
+ if (up_time > 0)
+ ap_rprintf(r, "%.3g requests/sec - ",
+ (float) count / (float) up_time);
+
+ if (up_time > 0) {
+ format_byte_out(r, KBYTE * (float) kbcount / (float) up_time);
+ ap_rputs("/second - ", r);
+ }
+
+ if (count > 0) {
+ format_byte_out(r, KBYTE * (float) kbcount / (float) count);
+ ap_rputs("/request", r);
+ }
+
+ ap_rputs(" \n", r);
+ } /* short_report */
+ } /* ap_extended_status */
+
+ if (!short_report)
+ ap_rprintf(r, "\n%d requests currently being processed, %d idle servers\n"
+ ,busy, ready);
+ else
+ ap_rprintf(r, "BusyServers: %d\nIdleServers: %d\n", busy, ready);
+
+ /* send the scoreboard 'table' out */
+
+ if (!short_report)
+ ap_rputs("", r);
+ else
+ ap_rputs("Scoreboard: ", r);
+
+ for (i = 0; i < HARD_SERVER_LIMIT; ++i) {
+ ap_rputc(stat_buffer[i], r);
+ if ((i % STATUS_MAXLINE == (STATUS_MAXLINE - 1)) && !short_report)
+ ap_rputs("\n", r);
+ }
+
+ if (short_report)
+ ap_rputs("\n", r);
+ else {
+ ap_rputs(" \n", r);
+ ap_rputs("Scoreboard Key: \n", r);
+ ap_rputs("\"_ \" Waiting for Connection, \n", r);
+ ap_rputs("\"S \" Starting up, \n", r);
+ ap_rputs("\"R \" Reading Request, \n", r);
+ ap_rputs("\"W \" Sending Reply, \n", r);
+ ap_rputs("\"K \" Keepalive (read), \n", r);
+ ap_rputs("\"D \" DNS Lookup, \n", r);
+ ap_rputs("\"L \" Logging, \n", r);
+ ap_rputs("\"G \" Gracefully finishing, \n", r);
+ ap_rputs("\". \" Open slot with no current process\n", r);
+ ap_rputs(" \n", r);
+ if (!ap_extended_status) {
+ int j = 0;
+ ap_rputs("PID Key: \n", r);
+ ap_rputs(" \n", r);
+ for (i = 0; i < HARD_SERVER_LIMIT; ++i) {
+ if (stat_buffer[i] != '.') {
+ ap_rprintf(r, " %d in state: %c ", pid_buffer[i],
+ stat_buffer[i]);
+ if (++j >= 3) {
+ ap_rputs("\n", r);
+ j = 0;
+ } else
+ ap_rputs(",", r);
+ }
+ }
+ ap_rputs("\n", r);
+ ap_rputs(" \n", r);
+ }
+ }
+
+ if (ap_extended_status) {
+ if (!short_report) {
+ if (no_table_report)
+ ap_rputs("
Server Details\n\n", r);
+ else
+#ifdef NO_TIMES
+ /* Allow for OS/2 not having CPU stats */
+ ap_rputs("\n\n Srv | PID | Acc | M\n | SS | Req | Conn | Child | Slot | Client | VHost | Request | \n\n", r);
+#else
+ ap_rputs("\n\n Srv | PID | Acc | M | CPU\n | SS | Req | Conn | Child | Slot | Client | VHost | Request | \n\n", r);
+#endif
+ }
+
+ for (i = 0; i < HARD_SERVER_LIMIT; ++i) {
+ score_record = ap_scoreboard_image->servers[i];
+ ps_record = ap_scoreboard_image->parent[i];
+ vhost = score_record.vhostrec;
+ if (ps_record.generation != ap_my_generation) {
+ vhost = NULL;
+ }
+
+#if defined(NO_GETTIMEOFDAY)
+#ifndef NO_TIMES
+ if (score_record.start_time == (clock_t) 0)
+#endif /* NO_TIMES */
+ req_time = 0L;
+#ifndef NO_TIMES
+ else {
+ req_time = score_record.stop_time - score_record.start_time;
+ req_time = (req_time * 1000) / (int) tick;
+ }
+#endif /* NO_TIMES */
+#else
+ if (score_record.start_time.tv_sec == 0L &&
+ score_record.start_time.tv_usec == 0L)
+ req_time = 0L;
+ else
+ req_time =
+ ((score_record.stop_time.tv_sec - score_record.start_time.tv_sec) * 1000) +
+ ((score_record.stop_time.tv_usec - score_record.start_time.tv_usec) / 1000);
+#endif
+ if (req_time < 0L)
+ req_time = 0L;
+
+ lres = score_record.access_count;
+ my_lres = score_record.my_access_count;
+ conn_lres = score_record.conn_count;
+ bytes = score_record.bytes_served;
+ my_bytes = score_record.my_bytes_served;
+ conn_bytes = score_record.conn_bytes;
+ if (lres != 0 || (score_record.status != SERVER_READY
+ && score_record.status != SERVER_DEAD)) {
+ if (!short_report) {
+ if (no_table_report) {
+ if (score_record.status == SERVER_DEAD)
+ ap_rprintf(r,
+ "Server %d-%d (-): %d|%lu|%lu [",
+ i, (int) ps_record.generation, (int) conn_lres,
+ my_lres, lres);
+ else
+ ap_rprintf(r,
+ "Server %d-%d (%d): %d|%lu|%lu [",
+ i, (int) ps_record.generation,
+ (int) ps_record.pid,
+ (int) conn_lres, my_lres, lres);
+
+ switch (score_record.status) {
+ case SERVER_READY:
+ ap_rputs("Ready", r);
+ break;
+ case SERVER_STARTING:
+ ap_rputs("Starting", r);
+ break;
+ case SERVER_BUSY_READ:
+ ap_rputs("Read", r);
+ break;
+ case SERVER_BUSY_WRITE:
+ ap_rputs("Write", r);
+ break;
+ case SERVER_BUSY_KEEPALIVE:
+ ap_rputs("Keepalive", r);
+ break;
+ case SERVER_BUSY_LOG:
+ ap_rputs("Logging", r);
+ break;
+ case SERVER_BUSY_DNS:
+ ap_rputs("DNS lookup", r);
+ break;
+ case SERVER_DEAD:
+ ap_rputs("Dead", r);
+ break;
+ case SERVER_GRACEFUL:
+ ap_rputs("Graceful", r);
+ break;
+ default:
+ ap_rputs("?STATE?", r);
+ break;
+ }
+#ifdef NO_TIMES
+ /* Allow for OS/2 not having CPU stats */
+ ap_rprintf(r, "]\n %.0f %ld (",
+#else
+
+ ap_rprintf(r, "] u%g s%g cu%g cs%g\n %.0f %ld (",
+ score_record.times.tms_utime / tick,
+ score_record.times.tms_stime / tick,
+ score_record.times.tms_cutime / tick,
+ score_record.times.tms_cstime / tick,
+#endif
+#ifdef OPTIMIZE_TIMEOUTS
+ difftime(nowtime, ps_record.last_rtime),
+#else
+ difftime(nowtime, score_record.last_used),
+#endif
+ (long) req_time);
+ format_byte_out(r, conn_bytes);
+ ap_rputs("|", r);
+ format_byte_out(r, my_bytes);
+ ap_rputs("|", r);
+ format_byte_out(r, bytes);
+ ap_rputs(")\n", r);
+ ap_rprintf(r, " %s {%s} [%s] \n\n",
+ score_record.client,
+ ap_escape_html(r->pool, score_record.request),
+ vhost ? vhost->server_hostname : "(unavailable)");
+ }
+ else { /* !no_table_report */
+ if (score_record.status == SERVER_DEAD)
+ ap_rprintf(r,
+ "%d-%d | - | %d/%lu/%lu",
+ i, (int) ps_record.generation,
+ (int) conn_lres, my_lres, lres);
+ else
+ ap_rprintf(r,
+ " | %d-%d | %d | %d/%lu/%lu",
+ i, (int) ps_record.generation,
+ (int) ps_record.pid, (int) conn_lres,
+ my_lres, lres);
+
+ switch (score_record.status) {
+ case SERVER_READY:
+ ap_rputs(" | _", r);
+ break;
+ case SERVER_STARTING:
+ ap_rputs(" | S", r);
+ break;
+ case SERVER_BUSY_READ:
+ ap_rputs(" | R", r);
+ break;
+ case SERVER_BUSY_WRITE:
+ ap_rputs(" | W", r);
+ break;
+ case SERVER_BUSY_KEEPALIVE:
+ ap_rputs(" | K", r);
+ break;
+ case SERVER_BUSY_LOG:
+ ap_rputs(" | L", r);
+ break;
+ case SERVER_BUSY_DNS:
+ ap_rputs(" | D", r);
+ break;
+ case SERVER_DEAD:
+ ap_rputs(" | .", r);
+ break;
+ case SERVER_GRACEFUL:
+ ap_rputs(" | G", r);
+ break;
+ default:
+ ap_rputs(" | ?", r);
+ break;
+ }
+#ifdef NO_TIMES
+ /* Allow for OS/2 not having CPU stats */
+ ap_rprintf(r, "\n | %.0f | %ld",
+#else
+ ap_rprintf(r, "\n | %.2f | %.0f | %ld",
+ (score_record.times.tms_utime +
+ score_record.times.tms_stime +
+ score_record.times.tms_cutime +
+ score_record.times.tms_cstime) / tick,
+#endif
+#ifdef OPTIMIZE_TIMEOUTS
+ difftime(nowtime, ps_record.last_rtime),
+#else
+ difftime(nowtime, score_record.last_used),
+#endif
+ (long) req_time);
+ ap_rprintf(r, " | %-1.1f | %-2.2f | %-2.2f\n",
+ (float) conn_bytes / KBYTE, (float) my_bytes / MBYTE,
+ (float) bytes / MBYTE);
+ if (score_record.status == SERVER_BUSY_READ)
+ ap_rprintf(r,
+ " | ? | ? | ..reading.. | \n\n");
+ else
+ ap_rprintf(r,
+ "%s | %s | %s\n\n",
+ score_record.client,
+ vhost ? vhost->server_hostname : "(unavailable)",
+ ap_escape_html(r->pool, score_record.request));
+ } /* no_table_report */
+ } /* !short_report */
+ } /* if () */
+ } /* for () */
+
+ if (!(short_report || no_table_report)) {
+#ifdef NO_TIMES
+ ap_rputs(" | \n \
+ \
+\n \
+Srv | Child Server number - generation\n \
+ |
---|
PID | OS process ID\n \
+ |
---|
Acc | Number of accesses this connection / this child / this slot\n \
+ |
---|
M | Mode of operation\n \
+ |
---|
SS | Seconds since beginning of most recent request\n \
+ |
---|
Req | Milliseconds required to process most recent request\n \
+ |
---|
Conn | Kilobytes transferred this connection\n \
+ |
---|
Child | Megabytes transferred this child\n \
+ |
---|
Slot | Total megabytes transferred this slot\n \
+ |
---|
\n", r);
+#else
+ ap_rputs(" \n \
+ \
+\n \
+Srv | Child Server number - generation\n \
+ |
---|
PID | OS process ID\n \
+ |
---|
Acc | Number of accesses this connection / this child / this slot\n \
+ |
---|
M | Mode of operation\n \
+ |
---|
CPU | CPU usage, number of seconds\n \
+ |
---|
SS | Seconds since beginning of most recent request\n \
+ |
---|
Req | Milliseconds required to process most recent request\n \
+ |
---|
Conn | Kilobytes transferred this connection\n \
+ |
---|
Child | Megabytes transferred this child\n \
+ |
---|
Slot | Total megabytes transferred this slot\n \
+ |
---|
\n", r);
+#endif
+ }
+
+ } else {
+
+ ap_rputs(" To obtain a full report with current status information ", r);
+ ap_rputs("you need to use the ExtendedStatus On directive. \n", r);
+
+ }
+
+ if (!short_report) {
+ ap_rputs(ap_psignature(" \n",r), r);
+ ap_rputs("\n", r);
+ }
+
+ ap_kill_timeout(r);
+ return 0;
+}
+
+
+static void status_init(server_rec *s, pool *p)
+{
+ status_flags[SERVER_DEAD] = '.'; /* We don't want to assume these are in */
+ status_flags[SERVER_READY] = '_'; /* any particular order in scoreboard.h */
+ status_flags[SERVER_STARTING] = 'S';
+ status_flags[SERVER_BUSY_READ] = 'R';
+ status_flags[SERVER_BUSY_WRITE] = 'W';
+ status_flags[SERVER_BUSY_KEEPALIVE] = 'K';
+ status_flags[SERVER_BUSY_LOG] = 'L';
+ status_flags[SERVER_BUSY_DNS] = 'D';
+ status_flags[SERVER_GRACEFUL] = 'G';
+}
+
+static const handler_rec status_handlers[] =
+{
+ {STATUS_MAGIC_TYPE, status_handler},
+ {"server-status", status_handler},
+ {NULL}
+};
+
+module MODULE_VAR_EXPORT status_module =
+{
+ STANDARD_MODULE_STUFF,
+ status_init, /* initializer */
+ NULL, /* dir config creater */
+ NULL, /* dir merger --- default is to override */
+ NULL, /* server config */
+ NULL, /* merge server config */
+ status_module_cmds, /* command table */
+ status_handlers, /* handlers */
+ NULL, /* filename translation */
+ NULL, /* check_user_id */
+ NULL, /* check auth */
+ NULL, /* check access */
+ NULL, /* type_checker */
+ NULL, /* fixups */
+ NULL, /* logger */
+ NULL, /* header parser */
+ NULL, /* child_init */
+ NULL, /* child_exit */
+ NULL /* post read-request */
+};
diff --git a/modules/generators/mod_status.dsp b/modules/generators/mod_status.dsp
new file mode 100644
index 00000000000..8bc9271959b
--- /dev/null
+++ b/modules/generators/mod_status.dsp
@@ -0,0 +1,113 @@
+# Microsoft Developer Studio Project File - Name="ApacheModuleStatus" - Package Owner=<4>
+# Microsoft Developer Studio Generated Build File, Format Version 5.00
+# ** DO NOT EDIT **
+
+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102
+
+CFG=ApacheModuleStatus - Win32 Release
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,
+!MESSAGE use the Export Makefile command and run
+!MESSAGE
+!MESSAGE NMAKE /f "ApacheModuleStatus.mak".
+!MESSAGE
+!MESSAGE You can specify a configuration when running NMAKE
+!MESSAGE by defining the macro CFG on the command line. For example:
+!MESSAGE
+!MESSAGE NMAKE /f "ApacheModuleStatus.mak"\
+ CFG="ApacheModuleStatus - Win32 Release"
+!MESSAGE
+!MESSAGE Possible choices for configuration are:
+!MESSAGE
+!MESSAGE "ApacheModuleStatus - Win32 Release" (based on\
+ "Win32 (x86) Dynamic-Link Library")
+!MESSAGE "ApacheModuleStatus - Win32 Debug" (based on\
+ "Win32 (x86) Dynamic-Link Library")
+!MESSAGE
+
+# Begin Project
+# PROP Scc_ProjName ""
+# PROP Scc_LocalPath ""
+CPP=cl.exe
+MTL=midl.exe
+RSC=rc.exe
+
+!IF "$(CFG)" == "ApacheModuleStatus - Win32 Release"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir ".\Release"
+# PROP BASE Intermediate_Dir ".\Release"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir ".\ApacheModuleStatusR"
+# PROP Intermediate_Dir ".\ApacheModuleStatusR"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /c
+# ADD CPP /nologo /MD /W3 /GX /O2 /I "..\..\include" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "SHARED_MODULE" /YX /FD /c
+# ADD BASE MTL /nologo /D "NDEBUG" /win32
+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
+# ADD BASE RSC /l 0x809 /d "NDEBUG"
+# ADD RSC /l 0x809 /d "NDEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /machine:I386
+# ADD LINK32 ..\..\CoreR\ApacheCore.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /dll /machine:I386
+
+!ELSEIF "$(CFG)" == "ApacheModuleStatus - Win32 Debug"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 1
+# PROP BASE Output_Dir ".\Debug"
+# PROP BASE Intermediate_Dir ".\Debug"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 1
+# PROP Output_Dir ".\ApacheModuleStatusD"
+# PROP Intermediate_Dir ".\ApacheModuleStatusD"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /c
+# ADD CPP /nologo /MDd /W3 /Gm /GX /Zi /Od /I "..\..\include" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "SHARED_MODULE" /YX /FD /c
+# ADD BASE MTL /nologo /D "_DEBUG" /win32
+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
+# ADD BASE RSC /l 0x809 /d "_DEBUG"
+# ADD RSC /l 0x809 /d "_DEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /debug /machine:I386
+# ADD LINK32 ..\..\CoreD\ApacheCore.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /dll /debug /machine:I386
+
+!ENDIF
+
+# Begin Target
+
+# Name "ApacheModuleStatus - Win32 Release"
+# Name "ApacheModuleStatus - Win32 Debug"
+# Begin Group "Source Files"
+
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;hpj;bat;for;f90"
+# Begin Source File
+
+SOURCE=..\..\modules\standard\mod_status.c
+# End Source File
+# End Group
+# Begin Group "Header Files"
+
+# PROP Default_Filter "h;hpp;hxx;hm;inl;fi;fd"
+# Begin Source File
+
+SOURCE=.\readdir.h
+# End Source File
+# End Group
+# Begin Group "Resource Files"
+
+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe"
+# End Group
+# End Target
+# End Project
diff --git a/modules/http/.indent.pro b/modules/http/.indent.pro
new file mode 100644
index 00000000000..a9fbe9f9a1f
--- /dev/null
+++ b/modules/http/.indent.pro
@@ -0,0 +1,54 @@
+-i4 -npsl -di0 -br -nce -d0 -cli0 -npcs -nfc1
+-TBUFF
+-TFILE
+-TTRANS
+-TUINT4
+-T_trans
+-Tallow_options_t
+-Tapache_sfio
+-Tarray_header
+-Tbool_int
+-Tbuf_area
+-Tbuff_struct
+-Tbuffy
+-Tcmd_how
+-Tcmd_parms
+-Tcommand_rec
+-Tcommand_struct
+-Tconn_rec
+-Tcore_dir_config
+-Tcore_server_config
+-Tdir_maker_func
+-Tevent
+-Tglobals_s
+-Thandler_func
+-Thandler_rec
+-Tjoblist_s
+-Tlisten_rec
+-Tmerger_func
+-Tmode_t
+-Tmodule
+-Tmodule_struct
+-Tmutex
+-Tn_long
+-Tother_child_rec
+-Toverrides_t
+-Tparent_score
+-Tpid_t
+-Tpiped_log
+-Tpool
+-Trequest_rec
+-Trequire_line
+-Trlim_t
+-Tscoreboard
+-Tsemaphore
+-Tserver_addr_rec
+-Tserver_rec
+-Tserver_rec_chain
+-Tshort_score
+-Ttable
+-Ttable_entry
+-Tthread
+-Tu_wide_int
+-Tvtime_t
+-Twide_int
diff --git a/modules/http/http_core.c b/modules/http/http_core.c
new file mode 100644
index 00000000000..e02d32ec5f4
--- /dev/null
+++ b/modules/http/http_core.c
@@ -0,0 +1,3214 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+#define CORE_PRIVATE
+#include "httpd.h"
+#include "http_config.h"
+#include "http_core.h"
+#include "http_protocol.h" /* For index_of_response(). Grump. */
+#include "http_request.h"
+#include "http_conf_globals.h"
+#include "http_vhost.h"
+#include "http_main.h" /* For the default_handler below... */
+#include "http_log.h"
+#include "rfc1413.h"
+#include "util_md5.h"
+#include "scoreboard.h"
+#include "fnmatch.h"
+
+#ifdef USE_MMAP_FILES
+#include
+
+/* mmap support for static files based on ideas from John Heidemann's
+ * patch against 1.0.5. See
+ * .
+ */
+
+/* Files have to be at least this big before they're mmap()d. This is to deal
+ * with systems where the expense of doing an mmap() and an munmap() outweighs
+ * the benefit for small files. It shouldn't be set lower than 1.
+ */
+#ifndef MMAP_THRESHOLD
+#ifdef SUNOS4
+#define MMAP_THRESHOLD (8*1024)
+#else
+#define MMAP_THRESHOLD 1
+#endif
+#endif
+#endif
+#ifndef MMAP_LIMIT
+#define MMAP_LIMIT (4*1024*1024)
+#endif
+
+/* Server core module... This module provides support for really basic
+ * server operations, including options and commands which control the
+ * operation of other modules. Consider this the bureaucracy module.
+ *
+ * The core module also defines handlers, etc., do handle just enough
+ * to allow a server with the core module ONLY to actually serve documents
+ * (though it slaps DefaultType on all of 'em); this was useful in testing,
+ * but may not be worth preserving.
+ *
+ * This file could almost be mod_core.c, except for the stuff which affects
+ * the http_conf_globals.
+ */
+
+static void *create_core_dir_config(pool *a, char *dir)
+{
+ core_dir_config *conf;
+
+ conf = (core_dir_config *)ap_pcalloc(a, sizeof(core_dir_config));
+ if (!dir || dir[strlen(dir) - 1] == '/') {
+ conf->d = dir;
+ }
+ else if (strncmp(dir, "proxy:", 6) == 0) {
+ conf->d = ap_pstrdup(a, dir);
+ }
+ else {
+ conf->d = ap_pstrcat(a, dir, "/", NULL);
+ }
+ conf->d_is_fnmatch = conf->d ? (ap_is_fnmatch(conf->d) != 0) : 0;
+ conf->d_components = conf->d ? ap_count_dirs(conf->d) : 0;
+
+ conf->opts = dir ? OPT_UNSET : OPT_UNSET|OPT_ALL;
+ conf->opts_add = conf->opts_remove = OPT_NONE;
+ conf->override = dir ? OR_UNSET : OR_UNSET|OR_ALL;
+
+ conf->content_md5 = 2;
+
+ conf->use_canonical_name = USE_CANONICAL_NAME_UNSET;
+
+ conf->hostname_lookups = HOSTNAME_LOOKUP_UNSET;
+ conf->do_rfc1413 = DEFAULT_RFC1413 | 2; /* set bit 1 to indicate default */
+ conf->satisfy = SATISFY_NOSPEC;
+
+#ifdef RLIMIT_CPU
+ conf->limit_cpu = NULL;
+#endif
+#if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
+ conf->limit_mem = NULL;
+#endif
+#ifdef RLIMIT_NPROC
+ conf->limit_nproc = NULL;
+#endif
+
+ conf->limit_req_body = 0;
+ conf->sec = ap_make_array(a, 2, sizeof(void *));
+#ifdef WIN32
+ conf->script_interpreter_source = INTERPRETER_SOURCE_UNSET;
+#endif
+
+ conf->server_signature = srv_sig_unset;
+
+ return (void *)conf;
+}
+
+static void *merge_core_dir_configs(pool *a, void *basev, void *newv)
+{
+ core_dir_config *base = (core_dir_config *)basev;
+ core_dir_config *new = (core_dir_config *)newv;
+ core_dir_config *conf;
+ int i;
+
+ conf = (core_dir_config *)ap_palloc(a, sizeof(core_dir_config));
+ memcpy((char *)conf, (const char *)base, sizeof(core_dir_config));
+ if (base->response_code_strings) {
+ conf->response_code_strings =
+ ap_palloc(a, sizeof(*conf->response_code_strings)
+ * RESPONSE_CODES);
+ memcpy(conf->response_code_strings, base->response_code_strings,
+ sizeof(*conf->response_code_strings) * RESPONSE_CODES);
+ }
+
+ conf->d = new->d;
+ conf->d_is_fnmatch = new->d_is_fnmatch;
+ conf->d_components = new->d_components;
+ conf->r = new->r;
+
+ if (new->opts & OPT_UNSET) {
+ /* there was no explicit setting of new->opts, so we merge
+ * preserve the invariant (opts_add & opts_remove) == 0
+ */
+ conf->opts_add = (conf->opts_add & ~new->opts_remove) | new->opts_add;
+ conf->opts_remove = (conf->opts_remove & ~new->opts_add)
+ | new->opts_remove;
+ conf->opts = (conf->opts & ~conf->opts_remove) | conf->opts_add;
+ if ((base->opts & OPT_INCNOEXEC) && (new->opts & OPT_INCLUDES)) {
+ conf->opts = (conf->opts & ~OPT_INCNOEXEC) | OPT_INCLUDES;
+ }
+ }
+ else {
+ /* otherwise we just copy, because an explicit opts setting
+ * overrides all earlier +/- modifiers
+ */
+ conf->opts = new->opts;
+ conf->opts_add = new->opts_add;
+ conf->opts_remove = new->opts_remove;
+ }
+
+ if (!(new->override & OR_UNSET)) {
+ conf->override = new->override;
+ }
+ if (new->ap_default_type) {
+ conf->ap_default_type = new->ap_default_type;
+ }
+
+ if (new->ap_auth_type) {
+ conf->ap_auth_type = new->ap_auth_type;
+ }
+ if (new->ap_auth_name) {
+ conf->ap_auth_name = new->ap_auth_name;
+ }
+ if (new->ap_requires) {
+ conf->ap_requires = new->ap_requires;
+ }
+
+ if (new->response_code_strings) {
+ if (conf->response_code_strings == NULL) {
+ conf->response_code_strings = ap_palloc(a,
+ sizeof(*conf->response_code_strings) * RESPONSE_CODES);
+ memcpy(conf->response_code_strings, new->response_code_strings,
+ sizeof(*conf->response_code_strings) * RESPONSE_CODES);
+ }
+ else {
+ for (i = 0; i < RESPONSE_CODES; ++i) {
+ if (new->response_code_strings[i] != NULL) {
+ conf->response_code_strings[i]
+ = new->response_code_strings[i];
+ }
+ }
+ }
+ }
+ if (new->hostname_lookups != HOSTNAME_LOOKUP_UNSET) {
+ conf->hostname_lookups = new->hostname_lookups;
+ }
+ if ((new->do_rfc1413 & 2) == 0) {
+ conf->do_rfc1413 = new->do_rfc1413;
+ }
+ if ((new->content_md5 & 2) == 0) {
+ conf->content_md5 = new->content_md5;
+ }
+ if (new->use_canonical_name != USE_CANONICAL_NAME_UNSET) {
+ conf->use_canonical_name = new->use_canonical_name;
+ }
+
+#ifdef RLIMIT_CPU
+ if (new->limit_cpu) {
+ conf->limit_cpu = new->limit_cpu;
+ }
+#endif
+#if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
+ if (new->limit_mem) {
+ conf->limit_mem = new->limit_mem;
+ }
+#endif
+#ifdef RLIMIT_NPROC
+ if (new->limit_nproc) {
+ conf->limit_nproc = new->limit_nproc;
+ }
+#endif
+
+ if (new->limit_req_body) {
+ conf->limit_req_body = new->limit_req_body;
+ }
+ conf->sec = ap_append_arrays(a, base->sec, new->sec);
+
+ if (new->satisfy != SATISFY_NOSPEC) {
+ conf->satisfy = new->satisfy;
+ }
+
+#ifdef WIN32
+ if (new->script_interpreter_source != INTERPRETER_SOURCE_UNSET) {
+ conf->script_interpreter_source = new->script_interpreter_source;
+ }
+#endif
+
+ if (new->server_signature != srv_sig_unset) {
+ conf->server_signature = new->server_signature;
+ }
+
+ return (void*)conf;
+}
+
+static void *create_core_server_config(pool *a, server_rec *s)
+{
+ core_server_config *conf;
+ int is_virtual = s->is_virtual;
+
+ conf = (core_server_config *)ap_pcalloc(a, sizeof(core_server_config));
+#ifdef GPROF
+ conf->gprof_dir = NULL;
+#endif
+ conf->access_name = is_virtual ? NULL : DEFAULT_ACCESS_FNAME;
+ conf->ap_document_root = is_virtual ? NULL : DOCUMENT_LOCATION;
+ conf->sec = ap_make_array(a, 40, sizeof(void *));
+ conf->sec_url = ap_make_array(a, 40, sizeof(void *));
+
+ return (void *)conf;
+}
+
+static void *merge_core_server_configs(pool *p, void *basev, void *virtv)
+{
+ core_server_config *base = (core_server_config *)basev;
+ core_server_config *virt = (core_server_config *)virtv;
+ core_server_config *conf;
+
+ conf = (core_server_config *)ap_pcalloc(p, sizeof(core_server_config));
+ *conf = *virt;
+ if (!conf->access_name) {
+ conf->access_name = base->access_name;
+ }
+ if (!conf->ap_document_root) {
+ conf->ap_document_root = base->ap_document_root;
+ }
+ conf->sec = ap_append_arrays(p, base->sec, virt->sec);
+ conf->sec_url = ap_append_arrays(p, base->sec_url, virt->sec_url);
+
+ return conf;
+}
+
+/* Add per-directory configuration entry (for section);
+ * these are part of the core server config.
+ */
+
+CORE_EXPORT(void) ap_add_per_dir_conf(server_rec *s, void *dir_config)
+{
+ core_server_config *sconf = ap_get_module_config(s->module_config,
+ &core_module);
+ void **new_space = (void **)ap_push_array(sconf->sec);
+
+ *new_space = dir_config;
+}
+
+CORE_EXPORT(void) ap_add_per_url_conf(server_rec *s, void *url_config)
+{
+ core_server_config *sconf = ap_get_module_config(s->module_config,
+ &core_module);
+ void **new_space = (void **)ap_push_array(sconf->sec_url);
+
+ *new_space = url_config;
+}
+
+CORE_EXPORT(void) ap_add_file_conf(core_dir_config *conf, void *url_config)
+{
+ void **new_space = (void **)ap_push_array(conf->sec);
+
+ *new_space = url_config;
+}
+
+/* core_reorder_directories reorders the directory sections such that the
+ * 1-component sections come first, then the 2-component, and so on, finally
+ * followed by the "special" sections. A section is "special" if it's a regex,
+ * or if it doesn't start with / -- consider proxy: matching. All movements
+ * are in-order to preserve the ordering of the sections from the config files.
+ * See directory_walk().
+ */
+
+#ifdef HAVE_DRIVE_LETTERS
+#define IS_SPECIAL(entry_core) \
+ ((entry_core)->r != NULL \
+ || ((entry_core)->d[0] != '/' && (entry_core)->d[1] != ':'))
+#else
+#define IS_SPECIAL(entry_core) \
+ ((entry_core)->r != NULL || (entry_core)->d[0] != '/')
+#endif
+
+/* We need to do a stable sort, qsort isn't stable. So to make it stable
+ * we'll be maintaining the original index into the list, and using it
+ * as the minor key during sorting. The major key is the number of
+ * components (where a "special" section has infinite components).
+ */
+struct reorder_sort_rec {
+ void *elt;
+ int orig_index;
+};
+
+static int reorder_sorter(const void *va, const void *vb)
+{
+ const struct reorder_sort_rec *a = va;
+ const struct reorder_sort_rec *b = vb;
+ core_dir_config *core_a;
+ core_dir_config *core_b;
+
+ core_a = (core_dir_config *)ap_get_module_config(a->elt, &core_module);
+ core_b = (core_dir_config *)ap_get_module_config(b->elt, &core_module);
+ if (IS_SPECIAL(core_a)) {
+ if (!IS_SPECIAL(core_b)) {
+ return 1;
+ }
+ }
+ else if (IS_SPECIAL(core_b)) {
+ return -1;
+ }
+ else {
+ /* we know they're both not special */
+ if (core_a->d_components < core_b->d_components) {
+ return -1;
+ }
+ else if (core_a->d_components > core_b->d_components) {
+ return 1;
+ }
+ }
+ /* Either they're both special, or they're both not special and have the
+ * same number of components. In any event, we now have to compare
+ * the minor key. */
+ return a->orig_index - b->orig_index;
+}
+
+void ap_core_reorder_directories(pool *p, server_rec *s)
+{
+ core_server_config *sconf;
+ array_header *sec;
+ struct reorder_sort_rec *sortbin;
+ int nelts;
+ void **elts;
+ int i;
+ pool *tmp;
+
+ sconf = ap_get_module_config(s->module_config, &core_module);
+ sec = sconf->sec;
+ nelts = sec->nelts;
+ elts = (void **)sec->elts;
+
+ /* we have to allocate tmp space to do a stable sort */
+ tmp = ap_make_sub_pool(p);
+ sortbin = ap_palloc(tmp, sec->nelts * sizeof(*sortbin));
+ for (i = 0; i < nelts; ++i) {
+ sortbin[i].orig_index = i;
+ sortbin[i].elt = elts[i];
+ }
+
+ qsort(sortbin, nelts, sizeof(*sortbin), reorder_sorter);
+
+ /* and now copy back to the original array */
+ for (i = 0; i < nelts; ++i) {
+ elts[i] = sortbin[i].elt;
+ }
+
+ ap_destroy_pool(tmp);
+}
+
+/*****************************************************************
+ *
+ * There are some elements of the core config structures in which
+ * other modules have a legitimate interest (this is ugly, but necessary
+ * to preserve NCSA back-compatibility). So, we have a bunch of accessors
+ * here...
+ */
+
+API_EXPORT(int) ap_allow_options(request_rec *r)
+{
+ core_dir_config *conf =
+ (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
+
+ return conf->opts;
+}
+
+API_EXPORT(int) ap_allow_overrides(request_rec *r)
+{
+ core_dir_config *conf;
+ conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
+ &core_module);
+
+ return conf->override;
+}
+
+API_EXPORT(const char *) ap_auth_type(request_rec *r)
+{
+ core_dir_config *conf;
+
+ conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
+ &core_module);
+ return conf->ap_auth_type;
+}
+
+API_EXPORT(const char *) ap_auth_name(request_rec *r)
+{
+ core_dir_config *conf;
+
+ conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
+ &core_module);
+ return conf->ap_auth_name;
+}
+
+API_EXPORT(const char *) ap_default_type(request_rec *r)
+{
+ core_dir_config *conf;
+
+ conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
+ &core_module);
+ return conf->ap_default_type
+ ? conf->ap_default_type
+ : DEFAULT_CONTENT_TYPE;
+}
+
+API_EXPORT(const char *) ap_document_root(request_rec *r) /* Don't use this! */
+{
+ core_server_config *conf;
+
+ conf = (core_server_config *)ap_get_module_config(r->server->module_config,
+ &core_module);
+ return conf->ap_document_root;
+}
+
+API_EXPORT(const array_header *) ap_requires(request_rec *r)
+{
+ core_dir_config *conf;
+
+ conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
+ &core_module);
+ return conf->ap_requires;
+}
+
+API_EXPORT(int) ap_satisfies(request_rec *r)
+{
+ core_dir_config *conf;
+
+ conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
+ &core_module);
+
+ return conf->satisfy;
+}
+
+/* Should probably just get rid of this... the only code that cares is
+ * part of the core anyway (and in fact, it isn't publicised to other
+ * modules).
+ */
+
+char *ap_response_code_string(request_rec *r, int error_index)
+{
+ core_dir_config *conf;
+
+ conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
+ &core_module);
+
+ if (conf->response_code_strings == NULL) {
+ return NULL;
+ }
+ return conf->response_code_strings[error_index];
+}
+
+
+/* Code from Harald Hanche-Olsen */
+static ap_inline void do_double_reverse (conn_rec *conn)
+{
+ struct hostent *hptr;
+
+ if (conn->double_reverse) {
+ /* already done */
+ return;
+ }
+ if (conn->remote_host == NULL || conn->remote_host[0] == '\0') {
+ /* single reverse failed, so don't bother */
+ conn->double_reverse = -1;
+ return;
+ }
+ hptr = gethostbyname(conn->remote_host);
+ if (hptr) {
+ char **haddr;
+
+ for (haddr = hptr->h_addr_list; *haddr; haddr++) {
+ if (((struct in_addr *)(*haddr))->s_addr
+ == conn->remote_addr.sin_addr.s_addr) {
+ conn->double_reverse = 1;
+ return;
+ }
+ }
+ }
+ conn->double_reverse = -1;
+}
+
+API_EXPORT(const char *) ap_get_remote_host(conn_rec *conn, void *dir_config,
+ int type)
+{
+ struct in_addr *iaddr;
+ struct hostent *hptr;
+ int hostname_lookups;
+ int old_stat = SERVER_DEAD; /* we shouldn't ever be in this state */
+
+ /* If we haven't checked the host name, and we want to */
+ if (dir_config) {
+ hostname_lookups =
+ ((core_dir_config *)ap_get_module_config(dir_config, &core_module))
+ ->hostname_lookups;
+ if (hostname_lookups == HOSTNAME_LOOKUP_UNSET) {
+ hostname_lookups = HOSTNAME_LOOKUP_OFF;
+ }
+ }
+ else {
+ /* the default */
+ hostname_lookups = HOSTNAME_LOOKUP_OFF;
+ }
+
+ if (type != REMOTE_NOLOOKUP
+ && conn->remote_host == NULL
+ && (type == REMOTE_DOUBLE_REV
+ || hostname_lookups != HOSTNAME_LOOKUP_OFF)) {
+ old_stat = ap_update_child_status(conn->child_num, SERVER_BUSY_DNS,
+ (request_rec*)NULL);
+ iaddr = &(conn->remote_addr.sin_addr);
+ hptr = gethostbyaddr((char *)iaddr, sizeof(struct in_addr), AF_INET);
+ if (hptr != NULL) {
+ conn->remote_host = ap_pstrdup(conn->pool, (void *)hptr->h_name);
+ ap_str_tolower(conn->remote_host);
+
+ if (hostname_lookups == HOSTNAME_LOOKUP_DOUBLE) {
+ do_double_reverse(conn);
+ if (conn->double_reverse != 1) {
+ conn->remote_host = NULL;
+ }
+ }
+ }
+ /* if failed, set it to the NULL string to indicate error */
+ if (conn->remote_host == NULL) {
+ conn->remote_host = "";
+ }
+ }
+ if (type == REMOTE_DOUBLE_REV) {
+ do_double_reverse(conn);
+ if (conn->double_reverse == -1) {
+ return NULL;
+ }
+ }
+ if (old_stat != SERVER_DEAD) {
+ (void)ap_update_child_status(conn->child_num, old_stat,
+ (request_rec*)NULL);
+ }
+
+/*
+ * Return the desired information; either the remote DNS name, if found,
+ * or either NULL (if the hostname was requested) or the IP address
+ * (if any identifier was requested).
+ */
+ if (conn->remote_host != NULL && conn->remote_host[0] != '\0') {
+ return conn->remote_host;
+ }
+ else {
+ if (type == REMOTE_HOST || type == REMOTE_DOUBLE_REV) {
+ return NULL;
+ }
+ else {
+ return conn->remote_ip;
+ }
+ }
+}
+
+API_EXPORT(const char *) ap_get_remote_logname(request_rec *r)
+{
+ core_dir_config *dir_conf;
+
+ if (r->connection->remote_logname != NULL) {
+ return r->connection->remote_logname;
+ }
+
+/* If we haven't checked the identity, and we want to */
+ dir_conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
+ &core_module);
+
+ if (dir_conf->do_rfc1413 & 1) {
+ return ap_rfc1413(r->connection, r->server);
+ }
+ else {
+ return NULL;
+ }
+}
+
+/* There are two options regarding what the "name" of a server is. The
+ * "canonical" name as defined by ServerName and Port, or the "client's
+ * name" as supplied by a possible Host: header or full URI. We never
+ * trust the port passed in the client's headers, we always use the
+ * port of the actual socket.
+ *
+ * The DNS option to UseCanonicalName causes this routine to do a
+ * reverse lookup on the local IP address of the connectiona and use
+ * that for the ServerName. This makes its value more reliable while
+ * at the same time allowing Demon's magic virtual hosting to work.
+ * The assumption is that DNS lookups are sufficiently quick...
+ * -- fanf 1998-10-03
+ */
+API_EXPORT(const char *) ap_get_server_name(request_rec *r)
+{
+ conn_rec *conn = r->connection;
+ core_dir_config *d;
+
+ d = (core_dir_config *)ap_get_module_config(r->per_dir_config,
+ &core_module);
+
+ if (d->use_canonical_name == USE_CANONICAL_NAME_OFF) {
+ return r->hostname ? r->hostname : r->server->server_hostname;
+ }
+ if (d->use_canonical_name == USE_CANONICAL_NAME_DNS) {
+ if (conn->local_host == NULL) {
+ struct in_addr *iaddr;
+ struct hostent *hptr;
+ int old_stat;
+ old_stat = ap_update_child_status(conn->child_num,
+ SERVER_BUSY_DNS, r);
+ iaddr = &(conn->local_addr.sin_addr);
+ hptr = gethostbyaddr((char *)iaddr, sizeof(struct in_addr),
+ AF_INET);
+ if (hptr != NULL) {
+ conn->local_host = ap_pstrdup(conn->pool,
+ (void *)hptr->h_name);
+ ap_str_tolower(conn->local_host);
+ }
+ else {
+ conn->local_host = ap_pstrdup(conn->pool,
+ r->server->server_hostname);
+ }
+ (void) ap_update_child_status(conn->child_num, old_stat, r);
+ }
+ return conn->local_host;
+ }
+ /* default */
+ return r->server->server_hostname;
+}
+
+API_EXPORT(unsigned) ap_get_server_port(const request_rec *r)
+{
+ unsigned port;
+ core_dir_config *d =
+ (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
+
+ port = r->server->port ? r->server->port : ap_default_port(r);
+
+ if (d->use_canonical_name == USE_CANONICAL_NAME_OFF
+ || d->use_canonical_name == USE_CANONICAL_NAME_DNS) {
+ return r->hostname ? ntohs(r->connection->local_addr.sin_port)
+ : port;
+ }
+ /* default */
+ return port;
+}
+
+API_EXPORT(char *) ap_construct_url(pool *p, const char *uri,
+ request_rec *r)
+{
+ unsigned port = ap_get_server_port(r);
+ const char *host = ap_get_server_name(r);
+
+ if (ap_is_default_port(port, r)) {
+ return ap_pstrcat(p, ap_http_method(r), "://", host, uri, NULL);
+ }
+ return ap_psprintf(p, "%s://%s:%u%s", ap_http_method(r), host, port, uri);
+}
+
+API_EXPORT(unsigned long) ap_get_limit_req_body(const request_rec *r)
+{
+ core_dir_config *d =
+ (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
+
+ return d->limit_req_body;
+}
+
+#ifdef WIN32
+static char* get_interpreter_from_win32_registry(pool *p, const char* ext)
+{
+ char extension_path[] = "SOFTWARE\\Classes\\";
+ char executable_path[] = "\\SHELL\\OPEN\\COMMAND";
+
+ HKEY hkeyOpen;
+ DWORD type;
+ int size;
+ int result;
+ char *keyName;
+ char *buffer;
+ char *s;
+
+ if (!ext)
+ return NULL;
+ /*
+ * Future optimization:
+ * When the registry is successfully searched, store the interpreter
+ * string in a table to make subsequent look-ups faster
+ */
+
+ /* Open the key associated with the script extension */
+ keyName = ap_pstrcat(p, extension_path, ext, NULL);
+
+ result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyName, 0, KEY_QUERY_VALUE,
+ &hkeyOpen);
+
+ if (result != ERROR_SUCCESS)
+ return NULL;
+
+ /* Read to NULL buffer to find value size */
+ size = 0;
+ result = RegQueryValueEx(hkeyOpen, "", NULL, &type, NULL, &size);
+
+ if (result == ERROR_SUCCESS) {
+ buffer = ap_palloc(p, size);
+ result = RegQueryValueEx(hkeyOpen, "", NULL, &type, buffer, &size);
+ }
+
+ RegCloseKey(hkeyOpen);
+
+ if (result != ERROR_SUCCESS)
+ return NULL;
+
+ /* Open the key associated with the interpreter path */
+ keyName = ap_pstrcat(p, extension_path, buffer, executable_path, NULL);
+
+ result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyName, 0, KEY_QUERY_VALUE,
+ &hkeyOpen);
+
+ if (result != ERROR_SUCCESS)
+ return NULL;
+
+ /* Read to NULL buffer to find value size */
+ size = 0;
+ result = RegQueryValueEx(hkeyOpen, "", 0, &type, NULL, &size);
+
+ if (result == ERROR_SUCCESS) {
+ buffer = ap_palloc(p, size);
+ result = RegQueryValueEx(hkeyOpen, "", 0, &type, buffer, &size);
+ }
+
+ RegCloseKey(hkeyOpen);
+
+ if (result != ERROR_SUCCESS)
+ return NULL;
+
+ /*
+ * The canonical way shell command entries are entered in the Win32
+ * registry is as follows:
+ * shell [options] "%1"
+ * where
+ * shell - full path name to interpreter or shell to run.
+ * E.g., c:\usr\local\ntreskit\perl\bin\perl.exe
+ * options - optional switches
+ * E.g., \C
+ * "%1" - Place holder for file to run the shell against.
+ * Typically quoted.
+ *
+ * If we find a %1 or a quoted %1, lop it off.
+ */
+ if (buffer && *buffer) {
+ if ((s = strstr(buffer, "\"%1")))
+ *s = '\0';
+ else if ((s = strstr(buffer, "%1")))
+ *s = '\0';
+ }
+
+ return buffer;
+}
+
+API_EXPORT (file_type_e) ap_get_win32_interpreter(const request_rec *r,
+ char** interpreter )
+{
+ HANDLE hFile;
+ DWORD nBytesRead;
+ BOOLEAN bResult;
+ char buffer[1024];
+ core_dir_config *d;
+ int i;
+ file_type_e fileType = eFileTypeUNKNOWN;
+ char *ext = NULL;
+ char *exename = NULL;
+
+ d = (core_dir_config *)ap_get_module_config(r->per_dir_config,
+ &core_module);
+
+ /* Find the file extension */
+ exename = strrchr(r->filename, '/');
+ if (!exename) {
+ exename = strrchr(r->filename, '\\');
+ }
+ if (!exename) {
+ exename = r->filename;
+ }
+ else {
+ exename++;
+ }
+ ext = strrchr(exename, '.');
+
+ if (ext && (!strcasecmp(ext,".bat") || !strcasecmp(ext,".cmd"))) {
+ return eFileTypeEXE32;
+ }
+
+ /* If the file has an extension and it is not .com and not .exe and
+ * we've been instructed to search the registry, then do it!
+ */
+ if (ext && strcasecmp(ext,".exe") && strcasecmp(ext,".com") &&
+ d->script_interpreter_source == INTERPRETER_SOURCE_REGISTRY) {
+ /* Check the registry */
+ *interpreter = get_interpreter_from_win32_registry(r->pool, ext);
+ if (*interpreter)
+ return eFileTypeSCRIPT;
+ else {
+ ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, r->server,
+ "ScriptInterpreterSource config directive set to \"registry\".\n\t"
+ "Registry was searched but interpreter not found. Trying the shebang line.");
+ }
+ }
+
+ /* Need to peek into the file figure out what it really is... */
+ hFile = CreateFile(r->filename, GENERIC_READ, FILE_SHARE_READ, NULL,
+ OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
+ if (hFile == INVALID_HANDLE_VALUE) {
+ return eFileTypeUNKNOWN;
+ }
+ bResult = ReadFile(hFile, (void*) &buffer, sizeof(buffer) - 1,
+ &nBytesRead, NULL);
+ if (!bResult || (nBytesRead == 0)) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
+ "ReadFile(%s) failed", r->filename);
+ CloseHandle(hFile);
+ return eFileTypeUNKNOWN;
+ }
+ CloseHandle(hFile);
+ buffer[nBytesRead] = '\0';
+
+ /* Script or executable, that is the question... */
+ if ((buffer[0] == '#') && (buffer[1] == '!')) {
+ /* Assuming file is a script since it starts with a shebang */
+ fileType = eFileTypeSCRIPT;
+ for (i = 2; i < sizeof(buffer); i++) {
+ if ((buffer[i] == '\r')
+ || (buffer[i] == '\n')) {
+ break;
+ }
+ }
+ buffer[i] = '\0';
+ for (i = 2; buffer[i] == ' ' ; ++i)
+ ;
+ *interpreter = ap_pstrdup(r->pool, buffer + i );
+ }
+ else {
+ /* Not a script, is it an executable? */
+ IMAGE_DOS_HEADER *hdr = (IMAGE_DOS_HEADER*)buffer;
+ if ((nBytesRead >= sizeof(IMAGE_DOS_HEADER)) && (hdr->e_magic == IMAGE_DOS_SIGNATURE)) {
+ if (hdr->e_lfarlc < 0x40)
+ fileType = eFileTypeEXE16;
+ else
+ fileType = eFileTypeEXE32;
+ }
+ else
+ fileType = eFileTypeUNKNOWN;
+ }
+
+ return fileType;
+}
+#endif
+
+/*****************************************************************
+ *
+ * Commands... this module handles almost all of the NCSA httpd.conf
+ * commands, but most of the old srm.conf is in the the modules.
+ */
+
+static const char end_directory_section[] = "";
+static const char end_directorymatch_section[] = "";
+static const char end_location_section[] = " ";
+static const char end_locationmatch_section[] = "";
+static const char end_files_section[] = "";
+static const char end_filesmatch_section[] = "";
+static const char end_virtualhost_section[] = "";
+static const char end_ifmodule_section[] = "";
+static const char end_ifdefine_section[] = "";
+
+
+API_EXPORT(const char *) ap_check_cmd_context(cmd_parms *cmd,
+ unsigned forbidden)
+{
+ const char *gt = (cmd->cmd->name[0] == '<'
+ && cmd->cmd->name[strlen(cmd->cmd->name)-1] != '>')
+ ? ">" : "";
+
+ if ((forbidden & NOT_IN_VIRTUALHOST) && cmd->server->is_virtual) {
+ return ap_pstrcat(cmd->pool, cmd->cmd->name, gt,
+ " cannot occur within section", NULL);
+ }
+
+ if ((forbidden & NOT_IN_LIMIT) && cmd->limited != -1) {
+ return ap_pstrcat(cmd->pool, cmd->cmd->name, gt,
+ " cannot occur within section", NULL);
+ }
+
+ if ((forbidden & NOT_IN_DIR_LOC_FILE) == NOT_IN_DIR_LOC_FILE
+ && cmd->path != NULL) {
+ return ap_pstrcat(cmd->pool, cmd->cmd->name, gt,
+ " cannot occur within "
+ "section", NULL);
+ }
+
+ if (((forbidden & NOT_IN_DIRECTORY)
+ && (cmd->end_token == end_directory_section
+ || cmd->end_token == end_directorymatch_section))
+ || ((forbidden & NOT_IN_LOCATION)
+ && (cmd->end_token == end_location_section
+ || cmd->end_token == end_locationmatch_section))
+ || ((forbidden & NOT_IN_FILES)
+ && (cmd->end_token == end_files_section
+ || cmd->end_token == end_filesmatch_section))) {
+ return ap_pstrcat(cmd->pool, cmd->cmd->name, gt,
+ " cannot occur within <", cmd->end_token+2,
+ " section", NULL);
+ }
+
+ return NULL;
+}
+
+static const char *set_access_name(cmd_parms *cmd, void *dummy, char *arg)
+{
+ void *sconf = cmd->server->module_config;
+ core_server_config *conf = ap_get_module_config(sconf, &core_module);
+
+ const char *err = ap_check_cmd_context(cmd,
+ NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
+ if (err != NULL) {
+ return err;
+ }
+
+ conf->access_name = ap_pstrdup(cmd->pool, arg);
+ return NULL;
+}
+
+#ifdef GPROF
+static const char *set_gprof_dir(cmd_parms *cmd, void *dummy, char *arg)
+{
+ void *sconf = cmd->server->module_config;
+ core_server_config *conf = ap_get_module_config(sconf, &core_module);
+
+ const char *err = ap_check_cmd_context(cmd,
+ NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
+ if (err != NULL) {
+ return err;
+ }
+
+ conf->gprof_dir = ap_pstrdup(cmd->pool, arg);
+ return NULL;
+}
+#endif /*GPROF*/
+
+static const char *set_document_root(cmd_parms *cmd, void *dummy, char *arg)
+{
+ void *sconf = cmd->server->module_config;
+ core_server_config *conf = ap_get_module_config(sconf, &core_module);
+
+ const char *err = ap_check_cmd_context(cmd,
+ NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
+ if (err != NULL) {
+ return err;
+ }
+
+ arg = ap_os_canonical_filename(cmd->pool, arg);
+ if (ap_configtestonly && ap_docrootcheck && !ap_is_directory(arg)) {
+ if (cmd->server->is_virtual) {
+ fprintf(stderr, "Warning: DocumentRoot [%s] does not exist\n",
+ arg);
+ }
+ else {
+ return "DocumentRoot must be a directory";
+ }
+ }
+
+ conf->ap_document_root = arg;
+ return NULL;
+}
+
+API_EXPORT(void) ap_custom_response(request_rec *r, int status, char *string)
+{
+ core_dir_config *conf =
+ ap_get_module_config(r->per_dir_config, &core_module);
+ int idx;
+
+ if(conf->response_code_strings == NULL) {
+ conf->response_code_strings =
+ ap_pcalloc(r->pool,
+ sizeof(*conf->response_code_strings) *
+ RESPONSE_CODES);
+ }
+
+ idx = ap_index_of_response(status);
+
+ conf->response_code_strings[idx] =
+ ((ap_is_url(string) || (*string == '/')) && (*string != '"')) ?
+ ap_pstrdup(r->pool, string) : ap_pstrcat(r->pool, "\"", string, NULL);
+}
+
+static const char *set_error_document(cmd_parms *cmd, core_dir_config *conf,
+ char *line)
+{
+ int error_number, index_number, idx500;
+ char *w;
+
+ const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
+ if (err != NULL) {
+ return err;
+ }
+
+ /* 1st parameter should be a 3 digit number, which we recognize;
+ * convert it into an array index
+ */
+
+ w = ap_getword_conf_nc(cmd->pool, &line);
+ error_number = atoi(w);
+
+ idx500 = ap_index_of_response(HTTP_INTERNAL_SERVER_ERROR);
+
+ if (error_number == HTTP_INTERNAL_SERVER_ERROR) {
+ index_number = idx500;
+ }
+ else if ((index_number = ap_index_of_response(error_number)) == idx500) {
+ return ap_pstrcat(cmd->pool, "Unsupported HTTP response code ",
+ w, NULL);
+ }
+
+ /* The entry should be ignored if it is a full URL for a 401 error */
+
+ if (error_number == 401 &&
+ line[0] != '/' && line[0] != '"') { /* Ignore it... */
+ ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, cmd->server,
+ "cannot use a full URL in a 401 ErrorDocument "
+ "directive --- ignoring!");
+ }
+ else { /* Store it... */
+ if (conf->response_code_strings == NULL) {
+ conf->response_code_strings =
+ ap_pcalloc(cmd->pool,
+ sizeof(*conf->response_code_strings) * RESPONSE_CODES);
+ }
+ conf->response_code_strings[index_number] = ap_pstrdup(cmd->pool, line);
+ }
+
+ return NULL;
+}
+
+/* access.conf commands...
+ *
+ * The *only* thing that can appear in access.conf at top level is a
+ * section. NB we need to have a way to cut the srm_command_loop
+ * invoked by dirsection (i.e., ) short when is seen.
+ * We do that by returning an error, which dirsection itself recognizes and
+ * discards as harmless. Cheesy, but it works.
+ */
+
+static const char *set_override(cmd_parms *cmd, core_dir_config *d,
+ const char *l)
+{
+ char *w;
+
+ const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
+ if (err != NULL) {
+ return err;
+ }
+
+ d->override = OR_NONE;
+ while (l[0]) {
+ w = ap_getword_conf(cmd->pool, &l);
+ if (!strcasecmp(w, "Limit")) {
+ d->override |= OR_LIMIT;
+ }
+ else if (!strcasecmp(w, "Options")) {
+ d->override |= OR_OPTIONS;
+ }
+ else if (!strcasecmp(w, "FileInfo")) {
+ d->override |= OR_FILEINFO;
+ }
+ else if (!strcasecmp(w, "AuthConfig")) {
+ d->override |= OR_AUTHCFG;
+ }
+ else if (!strcasecmp(w, "Indexes")) {
+ d->override |= OR_INDEXES;
+ }
+ else if (!strcasecmp(w, "None")) {
+ d->override = OR_NONE;
+ }
+ else if (!strcasecmp(w, "All")) {
+ d->override = OR_ALL;
+ }
+ else {
+ return ap_pstrcat(cmd->pool, "Illegal override option ", w, NULL);
+ }
+ d->override &= ~OR_UNSET;
+ }
+
+ return NULL;
+}
+
+static const char *set_options(cmd_parms *cmd, core_dir_config *d,
+ const char *l)
+{
+ allow_options_t opt;
+ int first = 1;
+ char action;
+
+ while (l[0]) {
+ char *w = ap_getword_conf(cmd->pool, &l);
+ action = '\0';
+
+ if (*w == '+' || *w == '-') {
+ action = *(w++);
+ }
+ else if (first) {
+ d->opts = OPT_NONE;
+ first = 0;
+ }
+
+ if (!strcasecmp(w, "Indexes")) {
+ opt = OPT_INDEXES;
+ }
+ else if (!strcasecmp(w, "Includes")) {
+ opt = OPT_INCLUDES;
+ }
+ else if (!strcasecmp(w, "IncludesNOEXEC")) {
+ opt = (OPT_INCLUDES | OPT_INCNOEXEC);
+ }
+ else if (!strcasecmp(w, "FollowSymLinks")) {
+ opt = OPT_SYM_LINKS;
+ }
+ else if (!strcasecmp(w, "SymLinksIfOwnerMatch")) {
+ opt = OPT_SYM_OWNER;
+ }
+ else if (!strcasecmp(w, "execCGI")) {
+ opt = OPT_EXECCGI;
+ }
+ else if (!strcasecmp(w, "MultiViews")) {
+ opt = OPT_MULTI;
+ }
+ else if (!strcasecmp(w, "RunScripts")) { /* AI backcompat. Yuck */
+ opt = OPT_MULTI|OPT_EXECCGI;
+ }
+ else if (!strcasecmp(w, "None")) {
+ opt = OPT_NONE;
+ }
+ else if (!strcasecmp(w, "All")) {
+ opt = OPT_ALL;
+ }
+ else {
+ return ap_pstrcat(cmd->pool, "Illegal option ", w, NULL);
+ }
+
+ /* we ensure the invariant (d->opts_add & d->opts_remove) == 0 */
+ if (action == '-') {
+ d->opts_remove |= opt;
+ d->opts_add &= ~opt;
+ d->opts &= ~opt;
+ }
+ else if (action == '+') {
+ d->opts_add |= opt;
+ d->opts_remove &= ~opt;
+ d->opts |= opt;
+ }
+ else {
+ d->opts |= opt;
+ }
+ }
+
+ return NULL;
+}
+
+static const char *satisfy(cmd_parms *cmd, core_dir_config *c, char *arg)
+{
+ if (!strcasecmp(arg, "all")) {
+ c->satisfy = SATISFY_ALL;
+ }
+ else if (!strcasecmp(arg, "any")) {
+ c->satisfy = SATISFY_ANY;
+ }
+ else {
+ return "Satisfy either 'any' or 'all'.";
+ }
+ return NULL;
+}
+
+static const char *require(cmd_parms *cmd, core_dir_config *c, char *arg)
+{
+ require_line *r;
+
+ if (!c->ap_requires) {
+ c->ap_requires = ap_make_array(cmd->pool, 2, sizeof(require_line));
+ }
+ r = (require_line *)ap_push_array(c->ap_requires);
+ r->requirement = ap_pstrdup(cmd->pool, arg);
+ r->method_mask = cmd->limited;
+ return NULL;
+}
+
+CORE_EXPORT_NONSTD(const char *) ap_limit_section(cmd_parms *cmd, void *dummy,
+ const char *arg)
+{
+ const char *limited_methods = ap_getword(cmd->pool, &arg, '>');
+ void *tog = cmd->cmd->cmd_data;
+ int limited = 0;
+
+ const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
+ if (err != NULL) {
+ return err;
+ }
+
+ /* XXX: NB: Currently, we have no way of checking
+ * whether or sections are closed properly.
+ * (If we would add a srm_command_loop() here we might...)
+ */
+
+ while (limited_methods[0]) {
+ char *method = ap_getword_conf(cmd->pool, &limited_methods);
+ int methnum = ap_method_number_of(method);
+
+ if (methnum == M_TRACE && !tog) {
+ return "TRACE cannot be controlled by ";
+ }
+ else if (methnum == M_INVALID) {
+ return ap_pstrcat(cmd->pool, "unknown method \"", method,
+ "\" in " : ">", NULL);
+ }
+ else {
+ limited |= (1 << methnum);
+ }
+ }
+
+ /* Killing two features with one function,
+ * if (tog == NULL) , else
+ */
+ cmd->limited = tog ? ~limited : limited;
+ return NULL;
+}
+
+static const char *endlimit_section(cmd_parms *cmd, void *dummy, void *dummy2)
+{
+ void *tog = cmd->cmd->cmd_data;
+
+ if (cmd->limited == -1) {
+ return tog ? " unexpected" : " unexpected";
+ }
+
+ cmd->limited = -1;
+ return NULL;
+}
+
+/*
+ * When a section is not closed properly when end-of-file is reached,
+ * then an error message should be printed:
+ */
+static const char *missing_endsection(cmd_parms *cmd, int nest)
+{
+ if (nest < 2) {
+ return ap_psprintf(cmd->pool, "Missing %s directive at end-of-file",
+ cmd->end_token);
+ }
+ return ap_psprintf(cmd->pool, "%d missing %s directives at end-of-file",
+ nest, cmd->end_token);
+}
+
+/* We use this in and , to ensure that
+ * people don't get bitten by wrong-cased regex matches
+ */
+
+#ifdef WIN32
+#define USE_ICASE REG_ICASE
+#else
+#define USE_ICASE 0
+#endif
+
+static const char *end_nested_section(cmd_parms *cmd, void *dummy)
+{
+ if (cmd->end_token == NULL) {
+ return ap_pstrcat(cmd->pool, cmd->cmd->name,
+ " without matching <", cmd->cmd->name + 2,
+ " section", NULL);
+ }
+ /*
+ * This '!=' may look weird on a string comparison, but it's correct --
+ * it's been set up so that checking for two pointers to the same datum
+ * is valid here. And faster.
+ */
+ if (cmd->cmd->name != cmd->end_token) {
+ return ap_pstrcat(cmd->pool, "Expected ", cmd->end_token, " but saw ",
+ cmd->cmd->name, NULL);
+ }
+ return cmd->end_token;
+}
+
+/*
+ * Report a missing-'>' syntax error.
+ */
+static char *unclosed_directive(cmd_parms *cmd)
+{
+ return ap_pstrcat(cmd->pool, cmd->cmd->name,
+ "> directive missing closing '>'", NULL);
+}
+
+static const char *dirsection(cmd_parms *cmd, void *dummy, const char *arg)
+{
+ const char *errmsg;
+ char *endp = strrchr(arg, '>');
+ int old_overrides = cmd->override;
+ char *old_path = cmd->path;
+ core_dir_config *conf;
+ void *new_dir_conf = ap_create_per_dir_config(cmd->pool);
+ regex_t *r = NULL;
+ const char *old_end_token;
+ const command_rec *thiscmd = cmd->cmd;
+
+ const char *err = ap_check_cmd_context(cmd,
+ NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
+ if (err != NULL) {
+ return err;
+ }
+
+ if (endp == NULL) {
+ return unclosed_directive(cmd);
+ }
+
+ *endp = '\0';
+
+ cmd->path = ap_getword_conf(cmd->pool, &arg);
+ cmd->override = OR_ALL|ACCESS_CONF;
+
+ if (thiscmd->cmd_data) { /* */
+ r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
+ }
+ else if (!strcmp(cmd->path, "~")) {
+ cmd->path = ap_getword_conf(cmd->pool, &arg);
+ r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
+ }
+ else {
+ /* Ensure that the pathname is canonical */
+ cmd->path = ap_os_canonical_filename(cmd->pool, cmd->path);
+ }
+
+ old_end_token = cmd->end_token;
+ cmd->end_token = thiscmd->cmd_data ? end_directorymatch_section : end_directory_section;
+ errmsg = ap_srm_command_loop(cmd, new_dir_conf);
+ if (errmsg == NULL) {
+ errmsg = missing_endsection(cmd, 1);
+ }
+ cmd->end_token = old_end_token;
+ if (errmsg != (thiscmd->cmd_data
+ ? end_directorymatch_section
+ : end_directory_section)) {
+ return errmsg;
+ }
+
+ conf = (core_dir_config *)ap_get_module_config(new_dir_conf, &core_module);
+ conf->r = r;
+
+ ap_add_per_dir_conf(cmd->server, new_dir_conf);
+
+ if (*arg != '\0') {
+ return ap_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
+ "> arguments not (yet) supported.", NULL);
+ }
+
+ cmd->path = old_path;
+ cmd->override = old_overrides;
+
+ return NULL;
+}
+
+static const char *urlsection(cmd_parms *cmd, void *dummy, const char *arg)
+{
+ const char *errmsg;
+ char *endp = strrchr(arg, '>');
+ int old_overrides = cmd->override;
+ char *old_path = cmd->path;
+ core_dir_config *conf;
+ regex_t *r = NULL;
+ const char *old_end_token;
+ const command_rec *thiscmd = cmd->cmd;
+
+ void *new_url_conf = ap_create_per_dir_config(cmd->pool);
+
+ const char *err = ap_check_cmd_context(cmd,
+ NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
+ if (err != NULL) {
+ return err;
+ }
+
+ if (endp == NULL) {
+ return unclosed_directive(cmd);
+ }
+
+ *endp = '\0';
+
+ cmd->path = ap_getword_conf(cmd->pool, &arg);
+ cmd->override = OR_ALL|ACCESS_CONF;
+
+ if (thiscmd->cmd_data) { /* */
+ r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED);
+ }
+ else if (!strcmp(cmd->path, "~")) {
+ cmd->path = ap_getword_conf(cmd->pool, &arg);
+ r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED);
+ }
+
+ old_end_token = cmd->end_token;
+ cmd->end_token = thiscmd->cmd_data ? end_locationmatch_section
+ : end_location_section;
+ errmsg = ap_srm_command_loop(cmd, new_url_conf);
+ if (errmsg == NULL) {
+ errmsg = missing_endsection(cmd, 1);
+ }
+ cmd->end_token = old_end_token;
+ if (errmsg != (thiscmd->cmd_data
+ ? end_locationmatch_section
+ : end_location_section)) {
+ return errmsg;
+ }
+
+ conf = (core_dir_config *)ap_get_module_config(new_url_conf, &core_module);
+ conf->d = ap_pstrdup(cmd->pool, cmd->path); /* No mangling, please */
+ conf->d_is_fnmatch = ap_is_fnmatch(conf->d) != 0;
+ conf->r = r;
+
+ ap_add_per_url_conf(cmd->server, new_url_conf);
+
+ if (*arg != '\0') {
+ return ap_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
+ "> arguments not (yet) supported.", NULL);
+ }
+
+ cmd->path = old_path;
+ cmd->override = old_overrides;
+
+ return NULL;
+}
+
+static const char *filesection(cmd_parms *cmd, core_dir_config *c,
+ const char *arg)
+{
+ const char *errmsg;
+ char *endp = strrchr(arg, '>');
+ int old_overrides = cmd->override;
+ char *old_path = cmd->path;
+ core_dir_config *conf;
+ regex_t *r = NULL;
+ const char *old_end_token;
+ const command_rec *thiscmd = cmd->cmd;
+
+ void *new_file_conf = ap_create_per_dir_config(cmd->pool);
+
+ const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT|NOT_IN_LOCATION);
+ if (err != NULL) {
+ return err;
+ }
+
+ if (endp == NULL) {
+ return unclosed_directive(cmd);
+ }
+
+ *endp = '\0';
+
+ cmd->path = ap_getword_conf(cmd->pool, &arg);
+ /* Only if not an .htaccess file */
+ if (!old_path) {
+ cmd->override = OR_ALL|ACCESS_CONF;
+ }
+
+ if (thiscmd->cmd_data) { /* */
+ r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
+ }
+ else if (!strcmp(cmd->path, "~")) {
+ cmd->path = ap_getword_conf(cmd->pool, &arg);
+ r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
+ }
+ else {
+ /* Ensure that the pathname is canonical */
+ cmd->path = ap_os_canonical_filename(cmd->pool, cmd->path);
+ }
+
+ old_end_token = cmd->end_token;
+ cmd->end_token = thiscmd->cmd_data ? end_filesmatch_section : end_files_section;
+ errmsg = ap_srm_command_loop(cmd, new_file_conf);
+ if (errmsg == NULL) {
+ errmsg = missing_endsection(cmd, 1);
+ }
+ cmd->end_token = old_end_token;
+ if (errmsg != (thiscmd->cmd_data
+ ? end_filesmatch_section
+ : end_files_section)) {
+ return errmsg;
+ }
+
+ conf = (core_dir_config *)ap_get_module_config(new_file_conf,
+ &core_module);
+ conf->d = cmd->path;
+ conf->d_is_fnmatch = ap_is_fnmatch(conf->d) != 0;
+ conf->r = r;
+
+ ap_add_file_conf(c, new_file_conf);
+
+ if (*arg != '\0') {
+ return ap_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
+ "> arguments not (yet) supported.", NULL);
+ }
+
+ cmd->path = old_path;
+ cmd->override = old_overrides;
+
+ return NULL;
+}
+
+/* XXX: NB: Currently, we have no way of checking
+ * whether sections are closed properly.
+ * Extra (redundant, unpaired) directives are
+ * simply silently ignored.
+ */
+static const char *end_ifmod(cmd_parms *cmd, void *dummy)
+{
+ return NULL;
+}
+
+static const char *start_ifmod(cmd_parms *cmd, void *dummy, char *arg)
+{
+ char *endp = strrchr(arg, '>');
+ char l[MAX_STRING_LEN];
+ int not = (arg[0] == '!');
+ module *found;
+ int nest = 1;
+
+ if (endp == NULL) {
+ return unclosed_directive(cmd);
+ }
+
+ *endp = '\0';
+
+ if (not) {
+ arg++;
+ }
+
+ found = ap_find_linked_module(arg);
+
+ if ((!not && found) || (not && !found)) {
+ return NULL;
+ }
+
+ while (nest && !(ap_cfg_getline(l, MAX_STRING_LEN, cmd->config_file))) {
+ if (!strncasecmp(l, "")) {
+ nest--;
+ }
+ }
+
+ if (nest) {
+ cmd->end_token = end_ifmodule_section;
+ return missing_endsection(cmd, nest);
+ }
+ return NULL;
+}
+
+API_EXPORT(int) ap_exists_config_define(char *name)
+{
+ char **defines;
+ int i;
+
+ defines = (char **)ap_server_config_defines->elts;
+ for (i = 0; i < ap_server_config_defines->nelts; i++) {
+ if (strcmp(defines[i], name) == 0) {
+ return 1;
+ }
+ }
+ return 0;
+}
+
+static const char *end_ifdefine(cmd_parms *cmd, void *dummy)
+{
+ return NULL;
+}
+
+static const char *start_ifdefine(cmd_parms *cmd, void *dummy, char *arg)
+{
+ char *endp;
+ char l[MAX_STRING_LEN];
+ int defined;
+ int not = 0;
+ int nest = 1;
+
+ endp = strrchr(arg, '>');
+ if (endp == NULL) {
+ return unclosed_directive(cmd);
+ }
+
+ *endp = '\0';
+
+ if (arg[0] == '!') {
+ not = 1;
+ arg++;
+ }
+
+ defined = ap_exists_config_define(arg);
+
+ if ((!not && defined) || (not && !defined)) {
+ return NULL;
+ }
+
+ while (nest && !(ap_cfg_getline(l, MAX_STRING_LEN, cmd->config_file))) {
+ if (!strncasecmp(l, "")) {
+ nest--;
+ }
+ }
+ if (nest) {
+ cmd->end_token = end_ifdefine_section;
+ return missing_endsection(cmd, nest);
+ }
+ return NULL;
+}
+
+/* httpd.conf commands... beginning with the business */
+
+static const char *virtualhost_section(cmd_parms *cmd, void *dummy, char *arg)
+{
+ server_rec *main_server = cmd->server, *s;
+ const char *errmsg;
+ char *endp = strrchr(arg, '>');
+ pool *p = cmd->pool, *ptemp = cmd->temp_pool;
+ const char *old_end_token;
+
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+ if (err != NULL) {
+ return err;
+ }
+
+ if (endp == NULL) {
+ return unclosed_directive(cmd);
+ }
+
+ *endp = '\0';
+
+ /* FIXME: There's another feature waiting to happen here -- since you
+ can now put multiple addresses/names on a single
+ you might want to use it to group common definitions and then
+ define other "subhosts" with their individual differences. But
+ personally I'd rather just do it with a macro preprocessor. -djg */
+ if (main_server->is_virtual) {
+ return " doesn't nest!";
+ }
+
+ errmsg = ap_init_virtual_host(p, arg, main_server, &s);
+ if (errmsg) {
+ return errmsg;
+ }
+
+ s->next = main_server->next;
+ main_server->next = s;
+
+ s->defn_name = cmd->config_file->name;
+ s->defn_line_number = cmd->config_file->line_number;
+
+ old_end_token = cmd->end_token;
+ cmd->end_token = end_virtualhost_section;
+ cmd->server = s;
+ errmsg = ap_srm_command_loop(cmd, s->lookup_defaults);
+ cmd->server = main_server;
+ if (errmsg == NULL) {
+ errmsg = missing_endsection(cmd, 1);
+ }
+ cmd->end_token = old_end_token;
+
+ if (s->srm_confname) {
+ ap_process_resource_config(s, s->srm_confname, p, ptemp);
+ }
+
+ if (s->access_confname) {
+ ap_process_resource_config(s, s->access_confname, p, ptemp);
+ }
+
+ if (errmsg == end_virtualhost_section) {
+ return NULL;
+ }
+ return errmsg;
+}
+
+static const char *set_server_alias(cmd_parms *cmd, void *dummy,
+ const char *arg)
+{
+ if (!cmd->server->names) {
+ return "ServerAlias only used in ";
+ }
+ while (*arg) {
+ char **item, *name = ap_getword_conf(cmd->pool, &arg);
+ if (ap_is_matchexp(name)) {
+ item = (char **)ap_push_array(cmd->server->wild_names);
+ }
+ else {
+ item = (char **)ap_push_array(cmd->server->names);
+ }
+ *item = name;
+ }
+ return NULL;
+}
+
+static const char *add_module_command(cmd_parms *cmd, void *dummy, char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+ if (err != NULL) {
+ return err;
+ }
+
+ if (!ap_add_named_module(arg)) {
+ return ap_pstrcat(cmd->pool, "Cannot add module via name '", arg,
+ "': not in list of loaded modules", NULL);
+ }
+ return NULL;
+}
+
+static const char *clear_module_list_command(cmd_parms *cmd, void *dummy)
+{
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+ if (err != NULL) {
+ return err;
+ }
+
+ ap_clear_module_list();
+ return NULL;
+}
+
+static const char *set_server_string_slot(cmd_parms *cmd, void *dummy,
+ char *arg)
+{
+ /* This one's pretty generic... */
+
+ int offset = (int)(long)cmd->info;
+ char *struct_ptr = (char *)cmd->server;
+
+ const char *err = ap_check_cmd_context(cmd,
+ NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
+ if (err != NULL) {
+ return err;
+ }
+
+ *(char **)(struct_ptr + offset) = arg;
+ return NULL;
+}
+
+static const char *server_type(cmd_parms *cmd, void *dummy, char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+ if (err != NULL) {
+ return err;
+ }
+
+ if (!strcasecmp(arg, "inetd")) {
+ ap_standalone = 0;
+ }
+ else if (!strcasecmp(arg, "standalone")) {
+ ap_standalone = 1;
+ }
+ else {
+ return "ServerType must be either 'inetd' or 'standalone'";
+ }
+
+ return NULL;
+}
+
+static const char *server_port(cmd_parms *cmd, void *dummy, char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
+ int port;
+
+ if (err != NULL) {
+ return err;
+ }
+ port = atoi(arg);
+ if (port <= 0 || port >= 65536) { /* 65536 == 1<<16 */
+ return ap_pstrcat(cmd->temp_pool, "The port number \"", arg,
+ "\" is outside the appropriate range "
+ "(i.e., 1..65535).", NULL);
+ }
+ cmd->server->port = port;
+ return NULL;
+}
+
+static const char *set_signature_flag(cmd_parms *cmd, core_dir_config *d,
+ char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
+ if (err != NULL) {
+ return err;
+ }
+
+ if (strcasecmp(arg, "On") == 0) {
+ d->server_signature = srv_sig_on;
+ }
+ else if (strcasecmp(arg, "Off") == 0) {
+ d->server_signature = srv_sig_off;
+ }
+ else if (strcasecmp(arg, "EMail") == 0) {
+ d->server_signature = srv_sig_withmail;
+ }
+ else {
+ return "ServerSignature: use one of: off | on | email";
+ }
+ return NULL;
+}
+
+static const char *set_send_buffer_size(cmd_parms *cmd, void *dummy, char *arg)
+{
+ int s = atoi(arg);
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+ if (err != NULL) {
+ return err;
+ }
+
+ if (s < 512 && s != 0) {
+ return "SendBufferSize must be >= 512 bytes, or 0 for system default.";
+ }
+ cmd->server->send_buffer_size = s;
+ return NULL;
+}
+
+static const char *set_user(cmd_parms *cmd, void *dummy, char *arg)
+{
+#ifdef WIN32
+ ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, cmd->server,
+ "User directive has no affect on Win32");
+ cmd->server->server_uid = ap_user_id = 1;
+#else
+ const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
+ if (err != NULL) {
+ return err;
+ }
+
+ if (!cmd->server->is_virtual) {
+ ap_user_name = arg;
+ cmd->server->server_uid = ap_user_id = ap_uname2id(arg);
+ }
+ else {
+ if (ap_suexec_enabled) {
+ cmd->server->server_uid = ap_uname2id(arg);
+ }
+ else {
+ cmd->server->server_uid = ap_user_id;
+ fprintf(stderr,
+ "Warning: User directive in "
+ "requires SUEXEC wrapper.\n");
+ }
+ }
+#if !defined (BIG_SECURITY_HOLE) && !defined (OS2)
+ if (cmd->server->server_uid == 0) {
+ fprintf(stderr,
+ "Error:\tApache has not been designed to serve pages while\n"
+ "\trunning as root. There are known race conditions that\n"
+ "\twill allow any local user to read any file on the system.\n"
+ "\tIf you still desire to serve pages as root then\n"
+ "\tadd -DBIG_SECURITY_HOLE to the EXTRA_CFLAGS line in your\n"
+ "\tsrc/Configuration file and rebuild the server. It is\n"
+ "\tstrongly suggested that you instead modify the User\n"
+ "\tdirective in your httpd.conf file to list a non-root\n"
+ "\tuser.\n");
+ exit (1);
+ }
+#endif
+#endif /* WIN32 */
+
+ return NULL;
+}
+
+static const char *set_group(cmd_parms *cmd, void *dummy, char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
+ if (err != NULL) {
+ return err;
+ }
+
+ if (!cmd->server->is_virtual) {
+ cmd->server->server_gid = ap_group_id = ap_gname2id(arg);
+ }
+ else {
+ if (ap_suexec_enabled) {
+ cmd->server->server_gid = ap_gname2id(arg);
+ }
+ else {
+ cmd->server->server_gid = ap_group_id;
+ fprintf(stderr,
+ "Warning: Group directive in requires "
+ "SUEXEC wrapper.\n");
+ }
+ }
+
+ return NULL;
+}
+
+static const char *set_server_root(cmd_parms *cmd, void *dummy, char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+
+ if (err != NULL) {
+ return err;
+ }
+
+ arg = ap_os_canonical_filename(cmd->pool, arg);
+
+ if (!ap_is_directory(arg)) {
+ return "ServerRoot must be a valid directory";
+ }
+ ap_cpystrn(ap_server_root, arg,
+ sizeof(ap_server_root));
+ return NULL;
+}
+
+static const char *set_timeout(cmd_parms *cmd, void *dummy, char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
+ if (err != NULL) {
+ return err;
+ }
+
+ cmd->server->timeout = atoi(arg);
+ return NULL;
+}
+
+static const char *set_keep_alive_timeout(cmd_parms *cmd, void *dummy,
+ char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
+ if (err != NULL) {
+ return err;
+ }
+
+ cmd->server->keep_alive_timeout = atoi(arg);
+ return NULL;
+}
+
+static const char *set_keep_alive(cmd_parms *cmd, void *dummy, char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
+ if (err != NULL) {
+ return err;
+ }
+
+ /* We've changed it to On/Off, but used to use numbers
+ * so we accept anything but "Off" or "0" as "On"
+ */
+ if (!strcasecmp(arg, "off") || !strcmp(arg, "0")) {
+ cmd->server->keep_alive = 0;
+ }
+ else {
+ cmd->server->keep_alive = 1;
+ }
+ return NULL;
+}
+
+static const char *set_keep_alive_max(cmd_parms *cmd, void *dummy, char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
+ if (err != NULL) {
+ return err;
+ }
+
+ cmd->server->keep_alive_max = atoi(arg);
+ return NULL;
+}
+
+static const char *set_pidfile(cmd_parms *cmd, void *dummy, char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+ if (err != NULL) {
+ return err;
+ }
+
+ if (cmd->server->is_virtual) {
+ return "PidFile directive not allowed in ";
+ }
+ ap_pid_fname = arg;
+ return NULL;
+}
+
+static const char *set_scoreboard(cmd_parms *cmd, void *dummy, char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+ if (err != NULL) {
+ return err;
+ }
+
+ ap_scoreboard_fname = arg;
+ return NULL;
+}
+
+static const char *set_lockfile(cmd_parms *cmd, void *dummy, char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+ if (err != NULL) {
+ return err;
+ }
+
+ ap_lock_fname = arg;
+ return NULL;
+}
+
+static const char *set_idcheck(cmd_parms *cmd, core_dir_config *d, int arg)
+{
+ const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
+ if (err != NULL) {
+ return err;
+ }
+
+ d->do_rfc1413 = arg != 0;
+ return NULL;
+}
+
+static const char *set_hostname_lookups(cmd_parms *cmd, core_dir_config *d,
+ char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
+ if (err != NULL) {
+ return err;
+ }
+
+ if (!strcasecmp(arg, "on")) {
+ d->hostname_lookups = HOSTNAME_LOOKUP_ON;
+ }
+ else if (!strcasecmp(arg, "off")) {
+ d->hostname_lookups = HOSTNAME_LOOKUP_OFF;
+ }
+ else if (!strcasecmp(arg, "double")) {
+ d->hostname_lookups = HOSTNAME_LOOKUP_DOUBLE;
+ }
+ else {
+ return "parameter must be 'on', 'off', or 'double'";
+ }
+ return NULL;
+}
+
+static const char *set_serverpath(cmd_parms *cmd, void *dummy, char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
+ if (err != NULL) {
+ return err;
+ }
+
+ cmd->server->path = arg;
+ cmd->server->pathlen = strlen(arg);
+ return NULL;
+}
+
+static const char *set_content_md5(cmd_parms *cmd, core_dir_config *d, int arg)
+{
+ const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
+ if (err != NULL) {
+ return err;
+ }
+
+ d->content_md5 = arg != 0;
+ return NULL;
+}
+
+static const char *set_use_canonical_name(cmd_parms *cmd, core_dir_config *d,
+ char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
+ if (err != NULL) {
+ return err;
+ }
+
+ if (strcasecmp(arg, "on") == 0) {
+ d->use_canonical_name = USE_CANONICAL_NAME_ON;
+ }
+ else if (strcasecmp(arg, "off") == 0) {
+ d->use_canonical_name = USE_CANONICAL_NAME_OFF;
+ }
+ else if (strcasecmp(arg, "dns") == 0) {
+ d->use_canonical_name = USE_CANONICAL_NAME_DNS;
+ }
+ else {
+ return "parameter must be 'on', 'off', or 'dns'";
+ }
+ return NULL;
+}
+
+static const char *set_daemons_to_start(cmd_parms *cmd, void *dummy, char *arg)
+{
+#ifdef WIN32
+ fprintf(stderr, "WARNING: StartServers has no effect on Win32\n");
+#else
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+ if (err != NULL) {
+ return err;
+ }
+
+ ap_daemons_to_start = atoi(arg);
+#endif
+ return NULL;
+}
+
+static const char *set_min_free_servers(cmd_parms *cmd, void *dummy, char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+ if (err != NULL) {
+ return err;
+ }
+
+ ap_daemons_min_free = atoi(arg);
+ if (ap_daemons_min_free <= 0) {
+ fprintf(stderr, "WARNING: detected MinSpareServers set to non-positive.\n");
+ fprintf(stderr, "Resetting to 1 to avoid almost certain Apache failure.\n");
+ fprintf(stderr, "Please read the documentation.\n");
+ ap_daemons_min_free = 1;
+ }
+
+ return NULL;
+}
+
+static const char *set_max_free_servers(cmd_parms *cmd, void *dummy, char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+ if (err != NULL) {
+ return err;
+ }
+
+ ap_daemons_max_free = atoi(arg);
+ return NULL;
+}
+
+static const char *set_server_limit (cmd_parms *cmd, void *dummy, char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+ if (err != NULL) {
+ return err;
+ }
+
+ ap_daemons_limit = atoi(arg);
+ if (ap_daemons_limit > HARD_SERVER_LIMIT) {
+ fprintf(stderr, "WARNING: MaxClients of %d exceeds compile time limit "
+ "of %d servers,\n", ap_daemons_limit, HARD_SERVER_LIMIT);
+ fprintf(stderr, " lowering MaxClients to %d. To increase, please "
+ "see the\n", HARD_SERVER_LIMIT);
+ fprintf(stderr, " HARD_SERVER_LIMIT define in src/include/httpd.h.\n");
+ ap_daemons_limit = HARD_SERVER_LIMIT;
+ }
+ else if (ap_daemons_limit < 1) {
+ fprintf(stderr, "WARNING: Require MaxClients > 0, setting to 1\n");
+ ap_daemons_limit = 1;
+ }
+ return NULL;
+}
+
+static const char *set_max_requests(cmd_parms *cmd, void *dummy, char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+ if (err != NULL) {
+ return err;
+ }
+
+ ap_max_requests_per_child = atoi(arg);
+ return NULL;
+}
+
+static const char *set_threads(cmd_parms *cmd, void *dummy, char *arg) {
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+ if (err != NULL) {
+ return err;
+ }
+
+ ap_threads_per_child = atoi(arg);
+ if (ap_threads_per_child > HARD_SERVER_LIMIT) {
+ fprintf(stderr, "WARNING: ThreadsPerChild of %d exceeds compile time limit "
+ "of %d threads,\n", ap_threads_per_child, HARD_SERVER_LIMIT);
+ fprintf(stderr, " lowering ThreadsPerChild to %d. To increase, please "
+ "see the\n", HARD_SERVER_LIMIT);
+ fprintf(stderr, " HARD_SERVER_LIMIT define in src/include/httpd.h.\n");
+ ap_threads_per_child = HARD_SERVER_LIMIT;
+ }
+ else if (ap_threads_per_child < 1) {
+ fprintf(stderr, "WARNING: Require ThreadsPerChild > 0, setting to 1\n");
+ ap_threads_per_child = 1;
+ }
+
+ return NULL;
+}
+
+static const char *set_excess_requests(cmd_parms *cmd, void *dummy, char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+ if (err != NULL) {
+ return err;
+ }
+
+ ap_excess_requests_per_child = atoi(arg);
+ return NULL;
+}
+
+
+#if defined(RLIMIT_CPU) || defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_NPROC) || defined(RLIMIT_AS)
+static void set_rlimit(cmd_parms *cmd, struct rlimit **plimit, const char *arg,
+ const char * arg2, int type)
+{
+ char *str;
+ struct rlimit *limit;
+ /* If your platform doesn't define rlim_t then typedef it in ap_config.h */
+ rlim_t cur = 0;
+ rlim_t max = 0;
+
+ *plimit = (struct rlimit *)ap_pcalloc(cmd->pool, sizeof(**plimit));
+ limit = *plimit;
+ if ((getrlimit(type, limit)) != 0) {
+ *plimit = NULL;
+ ap_log_error(APLOG_MARK, APLOG_ERR, cmd->server,
+ "%s: getrlimit failed", cmd->cmd->name);
+ return;
+ }
+
+ if ((str = ap_getword_conf(cmd->pool, &arg))) {
+ if (!strcasecmp(str, "max")) {
+ cur = limit->rlim_max;
+ }
+ else {
+ cur = atol(str);
+ }
+ }
+ else {
+ ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, cmd->server,
+ "Invalid parameters for %s", cmd->cmd->name);
+ return;
+ }
+
+ if (arg2 && (str = ap_getword_conf(cmd->pool, &arg2))) {
+ max = atol(str);
+ }
+
+ /* if we aren't running as root, cannot increase max */
+ if (geteuid()) {
+ limit->rlim_cur = cur;
+ if (max) {
+ ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, cmd->server,
+ "Must be uid 0 to raise maximum %s", cmd->cmd->name);
+ }
+ }
+ else {
+ if (cur) {
+ limit->rlim_cur = cur;
+ }
+ if (max) {
+ limit->rlim_max = max;
+ }
+ }
+}
+#endif
+
+#if !defined (RLIMIT_CPU) || !(defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)) || !defined (RLIMIT_NPROC)
+static const char *no_set_limit(cmd_parms *cmd, core_dir_config *conf,
+ char *arg, char *arg2)
+{
+ ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, cmd->server,
+ "%s not supported on this platform", cmd->cmd->name);
+ return NULL;
+}
+#endif
+
+#ifdef RLIMIT_CPU
+static const char *set_limit_cpu(cmd_parms *cmd, core_dir_config *conf,
+ char *arg, char *arg2)
+{
+ set_rlimit(cmd, &conf->limit_cpu, arg, arg2, RLIMIT_CPU);
+ return NULL;
+}
+#endif
+
+#if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)
+static const char *set_limit_mem(cmd_parms *cmd, core_dir_config *conf,
+ char *arg, char * arg2)
+{
+#if defined(RLIMIT_AS)
+ set_rlimit(cmd, &conf->limit_mem, arg, arg2 ,RLIMIT_AS);
+#elif defined(RLIMIT_DATA)
+ set_rlimit(cmd, &conf->limit_mem, arg, arg2, RLIMIT_DATA);
+#elif defined(RLIMIT_VMEM)
+ set_rlimit(cmd, &conf->limit_mem, arg, arg2, RLIMIT_VMEM);
+#endif
+ return NULL;
+}
+#endif
+
+#ifdef RLIMIT_NPROC
+static const char *set_limit_nproc(cmd_parms *cmd, core_dir_config *conf,
+ char *arg, char * arg2)
+{
+ set_rlimit(cmd, &conf->limit_nproc, arg, arg2, RLIMIT_NPROC);
+ return NULL;
+}
+#endif
+
+static const char *set_bind_address(cmd_parms *cmd, void *dummy, char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+ if (err != NULL) {
+ return err;
+ }
+
+ ap_bind_address.s_addr = ap_get_virthost_addr(arg, NULL);
+ return NULL;
+}
+
+static const char *set_listener(cmd_parms *cmd, void *dummy, char *ips)
+{
+ listen_rec *new;
+ char *ports;
+ unsigned short port;
+
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+ if (err != NULL) {
+ return err;
+ }
+
+ ports = strchr(ips, ':');
+ if (ports != NULL) {
+ if (ports == ips) {
+ return "Missing IP address";
+ }
+ else if (ports[1] == '\0') {
+ return "Address must end in :";
+ }
+ *(ports++) = '\0';
+ }
+ else {
+ ports = ips;
+ }
+
+ new=ap_pcalloc(cmd->pool, sizeof(listen_rec));
+ new->local_addr.sin_family = AF_INET;
+ if (ports == ips) { /* no address */
+ new->local_addr.sin_addr.s_addr = htonl(INADDR_ANY);
+ }
+ else {
+ new->local_addr.sin_addr.s_addr = ap_get_virthost_addr(ips, NULL);
+ }
+ port = atoi(ports);
+ if (!port) {
+ return "Port must be numeric";
+ }
+ new->local_addr.sin_port = htons(port);
+ new->fd = -1;
+ new->used = 0;
+ new->next = ap_listeners;
+ ap_listeners = new;
+ return NULL;
+}
+
+static const char *set_listenbacklog(cmd_parms *cmd, void *dummy, char *arg)
+{
+ int b;
+
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+ if (err != NULL) {
+ return err;
+ }
+
+ b = atoi(arg);
+ if (b < 1) {
+ return "ListenBacklog must be > 0";
+ }
+ ap_listenbacklog = b;
+ return NULL;
+}
+
+static const char *set_coredumpdir (cmd_parms *cmd, void *dummy, char *arg)
+{
+ struct stat finfo;
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+ if (err != NULL) {
+ return err;
+ }
+
+ arg = ap_server_root_relative(cmd->pool, arg);
+ if ((stat(arg, &finfo) == -1) || !S_ISDIR(finfo.st_mode)) {
+ return ap_pstrcat(cmd->pool, "CoreDumpDirectory ", arg,
+ " does not exist or is not a directory", NULL);
+ }
+ ap_cpystrn(ap_coredump_dir, arg, sizeof(ap_coredump_dir));
+ return NULL;
+}
+
+static const char *include_config (cmd_parms *cmd, void *dummy, char *name)
+{
+ name = ap_server_root_relative(cmd->pool, name);
+
+ ap_process_resource_config(cmd->server, name, cmd->pool, cmd->temp_pool);
+
+ return NULL;
+}
+
+static const char *set_loglevel(cmd_parms *cmd, void *dummy, const char *arg)
+{
+ char *str;
+
+ const char *err = ap_check_cmd_context(cmd,
+ NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
+ if (err != NULL) {
+ return err;
+ }
+
+ if ((str = ap_getword_conf(cmd->pool, &arg))) {
+ if (!strcasecmp(str, "emerg")) {
+ cmd->server->loglevel = APLOG_EMERG;
+ }
+ else if (!strcasecmp(str, "alert")) {
+ cmd->server->loglevel = APLOG_ALERT;
+ }
+ else if (!strcasecmp(str, "crit")) {
+ cmd->server->loglevel = APLOG_CRIT;
+ }
+ else if (!strcasecmp(str, "error")) {
+ cmd->server->loglevel = APLOG_ERR;
+ }
+ else if (!strcasecmp(str, "warn")) {
+ cmd->server->loglevel = APLOG_WARNING;
+ }
+ else if (!strcasecmp(str, "notice")) {
+ cmd->server->loglevel = APLOG_NOTICE;
+ }
+ else if (!strcasecmp(str, "info")) {
+ cmd->server->loglevel = APLOG_INFO;
+ }
+ else if (!strcasecmp(str, "debug")) {
+ cmd->server->loglevel = APLOG_DEBUG;
+ }
+ else {
+ return "LogLevel requires level keyword: one of "
+ "emerg/alert/crit/error/warn/notice/info/debug";
+ }
+ }
+ else {
+ return "LogLevel requires level keyword";
+ }
+
+ return NULL;
+}
+
+API_EXPORT(const char *) ap_psignature(const char *prefix, request_rec *r)
+{
+ char sport[20];
+ core_dir_config *conf;
+
+ conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
+ &core_module);
+ if ((conf->server_signature == srv_sig_off)
+ || (conf->server_signature == srv_sig_unset)) {
+ return "";
+ }
+
+ ap_snprintf(sport, sizeof sport, "%u", (unsigned) ap_get_server_port(r));
+
+ if (conf->server_signature == srv_sig_withmail) {
+ return ap_pstrcat(r->pool, prefix, "" SERVER_BASEVERSION
+ " Server at server->server_admin, "\">",
+ ap_get_server_name(r), " Port ", sport,
+ "\n", NULL);
+ }
+ return ap_pstrcat(r->pool, prefix, "" SERVER_BASEVERSION
+ " Server at ", ap_get_server_name(r), " Port ", sport,
+ "\n", NULL);
+}
+
+/*
+ * Load an authorisation realm into our location configuration, applying the
+ * usual rules that apply to realms.
+ */
+static const char *set_authname(cmd_parms *cmd, void *mconfig, char *word1)
+{
+ core_dir_config *aconfig = (core_dir_config *)mconfig;
+
+ aconfig->ap_auth_name = ap_escape_quotes(cmd->pool, word1);
+ return NULL;
+}
+
+#ifdef _OSD_POSIX /* BS2000 Logon Passwd file */
+static const char *set_bs2000_account(cmd_parms *cmd, void *dummy, char *name)
+{
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+ if (err != NULL) {
+ return err;
+ }
+
+ return os_set_account(cmd->pool, name);
+}
+#endif /*_OSD_POSIX*/
+
+/*
+ * Handle a request to include the server's OS platform in the Server
+ * response header field (the ServerTokens directive). Unfortunately
+ * this requires a new global in order to communicate the setting back to
+ * http_main so it can insert the information in the right place in the
+ * string.
+ */
+
+static const char *set_serv_tokens(cmd_parms *cmd, void *dummy, char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+ if (err != NULL) {
+ return err;
+ }
+
+ if (!strcasecmp(arg, "OS")) {
+ ap_server_tokens = SrvTk_OS;
+ }
+ else if (!strcasecmp(arg, "Min") || !strcasecmp(arg, "Minimal")) {
+ ap_server_tokens = SrvTk_MIN;
+ }
+ else {
+ ap_server_tokens = SrvTk_FULL;
+ }
+ return NULL;
+}
+
+static const char *set_limit_req_line(cmd_parms *cmd, void *dummy, char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd,
+ NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
+ int lim;
+
+ if (err != NULL) {
+ return err;
+ }
+ lim = atoi(arg);
+ if (lim < 0) {
+ return ap_pstrcat(cmd->temp_pool, "LimitRequestLine \"", arg,
+ "\" must be a non-negative integer", NULL);
+ }
+ if (lim > DEFAULT_LIMIT_REQUEST_LINE) {
+ return ap_psprintf(cmd->temp_pool, "LimitRequestLine \"%s\" "
+ "must not exceed the precompiled maximum of %d",
+ arg, DEFAULT_LIMIT_REQUEST_LINE);
+ }
+ cmd->server->limit_req_line = lim;
+ return NULL;
+}
+
+static const char *set_limit_req_fieldsize(cmd_parms *cmd, void *dummy,
+ char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd,
+ NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
+ int lim;
+
+ if (err != NULL) {
+ return err;
+ }
+ lim = atoi(arg);
+ if (lim < 0) {
+ return ap_pstrcat(cmd->temp_pool, "LimitRequestFieldsize \"", arg,
+ "\" must be a non-negative integer (0 = no limit)",
+ NULL);
+ }
+ if (lim > DEFAULT_LIMIT_REQUEST_FIELDSIZE) {
+ return ap_psprintf(cmd->temp_pool, "LimitRequestFieldsize \"%s\" "
+ "must not exceed the precompiled maximum of %d",
+ arg, DEFAULT_LIMIT_REQUEST_FIELDSIZE);
+ }
+ cmd->server->limit_req_fieldsize = lim;
+ return NULL;
+}
+
+static const char *set_limit_req_fields(cmd_parms *cmd, void *dummy, char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd,
+ NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
+ int lim;
+
+ if (err != NULL) {
+ return err;
+ }
+ lim = atoi(arg);
+ if (lim < 0) {
+ return ap_pstrcat(cmd->temp_pool, "LimitRequestFields \"", arg,
+ "\" must be a non-negative integer (0 = no limit)",
+ NULL);
+ }
+ cmd->server->limit_req_fields = lim;
+ return NULL;
+}
+
+static const char *set_limit_req_body(cmd_parms *cmd, core_dir_config *conf,
+ char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
+ if (err != NULL) {
+ return err;
+ }
+
+ /* WTF: If strtoul is not portable, then write a replacement.
+ * Instead we have an idiotic define in httpd.h that prevents
+ * it from being used even when it is available. Sheesh.
+ */
+ conf->limit_req_body = (unsigned long)strtol(arg, (char **)NULL, 10);
+ return NULL;
+}
+
+#ifdef WIN32
+static const char *set_interpreter_source(cmd_parms *cmd, core_dir_config *d,
+ char *arg)
+{
+ if (!strcasecmp(arg, "registry")) {
+ d->script_interpreter_source = INTERPRETER_SOURCE_REGISTRY;
+ } else if (!strcasecmp(arg, "script")) {
+ d->script_interpreter_source = INTERPRETER_SOURCE_SHEBANG;
+ } else {
+ d->script_interpreter_source = INTERPRETER_SOURCE_SHEBANG;
+ }
+ return NULL;
+}
+#endif
+
+/* Note --- ErrorDocument will now work from .htaccess files.
+ * The AllowOverride of Fileinfo allows webmasters to turn it off
+ */
+
+static const command_rec core_cmds[] = {
+
+/* Old access config file commands */
+
+{ "" },
+{ "" },
+{ "" },
+{ "" },
+{ "", endlimit_section, NULL, OR_ALL, NO_ARGS,
+ "Marks end of " },
+{ "", endlimit_section, (void*)1, OR_ALL, NO_ARGS,
+ "Marks end of " },
+{ "" },
+{ "" },
+{ "" },
+{ "" },
+{ "" },
+{ "AuthType", ap_set_string_slot,
+ (void*)XtOffsetOf(core_dir_config, ap_auth_type), OR_AUTHCFG, TAKE1,
+ "An HTTP authorization type (e.g., \"Basic\")" },
+{ "AuthName", set_authname, NULL, OR_AUTHCFG, TAKE1,
+ "The authentication realm (e.g. \"Members Only\")" },
+{ "Require", require, NULL, OR_AUTHCFG, RAW_ARGS,
+ "Selects which authenticated users or groups may access a protected space" },
+{ "Satisfy", satisfy, NULL, OR_AUTHCFG, TAKE1,
+ "access policy if both allow and require used ('all' or 'any')" },
+#ifdef GPROF
+{ "GprofDir", set_gprof_dir, NULL, RSRC_CONF, TAKE1,
+ "Directory to plop gmon.out files" },
+#endif
+
+/* Old resource config file commands */
+
+{ "AccessFileName", set_access_name, NULL, RSRC_CONF, RAW_ARGS,
+ "Name(s) of per-directory config files (default: .htaccess)" },
+{ "DocumentRoot", set_document_root, NULL, RSRC_CONF, TAKE1,
+ "Root directory of the document tree" },
+{ "ErrorDocument", set_error_document, NULL, OR_FILEINFO, RAW_ARGS,
+ "Change responses for HTTP errors" },
+{ "AllowOverride", set_override, NULL, ACCESS_CONF, RAW_ARGS,
+ "Controls what groups of directives can be configured by per-directory "
+ "config files" },
+{ "Options", set_options, NULL, OR_OPTIONS, RAW_ARGS,
+ "Set a number of attributes for a given directory" },
+{ "DefaultType", ap_set_string_slot,
+ (void*)XtOffsetOf (core_dir_config, ap_default_type),
+ OR_FILEINFO, TAKE1, "the default MIME type for untypable files" },
+
+/* Old server config file commands */
+
+{ "ServerType", server_type, NULL, RSRC_CONF, TAKE1,
+ "'inetd' or 'standalone'"},
+{ "Port", server_port, NULL, RSRC_CONF, TAKE1, "A TCP port number"},
+{ "HostnameLookups", set_hostname_lookups, NULL, ACCESS_CONF|RSRC_CONF, TAKE1,
+ "\"on\" to enable, \"off\" to disable reverse DNS lookups, or \"double\" to "
+ "enable double-reverse DNS lookups" },
+{ "User", set_user, NULL, RSRC_CONF, TAKE1,
+ "Effective user id for this server"},
+{ "Group", set_group, NULL, RSRC_CONF, TAKE1,
+ "Effective group id for this server"},
+{ "ServerAdmin", set_server_string_slot,
+ (void *)XtOffsetOf (server_rec, server_admin), RSRC_CONF, TAKE1,
+ "The email address of the server administrator" },
+{ "ServerName", set_server_string_slot,
+ (void *)XtOffsetOf (server_rec, server_hostname), RSRC_CONF, TAKE1,
+ "The hostname of the server" },
+{ "ServerSignature", set_signature_flag, NULL, OR_ALL, TAKE1,
+ "En-/disable server signature (on|off|email)" },
+{ "ServerRoot", set_server_root, NULL, RSRC_CONF, TAKE1,
+ "Common directory of server-related files (logs, confs, etc.)" },
+{ "ErrorLog", set_server_string_slot,
+ (void *)XtOffsetOf (server_rec, error_fname), RSRC_CONF, TAKE1,
+ "The filename of the error log" },
+{ "PidFile", set_pidfile, NULL, RSRC_CONF, TAKE1,
+ "A file for logging the server process ID"},
+{ "ScoreBoardFile", set_scoreboard, NULL, RSRC_CONF, TAKE1,
+ "A file for Apache to maintain runtime process management information"},
+{ "LockFile", set_lockfile, NULL, RSRC_CONF, TAKE1,
+ "The lockfile used when Apache needs to lock the accept() call"},
+{ "AccessConfig", set_server_string_slot,
+ (void *)XtOffsetOf (server_rec, access_confname), RSRC_CONF, TAKE1,
+ "The filename of the access config file" },
+{ "ResourceConfig", set_server_string_slot,
+ (void *)XtOffsetOf (server_rec, srm_confname), RSRC_CONF, TAKE1,
+ "The filename of the resource config file" },
+{ "ServerAlias", set_server_alias, NULL, RSRC_CONF, RAW_ARGS,
+ "A name or names alternately used to access the server" },
+{ "ServerPath", set_serverpath, NULL, RSRC_CONF, TAKE1,
+ "The pathname the server can be reached at" },
+{ "Timeout", set_timeout, NULL, RSRC_CONF, TAKE1, "Timeout duration (sec)" },
+{ "KeepAliveTimeout", set_keep_alive_timeout, NULL, RSRC_CONF, TAKE1,
+ "Keep-Alive timeout duration (sec)"},
+{ "MaxKeepAliveRequests", set_keep_alive_max, NULL, RSRC_CONF, TAKE1,
+ "Maximum number of Keep-Alive requests per connection, or 0 for infinite" },
+{ "KeepAlive", set_keep_alive, NULL, RSRC_CONF, TAKE1,
+ "Whether persistent connections should be On or Off" },
+{ "IdentityCheck", set_idcheck, NULL, RSRC_CONF|ACCESS_CONF, FLAG,
+ "Enable identd (RFC 1413) user lookups - SLOW" },
+{ "ContentDigest", set_content_md5, NULL, OR_OPTIONS,
+ FLAG, "whether or not to send a Content-MD5 header with each request" },
+{ "UseCanonicalName", set_use_canonical_name, NULL,
+ RSRC_CONF, TAKE1,
+ "How to work out the ServerName : Port when constructing URLs" },
+{ "StartServers", set_daemons_to_start, NULL, RSRC_CONF, TAKE1,
+ "Number of child processes launched at server startup" },
+{ "MinSpareServers", set_min_free_servers, NULL, RSRC_CONF, TAKE1,
+ "Minimum number of idle children, to handle request spikes" },
+{ "MaxSpareServers", set_max_free_servers, NULL, RSRC_CONF, TAKE1,
+ "Maximum number of idle children" },
+{ "MaxServers", set_max_free_servers, NULL, RSRC_CONF, TAKE1,
+ "Deprecated equivalent to MaxSpareServers" },
+{ "ServersSafetyLimit", set_server_limit, NULL, RSRC_CONF, TAKE1,
+ "Deprecated equivalent to MaxClients" },
+{ "MaxClients", set_server_limit, NULL, RSRC_CONF, TAKE1,
+ "Maximum number of children alive at the same time" },
+{ "MaxRequestsPerChild", set_max_requests, NULL, RSRC_CONF, TAKE1,
+ "Maximum number of requests a particular child serves before dying." },
+{ "RLimitCPU",
+#ifdef RLIMIT_CPU
+ set_limit_cpu, (void*)XtOffsetOf(core_dir_config, limit_cpu),
+#else
+ no_set_limit, NULL,
+#endif
+ OR_ALL, TAKE12, "Soft/hard limits for max CPU usage in seconds" },
+{ "RLimitMEM",
+#if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined (RLIMIT_AS)
+ set_limit_mem, (void*)XtOffsetOf(core_dir_config, limit_mem),
+#else
+ no_set_limit, NULL,
+#endif
+ OR_ALL, TAKE12, "Soft/hard limits for max memory usage per process" },
+{ "RLimitNPROC",
+#ifdef RLIMIT_NPROC
+ set_limit_nproc, (void*)XtOffsetOf(core_dir_config, limit_nproc),
+#else
+ no_set_limit, NULL,
+#endif
+ OR_ALL, TAKE12, "soft/hard limits for max number of processes per uid" },
+{ "BindAddress", set_bind_address, NULL, RSRC_CONF, TAKE1,
+ "'*', a numeric IP address, or the name of a host with a unique IP address"},
+{ "Listen", set_listener, NULL, RSRC_CONF, TAKE1,
+ "A port number or a numeric IP address and a port number"},
+{ "SendBufferSize", set_send_buffer_size, NULL, RSRC_CONF, TAKE1,
+ "Send buffer size in bytes"},
+{ "AddModule", add_module_command, NULL, RSRC_CONF, ITERATE,
+ "The name of a module" },
+{ "ClearModuleList", clear_module_list_command, NULL, RSRC_CONF, NO_ARGS,
+ NULL },
+{ "ThreadsPerChild", set_threads, NULL, RSRC_CONF, TAKE1,
+ "Number of threads a child creates" },
+{ "ExcessRequestsPerChild", set_excess_requests, NULL, RSRC_CONF, TAKE1,
+ "Maximum number of requests a particular child serves after it is ready "
+ "to die." },
+{ "ListenBacklog", set_listenbacklog, NULL, RSRC_CONF, TAKE1,
+ "Maximum length of the queue of pending connections, as used by listen(2)" },
+{ "CoreDumpDirectory", set_coredumpdir, NULL, RSRC_CONF, TAKE1,
+ "The location of the directory Apache changes to before dumping core" },
+{ "Include", include_config, NULL, (RSRC_CONF | ACCESS_CONF), TAKE1,
+ "Name of the config file to be included" },
+{ "LogLevel", set_loglevel, NULL, RSRC_CONF, TAKE1,
+ "Level of verbosity in error logging" },
+{ "NameVirtualHost", ap_set_name_virtual_host, NULL, RSRC_CONF, TAKE1,
+ "A numeric IP address:port, or the name of a host" },
+#ifdef _OSD_POSIX
+{ "BS2000Account", set_bs2000_account, NULL, RSRC_CONF, TAKE1,
+ "Name of server User's bs2000 logon account name" },
+#endif
+#ifdef WIN32
+{ "ScriptInterpreterSource", set_interpreter_source, NULL, OR_FILEINFO, TAKE1,
+ "Where to find interpreter to run Win32 scripts (Registry or script shebang line)" },
+#endif
+{ "ServerTokens", set_serv_tokens, NULL, RSRC_CONF, TAKE1,
+ "Determine tokens displayed in the Server: header - Min(imal), OS or Full" },
+{ "LimitRequestLine", set_limit_req_line, NULL, RSRC_CONF, TAKE1,
+ "Limit on maximum size of an HTTP request line"},
+{ "LimitRequestFieldsize", set_limit_req_fieldsize, NULL, RSRC_CONF, TAKE1,
+ "Limit on maximum size of an HTTP request header field"},
+{ "LimitRequestFields", set_limit_req_fields, NULL, RSRC_CONF, TAKE1,
+ "Limit (0 = unlimited) on max number of header fields in a request message"},
+{ "LimitRequestBody", set_limit_req_body,
+ (void*)XtOffsetOf(core_dir_config, limit_req_body),
+ OR_ALL, TAKE1,
+ "Limit (in bytes) on maximum size of request message body" },
+{ NULL }
+};
+
+/*****************************************************************
+ *
+ * Core handlers for various phases of server operation...
+ */
+
+static int core_translate(request_rec *r)
+{
+ void *sconf = r->server->module_config;
+ core_server_config *conf = ap_get_module_config(sconf, &core_module);
+
+ if (r->proxyreq) {
+ return HTTP_FORBIDDEN;
+ }
+ if ((r->uri[0] != '/') && strcmp(r->uri, "*")) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Invalid URI in request %s", r->the_request);
+ return BAD_REQUEST;
+ }
+
+ if (r->server->path
+ && !strncmp(r->uri, r->server->path, r->server->pathlen)
+ && (r->server->path[r->server->pathlen - 1] == '/'
+ || r->uri[r->server->pathlen] == '/'
+ || r->uri[r->server->pathlen] == '\0')) {
+ r->filename = ap_pstrcat(r->pool, conf->ap_document_root,
+ (r->uri + r->server->pathlen), NULL);
+ }
+ else {
+ /*
+ * Make sure that we do not mess up the translation by adding two
+ * /'s in a row. This happens under windows when the document
+ * root ends with a /
+ */
+ if ((conf->ap_document_root[strlen(conf->ap_document_root)-1] == '/')
+ && (*(r->uri) == '/')) {
+ r->filename = ap_pstrcat(r->pool, conf->ap_document_root, r->uri+1,
+ NULL);
+ }
+ else {
+ r->filename = ap_pstrcat(r->pool, conf->ap_document_root, r->uri,
+ NULL);
+ }
+ }
+
+ return OK;
+}
+
+static int do_nothing(request_rec *r) { return OK; }
+
+#ifdef USE_MMAP_FILES
+struct mmap_rec {
+ void *mm;
+ size_t length;
+};
+
+static void mmap_cleanup(void *mmv)
+{
+ struct mmap_rec *mmd = mmv;
+
+ if (munmap(mmd->mm, mmd->length) == -1) {
+ ap_log_error(APLOG_MARK, APLOG_ERR, NULL,
+ "Failed to munmap memory of length %ld at 0x%lx",
+ (long) mmd->length, (long) mmd->mm);
+ }
+}
+#endif
+
+/*
+ * Default handler for MIME types without other handlers. Only GET
+ * and OPTIONS at this point... anyone who wants to write a generic
+ * handler for PUT or POST is free to do so, but it seems unwise to provide
+ * any defaults yet... So, for now, we assume that this will always be
+ * the last handler called and return 405 or 501.
+ */
+
+static int default_handler(request_rec *r)
+{
+ core_dir_config *d =
+ (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
+ int rangestatus, errstatus;
+ FILE *f;
+#ifdef USE_MMAP_FILES
+ caddr_t mm;
+#endif
+#ifdef CHARSET_EBCDIC
+ int convert_flag;
+#endif
+
+ /* This handler has no use for a request body (yet), but we still
+ * need to read and discard it if the client sent one.
+ */
+ if ((errstatus = ap_discard_request_body(r)) != OK) {
+ return errstatus;
+ }
+
+ r->allowed |= (1 << M_GET) | (1 << M_OPTIONS);
+
+ if (r->method_number == M_INVALID) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Invalid method in request %s", r->the_request);
+ return NOT_IMPLEMENTED;
+ }
+ if (r->method_number == M_OPTIONS) {
+ return ap_send_http_options(r);
+ }
+ if (r->method_number == M_PUT) {
+ return METHOD_NOT_ALLOWED;
+ }
+
+ if (r->finfo.st_mode == 0 || (r->path_info && *r->path_info)) {
+ char *emsg;
+
+ emsg = "File does not exist: ";
+ if (r->path_info == NULL) {
+ emsg = ap_pstrcat(r->pool, emsg, r->filename, NULL);
+ }
+ else {
+ emsg = ap_pstrcat(r->pool, emsg, r->filename, r->path_info, NULL);
+ }
+ ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, r, "%s", emsg);
+ return HTTP_NOT_FOUND;
+ }
+ if (r->method_number != M_GET) {
+ return METHOD_NOT_ALLOWED;
+ }
+
+#if defined(OS2) || defined(WIN32)
+ /* Need binary mode for OS/2 */
+ f = ap_pfopen(r->pool, r->filename, "rb");
+#else
+ f = ap_pfopen(r->pool, r->filename, "r");
+#endif
+
+ if (f == NULL) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
+ "file permissions deny server access: %s", r->filename);
+ return FORBIDDEN;
+ }
+
+ ap_update_mtime(r, r->finfo.st_mtime);
+ ap_set_last_modified(r);
+ ap_set_etag(r);
+ ap_table_setn(r->headers_out, "Accept-Ranges", "bytes");
+ if (((errstatus = ap_meets_conditions(r)) != OK)
+ || (errstatus = ap_set_content_length(r, r->finfo.st_size))) {
+ return errstatus;
+ }
+
+#ifdef USE_MMAP_FILES
+ ap_block_alarms();
+ if ((r->finfo.st_size >= MMAP_THRESHOLD)
+ && (r->finfo.st_size < MMAP_LIMIT)
+ && (!r->header_only || (d->content_md5 & 1))) {
+ /* we need to protect ourselves in case we die while we've got the
+ * file mmapped */
+ mm = mmap(NULL, r->finfo.st_size, PROT_READ, MAP_PRIVATE,
+ fileno(f), 0);
+ if (mm == (caddr_t)-1) {
+ ap_log_rerror(APLOG_MARK, APLOG_CRIT, r,
+ "default_handler: mmap failed: %s", r->filename);
+ }
+ }
+ else {
+ mm = (caddr_t)-1;
+ }
+
+ if (mm == (caddr_t)-1) {
+ ap_unblock_alarms();
+#endif
+
+#ifdef CHARSET_EBCDIC
+ /* To make serving of "raw ASCII text" files easy (they serve faster
+ * since they don't have to be converted from EBCDIC), a new
+ * "magic" type prefix was invented: text/x-ascii-{plain,html,...}
+ * If we detect one of these content types here, we simply correct
+ * the type to the real text/{plain,html,...} type. Otherwise, we
+ * set a flag that translation is required later on.
+ */
+ convert_flag = ap_checkconv(r);
+ if (d->content_md5 & 1) {
+ ap_table_setn(r->headers_out, "Content-MD5",
+ ap_md5digest(r->pool, f, convert_flag));
+ }
+#else
+ if (d->content_md5 & 1) {
+ ap_table_setn(r->headers_out, "Content-MD5",
+ ap_md5digest(r->pool, f));
+ }
+#endif /* CHARSET_EBCDIC */
+
+ rangestatus = ap_set_byterange(r);
+
+ ap_send_http_header(r);
+
+ if (!r->header_only) {
+ if (!rangestatus) {
+ ap_send_fd(f, r);
+ }
+ else {
+ long offset, length;
+ while (ap_each_byterange(r, &offset, &length)) {
+ /*
+ * Non zero returns are more portable than checking
+ * for a return of -1.
+ */
+ if (fseek(f, offset, SEEK_SET)) {
+ ap_log_error(APLOG_MARK, APLOG_ERR, r->server,
+ "Failed to fseek for byterange (%ld, %ld)",
+ offset, length);
+ }
+ else {
+ ap_send_fd_length(f, r, length);
+ }
+ }
+ }
+ }
+
+#ifdef USE_MMAP_FILES
+ }
+ else {
+ struct mmap_rec *mmd;
+
+ mmd = ap_palloc(r->pool, sizeof(*mmd));
+ mmd->mm = mm;
+ mmd->length = r->finfo.st_size;
+ ap_register_cleanup(r->pool, (void *)mmd, mmap_cleanup, mmap_cleanup);
+ ap_unblock_alarms();
+
+ if (d->content_md5 & 1) {
+ AP_MD5_CTX context;
+
+ ap_MD5Init(&context);
+ ap_MD5Update(&context, (void *)mm, (unsigned int)r->finfo.st_size);
+ ap_table_setn(r->headers_out, "Content-MD5",
+ ap_md5contextTo64(r->pool, &context));
+ }
+
+ rangestatus = ap_set_byterange(r);
+ ap_send_http_header(r);
+
+ if (!r->header_only) {
+ if (!rangestatus) {
+ ap_send_mmap(mm, r, 0, r->finfo.st_size);
+ }
+ else {
+ long offset, length;
+ while (ap_each_byterange(r, &offset, &length)) {
+ ap_send_mmap(mm, r, offset, length);
+ }
+ }
+ }
+ }
+#endif
+
+ ap_pfclose(r->pool, f);
+ return OK;
+}
+
+static const handler_rec core_handlers[] = {
+{ "*/*", default_handler },
+{ "default-handler", default_handler },
+{ NULL, NULL }
+};
+
+API_VAR_EXPORT module core_module = {
+ STANDARD_MODULE_STUFF,
+ NULL, /* initializer */
+ create_core_dir_config, /* create per-directory config structure */
+ merge_core_dir_configs, /* merge per-directory config structures */
+ create_core_server_config, /* create per-server config structure */
+ merge_core_server_configs, /* merge per-server config structures */
+ core_cmds, /* command table */
+ core_handlers, /* handlers */
+ core_translate, /* translate_handler */
+ NULL, /* check_user_id */
+ NULL, /* check auth */
+ do_nothing, /* check access */
+ do_nothing, /* type_checker */
+ NULL, /* pre-run fixups */
+ NULL, /* logger */
+ NULL, /* header parser */
+ NULL, /* child_init */
+ NULL, /* child_exit */
+ NULL /* post_read_request */
+};
diff --git a/modules/http/http_protocol.c b/modules/http/http_protocol.c
new file mode 100644
index 00000000000..31779312c65
--- /dev/null
+++ b/modules/http/http_protocol.c
@@ -0,0 +1,2763 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+/*
+ * http_protocol.c --- routines which directly communicate with the client.
+ *
+ * Code originally by Rob McCool; much redone by Robert S. Thau
+ * and the Apache Group.
+ */
+
+#define CORE_PRIVATE
+#include "httpd.h"
+#include "http_config.h"
+#include "http_core.h"
+#include "http_protocol.h"
+#include "http_main.h"
+#include "http_request.h"
+#include "http_vhost.h"
+#include "http_log.h" /* For errors detected in basic auth common
+ * support code... */
+#include "util_date.h" /* For parseHTTPdate and BAD_DATE */
+#include
+#include "http_conf_globals.h"
+
+#define SET_BYTES_SENT(r) \
+ do { if (r->sent_bodyct) \
+ ap_bgetopt (r->connection->client, BO_BYTECT, &r->bytes_sent); \
+ } while (0)
+
+
+static int parse_byterange(char *range, long clength, long *start, long *end)
+{
+ char *dash = strchr(range, '-');
+
+ if (!dash)
+ return 0;
+
+ if ((dash == range)) {
+ /* In the form "-5" */
+ *start = clength - atol(dash + 1);
+ *end = clength - 1;
+ }
+ else {
+ *dash = '\0';
+ dash++;
+ *start = atol(range);
+ if (*dash)
+ *end = atol(dash);
+ else /* "5-" */
+ *end = clength - 1;
+ }
+
+ if (*start < 0)
+ *start = 0;
+
+ if (*end >= clength)
+ *end = clength - 1;
+
+ if (*start > *end)
+ return 0;
+
+ return (*start > 0 || *end < clength - 1);
+}
+
+static int internal_byterange(int, long *, request_rec *, const char **, long *,
+ long *);
+
+API_EXPORT(int) ap_set_byterange(request_rec *r)
+{
+ const char *range, *if_range, *match;
+ long range_start, range_end;
+
+ if (!r->clength || r->assbackwards)
+ return 0;
+
+ /* Check for Range request-header (HTTP/1.1) or Request-Range for
+ * backwards-compatibility with second-draft Luotonen/Franks
+ * byte-ranges (e.g. Netscape Navigator 2-3).
+ *
+ * We support this form, with Request-Range, and (farther down) we
+ * send multipart/x-byteranges instead of multipart/byteranges for
+ * Request-Range based requests to work around a bug in Netscape
+ * Navigator 2-3 and MSIE 3.
+ */
+
+ if (!(range = ap_table_get(r->headers_in, "Range")))
+ range = ap_table_get(r->headers_in, "Request-Range");
+
+ if (!range || strncasecmp(range, "bytes=", 6)) {
+ return 0;
+ }
+
+ /* Check the If-Range header for Etag or Date.
+ * Note that this check will return false (as required) if either
+ * of the two etags are weak.
+ */
+ if ((if_range = ap_table_get(r->headers_in, "If-Range"))) {
+ if (if_range[0] == '"') {
+ if (!(match = ap_table_get(r->headers_out, "Etag")) ||
+ (strcmp(if_range, match) != 0))
+ return 0;
+ }
+ else if (!(match = ap_table_get(r->headers_out, "Last-Modified")) ||
+ (strcmp(if_range, match) != 0))
+ return 0;
+ }
+
+ if (!strchr(range, ',')) {
+ /* A single range */
+ if (!parse_byterange(ap_pstrdup(r->pool, range + 6), r->clength,
+ &range_start, &range_end))
+ return 0;
+
+ r->byterange = 1;
+
+ ap_table_setn(r->headers_out, "Content-Range",
+ ap_psprintf(r->pool, "bytes %ld-%ld/%ld",
+ range_start, range_end, r->clength));
+ ap_table_setn(r->headers_out, "Content-Length",
+ ap_psprintf(r->pool, "%ld", range_end - range_start + 1));
+ }
+ else {
+ /* a multiple range */
+ const char *r_range = ap_pstrdup(r->pool, range + 6);
+ long tlength = 0;
+
+ r->byterange = 2;
+ r->boundary = ap_psprintf(r->pool, "%lx%lx",
+ r->request_time, (long) getpid());
+ while (internal_byterange(0, &tlength, r, &r_range, NULL, NULL));
+ ap_table_setn(r->headers_out, "Content-Length",
+ ap_psprintf(r->pool, "%ld", tlength));
+ }
+
+ r->status = PARTIAL_CONTENT;
+ r->range = range + 6;
+
+ return 1;
+}
+
+API_EXPORT(int) ap_each_byterange(request_rec *r, long *offset, long *length)
+{
+ return internal_byterange(1, NULL, r, &r->range, offset, length);
+}
+
+/* If this function is called with realreq=1, it will spit out
+ * the correct headers for a byterange chunk, and set offset and
+ * length to the positions they should be.
+ *
+ * If it is called with realreq=0, it will add to tlength the length
+ * it *would* have used with realreq=1.
+ *
+ * Either case will return 1 if it should be called again, and 0
+ * when done.
+ */
+static int internal_byterange(int realreq, long *tlength, request_rec *r,
+ const char **r_range, long *offset, long *length)
+{
+ long range_start, range_end;
+ char *range;
+
+ if (!**r_range) {
+ if (r->byterange > 1) {
+ if (realreq)
+ ap_rvputs(r, "\015\012--", r->boundary, "--\015\012", NULL);
+ else
+ *tlength += 4 + strlen(r->boundary) + 4;
+ }
+ return 0;
+ }
+
+ range = ap_getword(r->pool, r_range, ',');
+ if (!parse_byterange(range, r->clength, &range_start, &range_end))
+ /* Skip this one */
+ return internal_byterange(realreq, tlength, r, r_range, offset,
+ length);
+
+ if (r->byterange > 1) {
+ const char *ct = r->content_type ? r->content_type : ap_default_type(r);
+ char ts[MAX_STRING_LEN];
+
+ ap_snprintf(ts, sizeof(ts), "%ld-%ld/%ld", range_start, range_end,
+ r->clength);
+ if (realreq)
+ ap_rvputs(r, "\015\012--", r->boundary, "\015\012Content-type: ",
+ ct, "\015\012Content-range: bytes ", ts, "\015\012\015\012",
+ NULL);
+ else
+ *tlength += 4 + strlen(r->boundary) + 16 + strlen(ct) + 23 +
+ strlen(ts) + 4;
+ }
+
+ if (realreq) {
+ *offset = range_start;
+ *length = range_end - range_start + 1;
+ }
+ else {
+ *tlength += range_end - range_start + 1;
+ }
+ return 1;
+}
+
+API_EXPORT(int) ap_set_content_length(request_rec *r, long clength)
+{
+ r->clength = clength;
+ ap_table_setn(r->headers_out, "Content-Length", ap_psprintf(r->pool, "%ld", clength));
+ return 0;
+}
+
+API_EXPORT(int) ap_set_keepalive(request_rec *r)
+{
+ int ka_sent = 0;
+ int wimpy = ap_find_token(r->pool,
+ ap_table_get(r->headers_out, "Connection"), "close");
+ const char *conn = ap_table_get(r->headers_in, "Connection");
+
+ /* The following convoluted conditional determines whether or not
+ * the current connection should remain persistent after this response
+ * (a.k.a. HTTP Keep-Alive) and whether or not the output message
+ * body should use the HTTP/1.1 chunked transfer-coding. In English,
+ *
+ * IF we have not marked this connection as errored;
+ * and the response body has a defined length due to the status code
+ * being 304 or 204, the request method being HEAD, already
+ * having defined Content-Length or Transfer-Encoding: chunked, or
+ * the request version being HTTP/1.1 and thus capable of being set
+ * as chunked [we know the (r->chunked = 1) side-effect is ugly];
+ * and the server configuration enables keep-alive;
+ * and the server configuration has a reasonable inter-request timeout;
+ * and there is no maximum # requests or the max hasn't been reached;
+ * and the response status does not require a close;
+ * and the response generator has not already indicated close;
+ * and the client did not request non-persistence (Connection: close);
+ * and we haven't been configured to ignore the buggy twit
+ * or they're a buggy twit coming through a HTTP/1.1 proxy
+ * and the client is requesting an HTTP/1.0-style keep-alive
+ * or the client claims to be HTTP/1.1 compliant (perhaps a proxy);
+ * THEN we can be persistent, which requires more headers be output.
+ *
+ * Note that the condition evaluation order is extremely important.
+ */
+ if ((r->connection->keepalive != -1) &&
+ ((r->status == HTTP_NOT_MODIFIED) ||
+ (r->status == HTTP_NO_CONTENT) ||
+ r->header_only ||
+ ap_table_get(r->headers_out, "Content-Length") ||
+ ap_find_last_token(r->pool,
+ ap_table_get(r->headers_out, "Transfer-Encoding"),
+ "chunked") ||
+ ((r->proto_num >= HTTP_VERSION(1,1)) &&
+ (r->chunked = 1))) && /* THIS CODE IS CORRECT, see comment above. */
+ r->server->keep_alive &&
+ (r->server->keep_alive_timeout > 0) &&
+ ((r->server->keep_alive_max == 0) ||
+ (r->server->keep_alive_max > r->connection->keepalives)) &&
+ !ap_status_drops_connection(r->status) &&
+ !wimpy &&
+ !ap_find_token(r->pool, conn, "close") &&
+ (!ap_table_get(r->subprocess_env, "nokeepalive") ||
+ ap_table_get(r->headers_in, "Via")) &&
+ ((ka_sent = ap_find_token(r->pool, conn, "keep-alive")) ||
+ (r->proto_num >= HTTP_VERSION(1,1)))
+ ) {
+ int left = r->server->keep_alive_max - r->connection->keepalives;
+
+ r->connection->keepalive = 1;
+ r->connection->keepalives++;
+
+ /* If they sent a Keep-Alive token, send one back */
+ if (ka_sent) {
+ if (r->server->keep_alive_max)
+ ap_table_setn(r->headers_out, "Keep-Alive",
+ ap_psprintf(r->pool, "timeout=%d, max=%d",
+ r->server->keep_alive_timeout, left));
+ else
+ ap_table_setn(r->headers_out, "Keep-Alive",
+ ap_psprintf(r->pool, "timeout=%d",
+ r->server->keep_alive_timeout));
+ ap_table_mergen(r->headers_out, "Connection", "Keep-Alive");
+ }
+
+ return 1;
+ }
+
+ /* Otherwise, we need to indicate that we will be closing this
+ * connection immediately after the current response.
+ *
+ * We only really need to send "close" to HTTP/1.1 clients, but we
+ * always send it anyway, because a broken proxy may identify itself
+ * as HTTP/1.0, but pass our request along with our HTTP/1.1 tag
+ * to a HTTP/1.1 client. Better safe than sorry.
+ */
+ if (!wimpy)
+ ap_table_mergen(r->headers_out, "Connection", "close");
+
+ r->connection->keepalive = 0;
+
+ return 0;
+}
+
+/*
+ * Return the latest rational time from a request/mtime (modification time)
+ * pair. We return the mtime unless it's in the future, in which case we
+ * return the current time. We use the request time as a reference in order
+ * to limit the number of calls to time(). We don't check for futurosity
+ * unless the mtime is at least as new as the reference.
+ */
+API_EXPORT(time_t) ap_rationalize_mtime(request_rec *r, time_t mtime)
+{
+ time_t now;
+
+ /* For all static responses, it's almost certain that the file was
+ * last modified before the beginning of the request. So there's
+ * no reason to call time(NULL) again. But if the response has been
+ * created on demand, then it might be newer than the time the request
+ * started. In this event we really have to call time(NULL) again
+ * so that we can give the clients the most accurate Last-Modified. If we
+ * were given a time in the future, we return the current time - the
+ * Last-Modified can't be in the future.
+ */
+ now = (mtime < r->request_time) ? r->request_time : time(NULL);
+ return (mtime > now) ? now : mtime;
+}
+
+API_EXPORT(int) ap_meets_conditions(request_rec *r)
+{
+ const char *etag = ap_table_get(r->headers_out, "ETag");
+ const char *if_match, *if_modified_since, *if_unmodified, *if_nonematch;
+ time_t mtime;
+
+ /* Check for conditional requests --- note that we only want to do
+ * this if we are successful so far and we are not processing a
+ * subrequest or an ErrorDocument.
+ *
+ * The order of the checks is important, since ETag checks are supposed
+ * to be more accurate than checks relative to the modification time.
+ * However, not all documents are guaranteed to *have* ETags, and some
+ * might have Last-Modified values w/o ETags, so this gets a little
+ * complicated.
+ */
+
+ if (!ap_is_HTTP_SUCCESS(r->status) || r->no_local_copy) {
+ return OK;
+ }
+
+ mtime = (r->mtime != 0) ? r->mtime : time(NULL);
+
+ /* If an If-Match request-header field was given
+ * AND the field value is not "*" (meaning match anything)
+ * AND if our strong ETag does not match any entity tag in that field,
+ * respond with a status of 412 (Precondition Failed).
+ */
+ if ((if_match = ap_table_get(r->headers_in, "If-Match")) != NULL) {
+ if (if_match[0] != '*' &&
+ (etag == NULL || etag[0] == 'W' ||
+ !ap_find_list_item(r->pool, if_match, etag))) {
+ return HTTP_PRECONDITION_FAILED;
+ }
+ }
+ else {
+ /* Else if a valid If-Unmodified-Since request-header field was given
+ * AND the requested resource has been modified since the time
+ * specified in this field, then the server MUST
+ * respond with a status of 412 (Precondition Failed).
+ */
+ if_unmodified = ap_table_get(r->headers_in, "If-Unmodified-Since");
+ if (if_unmodified != NULL) {
+ time_t ius = ap_parseHTTPdate(if_unmodified);
+
+ if ((ius != BAD_DATE) && (mtime > ius)) {
+ return HTTP_PRECONDITION_FAILED;
+ }
+ }
+ }
+
+ /* If an If-None-Match request-header field was given
+ * AND the field value is "*" (meaning match anything)
+ * OR our ETag matches any of the entity tags in that field, fail.
+ *
+ * If the request method was GET or HEAD, failure means the server
+ * SHOULD respond with a 304 (Not Modified) response.
+ * For all other request methods, failure means the server MUST
+ * respond with a status of 412 (Precondition Failed).
+ *
+ * GET or HEAD allow weak etag comparison, all other methods require
+ * strong comparison. We can only use weak if it's not a range request.
+ */
+ if_nonematch = ap_table_get(r->headers_in, "If-None-Match");
+ if (if_nonematch != NULL) {
+ if (r->method_number == M_GET) {
+ if (if_nonematch[0] == '*')
+ return HTTP_NOT_MODIFIED;
+ if (etag != NULL) {
+ if (ap_table_get(r->headers_in, "Range")) {
+ if (etag[0] != 'W' &&
+ ap_find_list_item(r->pool, if_nonematch, etag)) {
+ return HTTP_NOT_MODIFIED;
+ }
+ }
+ else if (strstr(if_nonematch, etag)) {
+ return HTTP_NOT_MODIFIED;
+ }
+ }
+ }
+ else if (if_nonematch[0] == '*' ||
+ (etag != NULL &&
+ ap_find_list_item(r->pool, if_nonematch, etag))) {
+ return HTTP_PRECONDITION_FAILED;
+ }
+ }
+ /* Else if a valid If-Modified-Since request-header field was given
+ * AND it is a GET or HEAD request
+ * AND the requested resource has not been modified since the time
+ * specified in this field, then the server MUST
+ * respond with a status of 304 (Not Modified).
+ * A date later than the server's current request time is invalid.
+ */
+ else if ((r->method_number == M_GET)
+ && ((if_modified_since =
+ ap_table_get(r->headers_in, "If-Modified-Since")) != NULL)) {
+ time_t ims = ap_parseHTTPdate(if_modified_since);
+
+ if ((ims >= mtime) && (ims <= r->request_time)) {
+ return HTTP_NOT_MODIFIED;
+ }
+ }
+ return OK;
+}
+
+/*
+ * Construct an entity tag (ETag) from resource information. If it's a real
+ * file, build in some of the file characteristics. If the modification time
+ * is newer than (request-time minus 1 second), mark the ETag as weak - it
+ * could be modified again in as short an interval. We rationalize the
+ * modification time we're given to keep it from being in the future.
+ */
+API_EXPORT(char *) ap_make_etag(request_rec *r, int force_weak)
+{
+ char *etag;
+ char *weak;
+
+ /*
+ * Make an ETag header out of various pieces of information. We use
+ * the last-modified date and, if we have a real file, the
+ * length and inode number - note that this doesn't have to match
+ * the content-length (i.e. includes), it just has to be unique
+ * for the file.
+ *
+ * If the request was made within a second of the last-modified date,
+ * we send a weak tag instead of a strong one, since it could
+ * be modified again later in the second, and the validation
+ * would be incorrect.
+ */
+
+ weak = ((r->request_time - r->mtime > 1) && !force_weak) ? "" : "W/";
+
+ if (r->finfo.st_mode != 0) {
+ etag = ap_psprintf(r->pool,
+ "%s\"%lx-%lx-%lx\"", weak,
+ (unsigned long) r->finfo.st_ino,
+ (unsigned long) r->finfo.st_size,
+ (unsigned long) r->mtime);
+ }
+ else {
+ etag = ap_psprintf(r->pool, "%s\"%lx\"", weak,
+ (unsigned long) r->mtime);
+ }
+
+ return etag;
+}
+
+API_EXPORT(void) ap_set_etag(request_rec *r)
+{
+ char *etag;
+ char *variant_etag, *vlv;
+ int vlv_weak;
+
+ if (!r->vlist_validator) {
+ etag = ap_make_etag(r, 0);
+ }
+ else {
+ /* If we have a variant list validator (vlv) due to the
+ * response being negotiated, then we create a structured
+ * entity tag which merges the variant etag with the variant
+ * list validator (vlv). This merging makes revalidation
+ * somewhat safer, ensures that caches which can deal with
+ * Vary will (eventually) be updated if the set of variants is
+ * changed, and is also a protocol requirement for transparent
+ * content negotiation.
+ */
+
+ /* if the variant list validator is weak, we make the whole
+ * structured etag weak. If we would not, then clients could
+ * have problems merging range responses if we have different
+ * variants with the same non-globally-unique strong etag.
+ */
+
+ vlv = r->vlist_validator;
+ vlv_weak = (vlv[0] == 'W');
+
+ variant_etag = ap_make_etag(r, vlv_weak);
+
+ /* merge variant_etag and vlv into a structured etag */
+
+ variant_etag[strlen(variant_etag) - 1] = '\0';
+ if (vlv_weak)
+ vlv += 3;
+ else
+ vlv++;
+ etag = ap_pstrcat(r->pool, variant_etag, ";", vlv, NULL);
+ }
+
+ ap_table_setn(r->headers_out, "ETag", etag);
+}
+
+/*
+ * This function sets the Last-Modified output header field to the value
+ * of the mtime field in the request structure - rationalized to keep it from
+ * being in the future.
+ */
+API_EXPORT(void) ap_set_last_modified(request_rec *r)
+{
+ time_t mod_time = ap_rationalize_mtime(r, r->mtime);
+
+ ap_table_setn(r->headers_out, "Last-Modified",
+ ap_gm_timestr_822(r->pool, mod_time));
+}
+
+/* Get the method number associated with the given string, assumed to
+ * contain an HTTP method. Returns M_INVALID if not recognized.
+ *
+ * This is the first step toward placing method names in a configurable
+ * list. Hopefully it (and other routines) can eventually be moved to
+ * something like a mod_http_methods.c, complete with config stuff.
+ */
+API_EXPORT(int) ap_method_number_of(const char *method)
+{
+ switch (*method) {
+ case 'H':
+ if (strcmp(method, "HEAD") == 0)
+ return M_GET; /* see header_only in request_rec */
+ break;
+ case 'G':
+ if (strcmp(method, "GET") == 0)
+ return M_GET;
+ break;
+ case 'P':
+ if (strcmp(method, "POST") == 0)
+ return M_POST;
+ if (strcmp(method, "PUT") == 0)
+ return M_PUT;
+ if (strcmp(method, "PATCH") == 0)
+ return M_PATCH;
+ if (strcmp(method, "PROPFIND") == 0)
+ return M_PROPFIND;
+ if (strcmp(method, "PROPPATCH") == 0)
+ return M_PROPPATCH;
+ break;
+ case 'D':
+ if (strcmp(method, "DELETE") == 0)
+ return M_DELETE;
+ break;
+ case 'C':
+ if (strcmp(method, "CONNECT") == 0)
+ return M_CONNECT;
+ if (strcmp(method, "COPY") == 0)
+ return M_COPY;
+ break;
+ case 'M':
+ if (strcmp(method, "MKCOL") == 0)
+ return M_MKCOL;
+ if (strcmp(method, "MOVE") == 0)
+ return M_MOVE;
+ break;
+ case 'O':
+ if (strcmp(method, "OPTIONS") == 0)
+ return M_OPTIONS;
+ break;
+ case 'T':
+ if (strcmp(method, "TRACE") == 0)
+ return M_TRACE;
+ break;
+ case 'L':
+ if (strcmp(method, "LOCK") == 0)
+ return M_LOCK;
+ break;
+ case 'U':
+ if (strcmp(method, "UNLOCK") == 0)
+ return M_UNLOCK;
+ break;
+ }
+ return M_INVALID;
+}
+
+/* Get a line of protocol input, including any continuation lines
+ * caused by MIME folding (or broken clients) if fold != 0, and place it
+ * in the buffer s, of size n bytes, without the ending newline.
+ *
+ * Returns -1 on error, or the length of s.
+ *
+ * Note: Because bgets uses 1 char for newline and 1 char for NUL,
+ * the most we can get is (n - 2) actual characters if it
+ * was ended by a newline, or (n - 1) characters if the line
+ * length exceeded (n - 1). So, if the result == (n - 1),
+ * then the actual input line exceeded the buffer length,
+ * and it would be a good idea for the caller to puke 400 or 414.
+ */
+static int getline(char *s, int n, BUFF *in, int fold)
+{
+ char *pos, next;
+ int retval;
+ int total = 0;
+
+ pos = s;
+
+ do {
+ retval = ap_bgets(pos, n, in); /* retval == -1 if error, 0 if EOF */
+
+ if (retval <= 0)
+ return ((retval < 0) && (total == 0)) ? -1 : total;
+
+ /* retval is the number of characters read, not including NUL */
+
+ n -= retval; /* Keep track of how much of s is full */
+ pos += (retval - 1); /* and where s ends */
+ total += retval; /* and how long s has become */
+
+ if (*pos == '\n') { /* Did we get a full line of input? */
+ /*
+ * Trim any extra trailing spaces or tabs except for the first
+ * space or tab at the beginning of a blank string. This makes
+ * it much easier to check field values for exact matches, and
+ * saves memory as well. Terminate string at end of line.
+ */
+ while (pos > (s + 1) && (*(pos - 1) == ' ' || *(pos - 1) == '\t')) {
+ --pos; /* trim extra trailing spaces or tabs */
+ --total; /* but not one at the beginning of line */
+ ++n;
+ }
+ *pos = '\0';
+ --total;
+ ++n;
+ }
+ else
+ return total; /* if not, input line exceeded buffer size */
+
+ /* Continue appending if line folding is desired and
+ * the last line was not empty and we have room in the buffer and
+ * the next line begins with a continuation character.
+ */
+ } while (fold && (retval != 1) && (n > 1)
+ && (ap_blookc(&next, in) == 1)
+ && ((next == ' ') || (next == '\t')));
+
+ return total;
+}
+
+/* parse_uri: break apart the uri
+ * Side Effects:
+ * - sets r->args to rest after '?' (or NULL if no '?')
+ * - sets r->uri to request uri (without r->args part)
+ * - sets r->hostname (if not set already) from request (scheme://host:port)
+ */
+CORE_EXPORT(void) ap_parse_uri(request_rec *r, const char *uri)
+{
+ int status = HTTP_OK;
+
+ r->unparsed_uri = ap_pstrdup(r->pool, uri);
+
+ if (r->method_number == M_CONNECT) {
+ status = ap_parse_hostinfo_components(r->pool, uri, &r->parsed_uri);
+ } else {
+ /* Simple syntax Errors in URLs are trapped by parse_uri_components(). */
+ status = ap_parse_uri_components(r->pool, uri, &r->parsed_uri);
+ }
+
+ if (ap_is_HTTP_SUCCESS(status)) {
+ /* if it has a scheme we may need to do absoluteURI vhost stuff */
+ if (r->parsed_uri.scheme
+ && !strcasecmp(r->parsed_uri.scheme, ap_http_method(r))) {
+ r->hostname = r->parsed_uri.hostname;
+ } else if (r->method_number == M_CONNECT) {
+ r->hostname = r->parsed_uri.hostname;
+ }
+ r->args = r->parsed_uri.query;
+ r->uri = r->parsed_uri.path ? r->parsed_uri.path
+ : ap_pstrdup(r->pool, "/");
+#if defined(OS2) || defined(WIN32)
+ /* Handle path translations for OS/2 and plug security hole.
+ * This will prevent "http://www.wherever.com/..\..\/" from
+ * returning a directory for the root drive.
+ */
+ {
+ char *x;
+
+ for (x = r->uri; (x = strchr(x, '\\')) != NULL; )
+ *x = '/';
+ }
+#endif /* OS2 || WIN32 */
+ }
+ else {
+ r->args = NULL;
+ r->hostname = NULL;
+ r->status = status; /* set error status */
+ r->uri = ap_pstrdup(r->pool, uri);
+ }
+}
+
+static int read_request_line(request_rec *r)
+{
+ char l[DEFAULT_LIMIT_REQUEST_LINE + 2]; /* getline's two extra for \n\0 */
+ const char *ll = l;
+ const char *uri;
+ conn_rec *conn = r->connection;
+ int major = 1, minor = 0; /* Assume HTTP/1.0 if non-"HTTP" protocol */
+ int len;
+
+ /* Read past empty lines until we get a real request line,
+ * a read error, the connection closes (EOF), or we timeout.
+ *
+ * We skip empty lines because browsers have to tack a CRLF on to the end
+ * of POSTs to support old CERN webservers. But note that we may not
+ * have flushed any previous response completely to the client yet.
+ * We delay the flush as long as possible so that we can improve
+ * performance for clients that are pipelining requests. If a request
+ * is pipelined then we won't block during the (implicit) read() below.
+ * If the requests aren't pipelined, then the client is still waiting
+ * for the final buffer flush from us, and we will block in the implicit
+ * read(). B_SAFEREAD ensures that the BUFF layer flushes if it will
+ * have to block during a read.
+ */
+ ap_bsetflag(conn->client, B_SAFEREAD, 1);
+ while ((len = getline(l, sizeof(l), conn->client, 0)) <= 0) {
+ if ((len < 0) || ap_bgetflag(conn->client, B_EOF)) {
+ ap_bsetflag(conn->client, B_SAFEREAD, 0);
+ /* this is a hack to make sure that request time is set,
+ * it's not perfect, but it's better than nothing
+ */
+ r->request_time = time(0);
+ return 0;
+ }
+ }
+ /* we've probably got something to do, ignore graceful restart requests */
+#ifdef SIGUSR1
+ signal(SIGUSR1, SIG_IGN);
+#endif
+
+ ap_bsetflag(conn->client, B_SAFEREAD, 0);
+
+ r->request_time = time(NULL);
+ r->the_request = ap_pstrdup(r->pool, l);
+ r->method = ap_getword_white(r->pool, &ll);
+ uri = ap_getword_white(r->pool, &ll);
+
+ /* Provide quick information about the request method as soon as known */
+
+ r->method_number = ap_method_number_of(r->method);
+ if (r->method_number == M_GET && r->method[0] == 'H') {
+ r->header_only = 1;
+ }
+
+ ap_parse_uri(r, uri);
+
+ /* getline returns (size of max buffer - 1) if it fills up the
+ * buffer before finding the end-of-line. This is only going to
+ * happen if it exceeds the configured limit for a request-line.
+ */
+ if (len > r->server->limit_req_line) {
+ r->status = HTTP_REQUEST_URI_TOO_LARGE;
+ r->proto_num = HTTP_VERSION(1,0);
+ r->protocol = ap_pstrdup(r->pool, "HTTP/1.0");
+ return 0;
+ }
+
+ r->assbackwards = (ll[0] == '\0');
+ r->protocol = ap_pstrdup(r->pool, ll[0] ? ll : "HTTP/0.9");
+
+ if (2 == sscanf(r->protocol, "HTTP/%u.%u", &major, &minor)
+ && minor < HTTP_VERSION(1,0)) /* don't allow HTTP/0.1000 */
+ r->proto_num = HTTP_VERSION(major, minor);
+ else
+ r->proto_num = HTTP_VERSION(1,0);
+
+ return 1;
+}
+
+static void get_mime_headers(request_rec *r)
+{
+ char field[DEFAULT_LIMIT_REQUEST_FIELDSIZE + 2]; /* getline's two extra */
+ conn_rec *c = r->connection;
+ char *value;
+ char *copy;
+ int len;
+ unsigned int fields_read = 0;
+ table *tmp_headers;
+
+ /* We'll use ap_overlap_tables later to merge these into r->headers_in. */
+ tmp_headers = ap_make_table(r->pool, 50);
+
+ /*
+ * Read header lines until we get the empty separator line, a read error,
+ * the connection closes (EOF), reach the server limit, or we timeout.
+ */
+ while ((len = getline(field, sizeof(field), c->client, 1)) > 0) {
+
+ if (r->server->limit_req_fields &&
+ (++fields_read > r->server->limit_req_fields)) {
+ r->status = HTTP_BAD_REQUEST;
+ ap_table_setn(r->notes, "error-notes",
+ "The number of request header fields exceeds "
+ "this server's limit.\n");
+ return;
+ }
+ /* getline returns (size of max buffer - 1) if it fills up the
+ * buffer before finding the end-of-line. This is only going to
+ * happen if it exceeds the configured limit for a field size.
+ */
+ if (len > r->server->limit_req_fieldsize) {
+ r->status = HTTP_BAD_REQUEST;
+ ap_table_setn(r->notes, "error-notes", ap_pstrcat(r->pool,
+ "Size of a request header field exceeds server limit. \n"
+ " \n", field, " \n", NULL));
+ return;
+ }
+ copy = ap_palloc(r->pool, len + 1);
+ memcpy(copy, field, len + 1);
+
+ if (!(value = strchr(copy, ':'))) { /* Find the colon separator */
+ r->status = HTTP_BAD_REQUEST; /* or abort the bad request */
+ ap_table_setn(r->notes, "error-notes", ap_pstrcat(r->pool,
+ "Request header field is missing colon separator.\n"
+ " \n", copy, " \n", NULL));
+ return;
+ }
+
+ *value = '\0';
+ ++value;
+ while (*value == ' ' || *value == '\t')
+ ++value; /* Skip to start of value */
+
+ ap_table_addn(tmp_headers, copy, value);
+ }
+
+ ap_overlap_tables(r->headers_in, tmp_headers, AP_OVERLAP_TABLES_MERGE);
+}
+
+request_rec *ap_read_request(conn_rec *conn)
+{
+ request_rec *r;
+ pool *p;
+ const char *expect;
+ int access_status;
+
+ p = ap_make_sub_pool(conn->pool);
+ r = ap_pcalloc(p, sizeof(request_rec));
+ r->pool = p;
+ r->connection = conn;
+ conn->server = conn->base_server;
+ r->server = conn->server;
+
+ conn->keptalive = conn->keepalive == 1;
+ conn->keepalive = 0;
+
+ conn->user = NULL;
+ conn->ap_auth_type = NULL;
+
+ r->headers_in = ap_make_table(r->pool, 50);
+ r->subprocess_env = ap_make_table(r->pool, 50);
+ r->headers_out = ap_make_table(r->pool, 12);
+ r->err_headers_out = ap_make_table(r->pool, 5);
+ r->notes = ap_make_table(r->pool, 5);
+
+ r->request_config = ap_create_request_config(r->pool);
+ r->per_dir_config = r->server->lookup_defaults;
+
+ r->sent_bodyct = 0; /* bytect isn't for body */
+
+ r->read_length = 0;
+ r->read_body = REQUEST_NO_BODY;
+
+ r->status = HTTP_REQUEST_TIME_OUT; /* Until we get a request */
+ r->the_request = NULL;
+
+#ifdef CHARSET_EBCDIC
+ ap_bsetflag(r->connection->client, B_ASCII2EBCDIC|B_EBCDIC2ASCII, 1);
+#endif
+
+ /* Get the request... */
+
+ ap_keepalive_timeout("read request line", r);
+ if (!read_request_line(r)) {
+ ap_kill_timeout(r);
+ if (r->status == HTTP_REQUEST_URI_TOO_LARGE) {
+
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "request failed: URI too long");
+ ap_send_error_response(r, 0);
+ ap_log_transaction(r);
+ return r;
+ }
+ return NULL;
+ }
+ if (!r->assbackwards) {
+ ap_hard_timeout("read request headers", r);
+ get_mime_headers(r);
+ ap_kill_timeout(r);
+ if (r->status != HTTP_REQUEST_TIME_OUT) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "request failed: error reading the headers");
+ ap_send_error_response(r, 0);
+ ap_log_transaction(r);
+ return r;
+ }
+ }
+ else {
+ ap_kill_timeout(r);
+
+ if (r->header_only) {
+ /*
+ * Client asked for headers only with HTTP/0.9, which doesn't send
+ * headers! Have to dink things just to make sure the error message
+ * comes through...
+ */
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "client sent invalid HTTP/0.9 request: HEAD %s",
+ r->uri);
+ r->header_only = 0;
+ r->status = HTTP_BAD_REQUEST;
+ ap_send_error_response(r, 0);
+ ap_log_transaction(r);
+ return r;
+ }
+ }
+
+ r->status = HTTP_OK; /* Until further notice. */
+
+ /* update what we think the virtual host is based on the headers we've
+ * now read
+ */
+ ap_update_vhost_from_headers(r);
+
+ /* we may have switched to another server */
+ r->per_dir_config = r->server->lookup_defaults;
+
+ conn->keptalive = 0; /* We now have a request to play with */
+
+ if ((!r->hostname && (r->proto_num >= HTTP_VERSION(1,1))) ||
+ ((r->proto_num == HTTP_VERSION(1,1)) &&
+ !ap_table_get(r->headers_in, "Host"))) {
+ /*
+ * Client sent us an HTTP/1.1 or later request without telling us the
+ * hostname, either with a full URL or a Host: header. We therefore
+ * need to (as per the 1.1 spec) send an error. As a special case,
+ * HTTP/1.1 mentions twice (S9, S14.23) that a request MUST contain
+ * a Host: header, and the server MUST respond with 400 if it doesn't.
+ */
+ r->status = HTTP_BAD_REQUEST;
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "client sent HTTP/1.1 request without hostname "
+ "(see RFC2068 section 9, and 14.23): %s", r->uri);
+ ap_send_error_response(r, 0);
+ ap_log_transaction(r);
+ return r;
+ }
+ if (((expect = ap_table_get(r->headers_in, "Expect")) != NULL) &&
+ (expect[0] != '\0')) {
+ /*
+ * The Expect header field was added to HTTP/1.1 after RFC 2068
+ * as a means to signal when a 100 response is desired and,
+ * unfortunately, to signal a poor man's mandatory extension that
+ * the server must understand or return 417 Expectation Failed.
+ */
+ if (strcasecmp(expect, "100-continue") == 0) {
+ r->expecting_100 = 1;
+ }
+ else {
+ r->status = HTTP_EXPECTATION_FAILED;
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, r,
+ "client sent an unrecognized expectation value of "
+ "Expect: %s", expect);
+ ap_send_error_response(r, 0);
+ (void) ap_discard_request_body(r);
+ ap_log_transaction(r);
+ return r;
+ }
+ }
+
+ if ((access_status = ap_run_post_read_request(r))) {
+ ap_die(access_status, r);
+ ap_log_transaction(r);
+ return NULL;
+ }
+
+ return r;
+}
+
+/*
+ * A couple of other functions which initialize some of the fields of
+ * a request structure, as appropriate for adjuncts of one kind or another
+ * to a request in progress. Best here, rather than elsewhere, since
+ * *someone* has to set the protocol-specific fields...
+ */
+
+void ap_set_sub_req_protocol(request_rec *rnew, const request_rec *r)
+{
+ rnew->the_request = r->the_request; /* Keep original request-line */
+
+ rnew->assbackwards = 1; /* Don't send headers from this. */
+ rnew->no_local_copy = 1; /* Don't try to send USE_LOCAL_COPY for a
+ * fragment. */
+ rnew->method = "GET";
+ rnew->method_number = M_GET;
+ rnew->protocol = "INCLUDED";
+
+ rnew->status = HTTP_OK;
+
+ rnew->headers_in = r->headers_in;
+ rnew->subprocess_env = ap_copy_table(rnew->pool, r->subprocess_env);
+ rnew->headers_out = ap_make_table(rnew->pool, 5);
+ rnew->err_headers_out = ap_make_table(rnew->pool, 5);
+ rnew->notes = ap_make_table(rnew->pool, 5);
+
+ rnew->expecting_100 = r->expecting_100;
+ rnew->read_length = r->read_length;
+ rnew->read_body = REQUEST_NO_BODY;
+
+ rnew->main = (request_rec *) r;
+}
+
+void ap_finalize_sub_req_protocol(request_rec *sub)
+{
+ SET_BYTES_SENT(sub->main);
+}
+
+/*
+ * Support for the Basic authentication protocol, and a bit for Digest.
+ */
+
+API_EXPORT(void) ap_note_auth_failure(request_rec *r)
+{
+ if (!strcasecmp(ap_auth_type(r), "Basic"))
+ ap_note_basic_auth_failure(r);
+ else if (!strcasecmp(ap_auth_type(r), "Digest"))
+ ap_note_digest_auth_failure(r);
+}
+
+API_EXPORT(void) ap_note_basic_auth_failure(request_rec *r)
+{
+ if (strcasecmp(ap_auth_type(r), "Basic"))
+ ap_note_auth_failure(r);
+ else
+ ap_table_setn(r->err_headers_out,
+ r->proxyreq ? "Proxy-Authenticate" : "WWW-Authenticate",
+ ap_pstrcat(r->pool, "Basic realm=\"", ap_auth_name(r), "\"",
+ NULL));
+}
+
+API_EXPORT(void) ap_note_digest_auth_failure(request_rec *r)
+{
+ ap_table_setn(r->err_headers_out,
+ r->proxyreq ? "Proxy-Authenticate" : "WWW-Authenticate",
+ ap_psprintf(r->pool, "Digest realm=\"%s\", nonce=\"%lu\"",
+ ap_auth_name(r), r->request_time));
+}
+
+API_EXPORT(int) ap_get_basic_auth_pw(request_rec *r, const char **pw)
+{
+ const char *auth_line = ap_table_get(r->headers_in,
+ r->proxyreq ? "Proxy-Authorization"
+ : "Authorization");
+ const char *t;
+
+ if (!(t = ap_auth_type(r)) || strcasecmp(t, "Basic"))
+ return DECLINED;
+
+ if (!ap_auth_name(r)) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR,
+ r, "need AuthName: %s", r->uri);
+ return SERVER_ERROR;
+ }
+
+ if (!auth_line) {
+ ap_note_basic_auth_failure(r);
+ return AUTH_REQUIRED;
+ }
+
+ if (strcasecmp(ap_getword(r->pool, &auth_line, ' '), "Basic")) {
+ /* Client tried to authenticate using wrong auth scheme */
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "client used wrong authentication scheme: %s", r->uri);
+ ap_note_basic_auth_failure(r);
+ return AUTH_REQUIRED;
+ }
+
+ /* CHARSET_EBCDIC Issue's here ?!? Compare with 32/9 instead
+ * as we are operating on an octed stream ?
+ */
+ while (*auth_line== ' ' || *auth_line== '\t')
+ auth_line++;
+
+ t = ap_pbase64decode(r->pool, auth_line);
+ /* Note that this allocation has to be made from r->connection->pool
+ * because it has the lifetime of the connection. The other allocations
+ * are temporary and can be tossed away any time.
+ */
+ r->connection->user = ap_getword_nulls (r->connection->pool, &t, ':');
+ r->connection->ap_auth_type = "Basic";
+
+ *pw = t;
+
+ return OK;
+}
+
+/* New Apache routine to map status codes into array indicies
+ * e.g. 100 -> 0, 101 -> 1, 200 -> 2 ...
+ * The number of status lines must equal the value of RESPONSE_CODES (httpd.h)
+ * and must be listed in order.
+ */
+
+#ifdef UTS21
+/* The second const triggers an assembler bug on UTS 2.1.
+ * Another workaround is to move some code out of this file into another,
+ * but this is easier. Dave Dykstra, 3/31/99
+ */
+static const char * status_lines[RESPONSE_CODES] =
+#else
+static const char * const status_lines[RESPONSE_CODES] =
+#endif
+{
+ "100 Continue",
+ "101 Switching Protocols",
+ "102 Processing",
+#define LEVEL_200 3
+ "200 OK",
+ "201 Created",
+ "202 Accepted",
+ "203 Non-Authoritative Information",
+ "204 No Content",
+ "205 Reset Content",
+ "206 Partial Content",
+ "207 Multi-Status",
+#define LEVEL_300 11
+ "300 Multiple Choices",
+ "301 Moved Permanently",
+ "302 Found",
+ "303 See Other",
+ "304 Not Modified",
+ "305 Use Proxy",
+ "306 unused",
+ "307 Temporary Redirect",
+#define LEVEL_400 19
+ "400 Bad Request",
+ "401 Authorization Required",
+ "402 Payment Required",
+ "403 Forbidden",
+ "404 Not Found",
+ "405 Method Not Allowed",
+ "406 Not Acceptable",
+ "407 Proxy Authentication Required",
+ "408 Request Time-out",
+ "409 Conflict",
+ "410 Gone",
+ "411 Length Required",
+ "412 Precondition Failed",
+ "413 Request Entity Too Large",
+ "414 Request-URI Too Large",
+ "415 Unsupported Media Type",
+ "416 Requested Range Not Satisfiable",
+ "417 Expectation Failed",
+ "418 unused",
+ "419 unused",
+ "420 unused",
+ "421 unused",
+ "422 Unprocessable Entity",
+ "423 Locked",
+ "424 Failed Dependency",
+#define LEVEL_500 44
+ "500 Internal Server Error",
+ "501 Method Not Implemented",
+ "502 Bad Gateway",
+ "503 Service Temporarily Unavailable",
+ "504 Gateway Time-out",
+ "505 HTTP Version Not Supported",
+ "506 Variant Also Negotiates",
+ "507 Insufficient Storage",
+ "508 unused",
+ "509 unused",
+ "510 Not Extended"
+};
+
+/* The index is found by its offset from the x00 code of each level.
+ * Although this is fast, it will need to be replaced if some nutcase
+ * decides to define a high-numbered code before the lower numbers.
+ * If that sad event occurs, replace the code below with a linear search
+ * from status_lines[shortcut[i]] to status_lines[shortcut[i+1]-1];
+ */
+API_EXPORT(int) ap_index_of_response(int status)
+{
+ static int shortcut[6] = {0, LEVEL_200, LEVEL_300, LEVEL_400,
+ LEVEL_500, RESPONSE_CODES};
+ int i, pos;
+
+ if (status < 100) /* Below 100 is illegal for HTTP status */
+ return LEVEL_500;
+
+ for (i = 0; i < 5; i++) {
+ status -= 100;
+ if (status < 100) {
+ pos = (status + shortcut[i]);
+ if (pos < shortcut[i + 1])
+ return pos;
+ else
+ return LEVEL_500; /* status unknown (falls in gap) */
+ }
+ }
+ return LEVEL_500; /* 600 or above is also illegal */
+}
+
+/* Send a single HTTP header field to the client. Note that this function
+ * is used in calls to table_do(), so their interfaces are co-dependent.
+ * In other words, don't change this one without checking table_do in alloc.c.
+ * It returns true unless there was a write error of some kind.
+ */
+API_EXPORT_NONSTD(int) ap_send_header_field(request_rec *r,
+ const char *fieldname, const char *fieldval)
+{
+ return (0 < ap_rvputs(r, fieldname, ": ", fieldval, "\015\012", NULL));
+}
+
+API_EXPORT(void) ap_basic_http_header(request_rec *r)
+{
+ char *protocol;
+#ifdef CHARSET_EBCDIC
+ int convert = ap_bgetflag(r->connection->client, B_EBCDIC2ASCII);
+#endif /*CHARSET_EBCDIC*/
+
+ if (r->assbackwards)
+ return;
+
+ if (!r->status_line)
+ r->status_line = status_lines[ap_index_of_response(r->status)];
+
+ /* mod_proxy is only HTTP/1.0, so avoid sending HTTP/1.1 error response;
+ * kluge around broken browsers when indicated by force-response-1.0
+ */
+ if (r->proxyreq
+ || (r->proto_num == HTTP_VERSION(1,0)
+ && ap_table_get(r->subprocess_env, "force-response-1.0"))) {
+
+ protocol = "HTTP/1.0";
+ r->connection->keepalive = -1;
+ }
+ else
+ protocol = SERVER_PROTOCOL;
+
+#ifdef CHARSET_EBCDIC
+ ap_bsetflag(r->connection->client, B_EBCDIC2ASCII, 1);
+#endif /*CHARSET_EBCDIC*/
+
+ /* Output the HTTP/1.x Status-Line and the Date and Server fields */
+
+ ap_rvputs(r, protocol, " ", r->status_line, "\015\012", NULL);
+
+ ap_send_header_field(r, "Date", ap_gm_timestr_822(r->pool, r->request_time));
+ ap_send_header_field(r, "Server", ap_get_server_version());
+
+ ap_table_unset(r->headers_out, "Date"); /* Avoid bogosity */
+ ap_table_unset(r->headers_out, "Server");
+#ifdef CHARSET_EBCDIC
+ if (!convert)
+ ap_bsetflag(r->connection->client, B_EBCDIC2ASCII, convert);
+#endif /*CHARSET_EBCDIC*/
+}
+
+/* Navigator versions 2.x, 3.x and 4.0 betas up to and including 4.0b2
+ * have a header parsing bug. If the terminating \r\n occur starting
+ * at offset 256, 257 or 258 of output then it will not properly parse
+ * the headers. Curiously it doesn't exhibit this problem at 512, 513.
+ * We are guessing that this is because their initial read of a new request
+ * uses a 256 byte buffer, and subsequent reads use a larger buffer.
+ * So the problem might exist at different offsets as well.
+ *
+ * This should also work on keepalive connections assuming they use the
+ * same small buffer for the first read of each new request.
+ *
+ * At any rate, we check the bytes written so far and, if we are about to
+ * tickle the bug, we instead insert a bogus padding header. Since the bug
+ * manifests as a broken image in Navigator, users blame the server. :(
+ * It is more expensive to check the User-Agent than it is to just add the
+ * bytes, so we haven't used the BrowserMatch feature here.
+ */
+static void terminate_header(BUFF *client)
+{
+ long int bs;
+
+ ap_bgetopt(client, BO_BYTECT, &bs);
+ if (bs >= 255 && bs <= 257)
+ ap_bputs("X-Pad: avoid browser bug\015\012", client);
+
+ ap_bputs("\015\012", client); /* Send the terminating empty line */
+}
+
+/* Build the Allow field-value from the request handler method mask.
+ * Note that we always allow TRACE, since it is handled below.
+ */
+static char *make_allow(request_rec *r)
+{
+ return 2 + ap_pstrcat(r->pool,
+ (r->allowed & (1 << M_GET)) ? ", GET, HEAD" : "",
+ (r->allowed & (1 << M_POST)) ? ", POST" : "",
+ (r->allowed & (1 << M_PUT)) ? ", PUT" : "",
+ (r->allowed & (1 << M_DELETE)) ? ", DELETE" : "",
+ (r->allowed & (1 << M_CONNECT)) ? ", CONNECT" : "",
+ (r->allowed & (1 << M_OPTIONS)) ? ", OPTIONS" : "",
+ (r->allowed & (1 << M_PATCH)) ? ", PATCH" : "",
+ (r->allowed & (1 << M_PROPFIND)) ? ", PROPFIND" : "",
+ (r->allowed & (1 << M_PROPPATCH)) ? ", PROPPATCH" : "",
+ (r->allowed & (1 << M_MKCOL)) ? ", MKCOL" : "",
+ (r->allowed & (1 << M_COPY)) ? ", COPY" : "",
+ (r->allowed & (1 << M_MOVE)) ? ", MOVE" : "",
+ (r->allowed & (1 << M_LOCK)) ? ", LOCK" : "",
+ (r->allowed & (1 << M_UNLOCK)) ? ", UNLOCK" : "",
+ ", TRACE",
+ NULL);
+}
+
+API_EXPORT(int) ap_send_http_trace(request_rec *r)
+{
+ int rv;
+
+ /* Get the original request */
+ while (r->prev)
+ r = r->prev;
+
+ if ((rv = ap_setup_client_block(r, REQUEST_NO_BODY)))
+ return rv;
+
+ ap_hard_timeout("send TRACE", r);
+
+ r->content_type = "message/http";
+ ap_send_http_header(r);
+
+ /* Now we recreate the request, and echo it back */
+
+ ap_rvputs(r, r->the_request, "\015\012", NULL);
+
+ ap_table_do((int (*) (void *, const char *, const char *))
+ ap_send_header_field, (void *) r, r->headers_in, NULL);
+ ap_rputs("\015\012", r);
+
+ ap_kill_timeout(r);
+ return OK;
+}
+
+int ap_send_http_options(request_rec *r)
+{
+ const long int zero = 0L;
+
+ if (r->assbackwards)
+ return DECLINED;
+
+ ap_hard_timeout("send OPTIONS", r);
+
+ ap_basic_http_header(r);
+
+ ap_table_setn(r->headers_out, "Content-Length", "0");
+ ap_table_setn(r->headers_out, "Allow", make_allow(r));
+ ap_set_keepalive(r);
+
+ ap_table_do((int (*) (void *, const char *, const char *)) ap_send_header_field,
+ (void *) r, r->headers_out, NULL);
+
+ terminate_header(r->connection->client);
+
+ ap_kill_timeout(r);
+ ap_bsetopt(r->connection->client, BO_BYTECT, &zero);
+
+ return OK;
+}
+
+/*
+ * Here we try to be compatible with clients that want multipart/x-byteranges
+ * instead of multipart/byteranges (also see above), as per HTTP/1.1. We
+ * look for the Request-Range header (e.g. Netscape 2 and 3) as an indication
+ * that the browser supports an older protocol. We also check User-Agent
+ * for Microsoft Internet Explorer 3, which needs this as well.
+ */
+static int use_range_x(request_rec *r)
+{
+ const char *ua;
+ return (ap_table_get(r->headers_in, "Request-Range") ||
+ ((ua = ap_table_get(r->headers_in, "User-Agent"))
+ && strstr(ua, "MSIE 3")));
+}
+
+/* This routine is called by ap_table_do and merges all instances of
+ * the passed field values into a single array that will be further
+ * processed by some later routine. Originally intended to help split
+ * and recombine multiple Vary fields, though it is generic to any field
+ * consisting of comma/space-separated tokens.
+ */
+static int uniq_field_values(void *d, const char *key, const char *val)
+{
+ array_header *values;
+ char *start;
+ char *e;
+ char **strpp;
+ int i;
+
+ values = (array_header *)d;
+
+ e = ap_pstrdup(values->pool, val);
+
+ do {
+ /* Find a non-empty fieldname */
+
+ while (*e == ',' || ap_isspace(*e)) {
+ ++e;
+ }
+ if (*e == '\0') {
+ break;
+ }
+ start = e;
+ while (*e != '\0' && *e != ',' && !ap_isspace(*e)) {
+ ++e;
+ }
+ if (*e != '\0') {
+ *e++ = '\0';
+ }
+
+ /* Now add it to values if it isn't already represented.
+ * Could be replaced by a ap_array_strcasecmp() if we had one.
+ */
+ for (i = 0, strpp = (char **) values->elts; i < values->nelts;
+ ++i, ++strpp) {
+ if (*strpp && strcasecmp(*strpp, start) == 0) {
+ break;
+ }
+ }
+ if (i == values->nelts) { /* if not found */
+ *(char **)ap_push_array(values) = start;
+ }
+ } while (*e != '\0');
+
+ return 1;
+}
+
+/*
+ * Since some clients choke violently on multiple Vary fields, or
+ * Vary fields with duplicate tokens, combine any multiples and remove
+ * any duplicates.
+ */
+static void fixup_vary(request_rec *r)
+{
+ array_header *varies;
+
+ varies = ap_make_array(r->pool, 5, sizeof(char *));
+
+ /* Extract all Vary fields from the headers_out, separate each into
+ * its comma-separated fieldname values, and then add them to varies
+ * if not already present in the array.
+ */
+ ap_table_do((int (*)(void *, const char *, const char *))uniq_field_values,
+ (void *) varies, r->headers_out, "Vary", NULL);
+
+ /* If we found any, replace old Vary fields with unique-ified value */
+
+ if (varies->nelts > 0) {
+ ap_table_setn(r->headers_out, "Vary",
+ ap_array_pstrcat(r->pool, varies, ','));
+ }
+}
+
+API_EXPORT(void) ap_send_http_header(request_rec *r)
+{
+ int i;
+ const long int zero = 0L;
+#ifdef CHARSET_EBCDIC
+ int convert = ap_bgetflag(r->connection->client, B_EBCDIC2ASCII);
+#endif /*CHARSET_EBCDIC*/
+
+ if (r->assbackwards) {
+ if (!r->main)
+ ap_bsetopt(r->connection->client, BO_BYTECT, &zero);
+ r->sent_bodyct = 1;
+ return;
+ }
+
+ /*
+ * Now that we are ready to send a response, we need to combine the two
+ * header field tables into a single table. If we don't do this, our
+ * later attempts to set or unset a given fieldname might be bypassed.
+ */
+ if (!ap_is_empty_table(r->err_headers_out))
+ r->headers_out = ap_overlay_tables(r->pool, r->err_headers_out,
+ r->headers_out);
+
+ /*
+ * Remove the 'Vary' header field if the client can't handle it.
+ * Since this will have nasty effects on HTTP/1.1 caches, force
+ * the response into HTTP/1.0 mode.
+ */
+ if (ap_table_get(r->subprocess_env, "force-no-vary") != NULL) {
+ ap_table_unset(r->headers_out, "Vary");
+ r->proto_num = HTTP_VERSION(1,0);
+ ap_table_set(r->subprocess_env, "force-response-1.0", "1");
+ }
+ else {
+ fixup_vary(r);
+ }
+
+ ap_hard_timeout("send headers", r);
+
+ ap_basic_http_header(r);
+
+#ifdef CHARSET_EBCDIC
+ ap_bsetflag(r->connection->client, B_EBCDIC2ASCII, 1);
+#endif /*CHARSET_EBCDIC*/
+
+ ap_set_keepalive(r);
+
+ if (r->chunked) {
+ ap_table_mergen(r->headers_out, "Transfer-Encoding", "chunked");
+ ap_table_unset(r->headers_out, "Content-Length");
+ }
+
+ if (r->byterange > 1)
+ ap_table_setn(r->headers_out, "Content-Type",
+ ap_pstrcat(r->pool, "multipart", use_range_x(r) ? "/x-" : "/",
+ "byteranges; boundary=", r->boundary, NULL));
+ else if (r->content_type)
+ ap_table_setn(r->headers_out, "Content-Type", r->content_type);
+ else
+ ap_table_setn(r->headers_out, "Content-Type", ap_default_type(r));
+
+ if (r->content_encoding)
+ ap_table_setn(r->headers_out, "Content-Encoding", r->content_encoding);
+
+ if (r->content_languages && r->content_languages->nelts) {
+ for (i = 0; i < r->content_languages->nelts; ++i) {
+ ap_table_mergen(r->headers_out, "Content-Language",
+ ((char **) (r->content_languages->elts))[i]);
+ }
+ }
+ else if (r->content_language)
+ ap_table_setn(r->headers_out, "Content-Language", r->content_language);
+
+ /*
+ * Control cachability for non-cachable responses if not already set by
+ * some other part of the server configuration.
+ */
+ if (r->no_cache && !ap_table_get(r->headers_out, "Expires"))
+ ap_table_addn(r->headers_out, "Expires",
+ ap_gm_timestr_822(r->pool, r->request_time));
+
+ /* Send the entire table of header fields, terminated by an empty line. */
+
+ ap_table_do((int (*) (void *, const char *, const char *)) ap_send_header_field,
+ (void *) r, r->headers_out, NULL);
+
+ terminate_header(r->connection->client);
+
+ ap_kill_timeout(r);
+
+ ap_bsetopt(r->connection->client, BO_BYTECT, &zero);
+ r->sent_bodyct = 1; /* Whatever follows is real body stuff... */
+
+ /* Set buffer flags for the body */
+ if (r->chunked)
+ ap_bsetflag(r->connection->client, B_CHUNK, 1);
+#ifdef CHARSET_EBCDIC
+ if (!convert)
+ ap_bsetflag(r->connection->client, B_EBCDIC2ASCII, convert);
+#endif /*CHARSET_EBCDIC*/
+}
+
+/* finalize_request_protocol is called at completion of sending the
+ * response. It's sole purpose is to send the terminating protocol
+ * information for any wrappers around the response message body
+ * (i.e., transfer encodings). It should have been named finalize_response.
+ */
+API_EXPORT(void) ap_finalize_request_protocol(request_rec *r)
+{
+ if (r->chunked && !r->connection->aborted) {
+ /*
+ * Turn off chunked encoding --- we can only do this once.
+ */
+ r->chunked = 0;
+ ap_bsetflag(r->connection->client, B_CHUNK, 0);
+
+ ap_soft_timeout("send ending chunk", r);
+ ap_rputs("0\015\012", r);
+ /* If we had footer "headers", we'd send them now */
+ ap_rputs("\015\012", r);
+ ap_kill_timeout(r);
+ }
+}
+
+/* Here we deal with getting the request message body from the client.
+ * Whether or not the request contains a body is signaled by the presence
+ * of a non-zero Content-Length or by a Transfer-Encoding: chunked.
+ *
+ * Note that this is more complicated than it was in Apache 1.1 and prior
+ * versions, because chunked support means that the module does less.
+ *
+ * The proper procedure is this:
+ *
+ * 1. Call setup_client_block() near the beginning of the request
+ * handler. This will set up all the necessary properties, and will
+ * return either OK, or an error code. If the latter, the module should
+ * return that error code. The second parameter selects the policy to
+ * apply if the request message indicates a body, and how a chunked
+ * transfer-coding should be interpreted. Choose one of
+ *
+ * REQUEST_NO_BODY Send 413 error if message has any body
+ * REQUEST_CHUNKED_ERROR Send 411 error if body without Content-Length
+ * REQUEST_CHUNKED_DECHUNK If chunked, remove the chunks for me.
+ * REQUEST_CHUNKED_PASS Pass the chunks to me without removal.
+ *
+ * In order to use the last two options, the caller MUST provide a buffer
+ * large enough to hold a chunk-size line, including any extensions.
+ *
+ * 2. When you are ready to read a body (if any), call should_client_block().
+ * This will tell the module whether or not to read input. If it is 0,
+ * the module should assume that there is no message body to read.
+ * This step also sends a 100 Continue response to HTTP/1.1 clients,
+ * so should not be called until the module is *definitely* ready to
+ * read content. (otherwise, the point of the 100 response is defeated).
+ * Never call this function more than once.
+ *
+ * 3. Finally, call get_client_block in a loop. Pass it a buffer and its size.
+ * It will put data into the buffer (not necessarily a full buffer), and
+ * return the length of the input block. When it is done reading, it will
+ * return 0 if EOF, or -1 if there was an error.
+ * If an error occurs on input, we force an end to keepalive.
+ */
+
+API_EXPORT(int) ap_setup_client_block(request_rec *r, int read_policy)
+{
+ const char *tenc = ap_table_get(r->headers_in, "Transfer-Encoding");
+ const char *lenp = ap_table_get(r->headers_in, "Content-Length");
+ unsigned long max_body;
+
+ r->read_body = read_policy;
+ r->read_chunked = 0;
+ r->remaining = 0;
+
+ if (tenc) {
+ if (strcasecmp(tenc, "chunked")) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Unknown Transfer-Encoding %s", tenc);
+ return HTTP_NOT_IMPLEMENTED;
+ }
+ if (r->read_body == REQUEST_CHUNKED_ERROR) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "chunked Transfer-Encoding forbidden: %s", r->uri);
+ return (lenp) ? HTTP_BAD_REQUEST : HTTP_LENGTH_REQUIRED;
+ }
+
+ r->read_chunked = 1;
+ }
+ else if (lenp) {
+ const char *pos = lenp;
+
+ while (ap_isdigit(*pos) || ap_isspace(*pos))
+ ++pos;
+ if (*pos != '\0') {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Invalid Content-Length %s", lenp);
+ return HTTP_BAD_REQUEST;
+ }
+
+ r->remaining = atol(lenp);
+ }
+
+ if ((r->read_body == REQUEST_NO_BODY) &&
+ (r->read_chunked || (r->remaining > 0))) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "%s with body is not allowed for %s", r->method, r->uri);
+ return HTTP_REQUEST_ENTITY_TOO_LARGE;
+ }
+
+ max_body = ap_get_limit_req_body(r);
+ if (max_body && (r->remaining > max_body)) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Request content-length of %s is larger than the configured "
+ "limit of %lu", lenp, max_body);
+ return HTTP_REQUEST_ENTITY_TOO_LARGE;
+ }
+
+ return OK;
+}
+
+API_EXPORT(int) ap_should_client_block(request_rec *r)
+{
+ /* First check if we have already read the request body */
+
+ if (r->read_length || (!r->read_chunked && (r->remaining <= 0)))
+ return 0;
+
+ if (r->expecting_100 && r->proto_num >= HTTP_VERSION(1,1)) {
+ /* sending 100 Continue interim response */
+ ap_rvputs(r, SERVER_PROTOCOL, " ", status_lines[0], "\015\012\015\012",
+ NULL);
+ ap_rflush(r);
+ }
+
+ return 1;
+}
+
+static long get_chunk_size(char *b)
+{
+ long chunksize = 0;
+
+ while (ap_isxdigit(*b)) {
+ int xvalue = 0;
+
+ if (*b >= '0' && *b <= '9')
+ xvalue = *b - '0';
+ else if (*b >= 'A' && *b <= 'F')
+ xvalue = *b - 'A' + 0xa;
+ else if (*b >= 'a' && *b <= 'f')
+ xvalue = *b - 'a' + 0xa;
+
+ chunksize = (chunksize << 4) | xvalue;
+ ++b;
+ }
+
+ return chunksize;
+}
+
+/* get_client_block is called in a loop to get the request message body.
+ * This is quite simple if the client includes a content-length
+ * (the normal case), but gets messy if the body is chunked. Note that
+ * r->remaining is used to maintain state across calls and that
+ * r->read_length is the total number of bytes given to the caller
+ * across all invocations. It is messy because we have to be careful not
+ * to read past the data provided by the client, since these reads block.
+ * Returns 0 on End-of-body, -1 on error or premature chunk end.
+ *
+ * Reading the chunked encoding requires a buffer size large enough to
+ * hold a chunk-size line, including any extensions. For now, we'll leave
+ * that to the caller, at least until we can come up with a better solution.
+ */
+API_EXPORT(long) ap_get_client_block(request_rec *r, char *buffer, int bufsiz)
+{
+ int c;
+ long len_read, len_to_read;
+ long chunk_start = 0;
+ unsigned long max_body;
+
+ if (!r->read_chunked) { /* Content-length read */
+ len_to_read = (r->remaining > bufsiz) ? bufsiz : r->remaining;
+ len_read = ap_bread(r->connection->client, buffer, len_to_read);
+ if (len_read <= 0) {
+ if (len_read < 0)
+ r->connection->keepalive = -1;
+ return len_read;
+ }
+ r->read_length += len_read;
+ r->remaining -= len_read;
+ return len_read;
+ }
+
+ /*
+ * Handle chunked reading Note: we are careful to shorten the input
+ * bufsiz so that there will always be enough space for us to add a CRLF
+ * (if necessary).
+ */
+ if (r->read_body == REQUEST_CHUNKED_PASS)
+ bufsiz -= 2;
+ if (bufsiz <= 0)
+ return -1; /* Cannot read chunked with a small buffer */
+
+ /* Check to see if we have already read too much request data.
+ * For efficiency reasons, we only check this at the top of each
+ * caller read pass, since the limit exists just to stop infinite
+ * length requests and nobody cares if it goes over by one buffer.
+ */
+ max_body = ap_get_limit_req_body(r);
+ if (max_body && (r->read_length > max_body)) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Chunked request body is larger than the configured limit of %lu",
+ max_body);
+ r->connection->keepalive = -1;
+ return -1;
+ }
+
+ if (r->remaining == 0) { /* Start of new chunk */
+
+ chunk_start = getline(buffer, bufsiz, r->connection->client, 0);
+ if ((chunk_start <= 0) || (chunk_start >= (bufsiz - 1))
+ || !ap_isxdigit(*buffer)) {
+ r->connection->keepalive = -1;
+ return -1;
+ }
+
+ len_to_read = get_chunk_size(buffer);
+
+ if (len_to_read == 0) { /* Last chunk indicated, get footers */
+ if (r->read_body == REQUEST_CHUNKED_DECHUNK) {
+ get_mime_headers(r);
+ ap_snprintf(buffer, bufsiz, "%ld", r->read_length);
+ ap_table_unset(r->headers_in, "Transfer-Encoding");
+ ap_table_setn(r->headers_in, "Content-Length",
+ ap_pstrdup(r->pool, buffer));
+ return 0;
+ }
+ r->remaining = -1; /* Indicate footers in-progress */
+ }
+ else {
+ r->remaining = len_to_read;
+ }
+ if (r->read_body == REQUEST_CHUNKED_PASS) {
+ buffer[chunk_start++] = CR; /* Restore chunk-size line end */
+ buffer[chunk_start++] = LF;
+ buffer += chunk_start; /* and pass line on to caller */
+ bufsiz -= chunk_start;
+ }
+ else {
+ /* REQUEST_CHUNKED_DECHUNK -- do not include the length of the
+ * header in the return value
+ */
+ chunk_start = 0;
+ }
+ }
+ /* When REQUEST_CHUNKED_PASS, we are */
+ if (r->remaining == -1) { /* reading footers until empty line */
+ len_read = chunk_start;
+
+ while ((bufsiz > 1) && ((len_read =
+ getline(buffer, bufsiz, r->connection->client, 1)) > 0)) {
+
+ if (len_read != (bufsiz - 1)) {
+ buffer[len_read++] = CR; /* Restore footer line end */
+ buffer[len_read++] = LF;
+ }
+ chunk_start += len_read;
+ buffer += len_read;
+ bufsiz -= len_read;
+ }
+ if (len_read < 0) {
+ r->connection->keepalive = -1;
+ return -1;
+ }
+
+ if (len_read == 0) { /* Indicates an empty line */
+ buffer[0] = CR;
+ buffer[1] = LF;
+ chunk_start += 2;
+ r->remaining = -2;
+ }
+ r->read_length += chunk_start;
+ return chunk_start;
+ }
+ /* When REQUEST_CHUNKED_PASS, we */
+ if (r->remaining == -2) { /* finished footers when last called */
+ r->remaining = 0; /* so now we must signal EOF */
+ return 0;
+ }
+
+ /* Otherwise, we are in the midst of reading a chunk of data */
+
+ len_to_read = (r->remaining > bufsiz) ? bufsiz : r->remaining;
+
+ len_read = ap_bread(r->connection->client, buffer, len_to_read);
+ if (len_read <= 0) {
+ r->connection->keepalive = -1;
+ return -1;
+ }
+
+ r->remaining -= len_read;
+
+ if (r->remaining == 0) { /* End of chunk, get trailing CRLF */
+ if ((c = ap_bgetc(r->connection->client)) == CR) {
+ c = ap_bgetc(r->connection->client);
+ }
+ if (c != LF) {
+ r->connection->keepalive = -1;
+ return -1;
+ }
+ if (r->read_body == REQUEST_CHUNKED_PASS) {
+ buffer[len_read++] = CR;
+ buffer[len_read++] = LF;
+ }
+ }
+ r->read_length += (chunk_start + len_read);
+
+ return (chunk_start + len_read);
+}
+
+/* In HTTP/1.1, any method can have a body. However, most GET handlers
+ * wouldn't know what to do with a request body if they received one.
+ * This helper routine tests for and reads any message body in the request,
+ * simply discarding whatever it receives. We need to do this because
+ * failing to read the request body would cause it to be interpreted
+ * as the next request on a persistent connection.
+ *
+ * Since we return an error status if the request is malformed, this
+ * routine should be called at the beginning of a no-body handler, e.g.,
+ *
+ * if ((retval = ap_discard_request_body(r)) != OK)
+ * return retval;
+ */
+API_EXPORT(int) ap_discard_request_body(request_rec *r)
+{
+ int rv;
+
+ if ((rv = ap_setup_client_block(r, REQUEST_CHUNKED_PASS)))
+ return rv;
+
+ /* In order to avoid sending 100 Continue when we already know the
+ * final response status, and yet not kill the connection if there is
+ * no request body to be read, we need to duplicate the test from
+ * ap_should_client_block() here negated rather than call it directly.
+ */
+ if ((r->read_length == 0) && (r->read_chunked || (r->remaining > 0))) {
+ char dumpbuf[HUGE_STRING_LEN];
+
+ if (r->expecting_100) {
+ r->connection->keepalive = -1;
+ return OK;
+ }
+ ap_hard_timeout("reading request body", r);
+ while ((rv = ap_get_client_block(r, dumpbuf, HUGE_STRING_LEN)) > 0)
+ continue;
+ ap_kill_timeout(r);
+
+ if (rv < 0)
+ return HTTP_BAD_REQUEST;
+ }
+ return OK;
+}
+
+/*
+ * Send the body of a response to the client.
+ */
+API_EXPORT(long) ap_send_fd(FILE *f, request_rec *r)
+{
+ return ap_send_fd_length(f, r, -1);
+}
+
+API_EXPORT(long) ap_send_fd_length(FILE *f, request_rec *r, long length)
+{
+ char buf[IOBUFSIZE];
+ long total_bytes_sent = 0;
+ register int n, w, o, len;
+
+ if (length == 0)
+ return 0;
+
+ ap_soft_timeout("send body", r);
+
+ while (!r->connection->aborted) {
+ if ((length > 0) && (total_bytes_sent + IOBUFSIZE) > length)
+ len = length - total_bytes_sent;
+ else
+ len = IOBUFSIZE;
+
+ while ((n = fread(buf, sizeof(char), len, f)) < 1
+ && ferror(f) && errno == EINTR && !r->connection->aborted)
+ continue;
+
+ if (n < 1) {
+ break;
+ }
+ o = 0;
+
+ while (n && !r->connection->aborted) {
+ w = ap_bwrite(r->connection->client, &buf[o], n);
+ if (w > 0) {
+ ap_reset_timeout(r); /* reset timeout after successful write */
+ total_bytes_sent += w;
+ n -= w;
+ o += w;
+ }
+ else if (w < 0) {
+ if (!r->connection->aborted) {
+ ap_log_rerror(APLOG_MARK, APLOG_INFO, r,
+ "client stopped connection before send body completed");
+ ap_bsetflag(r->connection->client, B_EOUT, 1);
+ r->connection->aborted = 1;
+ }
+ break;
+ }
+ }
+ }
+
+ ap_kill_timeout(r);
+ SET_BYTES_SENT(r);
+ return total_bytes_sent;
+}
+
+/*
+ * Send the body of a response to the client.
+ */
+API_EXPORT(long) ap_send_fb(BUFF *fb, request_rec *r)
+{
+ return ap_send_fb_length(fb, r, -1);
+}
+
+API_EXPORT(long) ap_send_fb_length(BUFF *fb, request_rec *r, long length)
+{
+ char buf[IOBUFSIZE];
+ long total_bytes_sent = 0;
+ register int n, w, o, len, fd;
+ fd_set fds;
+
+ if (length == 0)
+ return 0;
+
+ /* Make fb unbuffered and non-blocking */
+ ap_bsetflag(fb, B_RD, 0);
+#ifndef TPF
+ ap_bnonblock(fb, B_RD);
+#endif
+ fd = ap_bfileno(fb, B_RD);
+#ifdef CHECK_FD_SETSIZE
+ if (fd >= FD_SETSIZE) {
+ ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, NULL,
+ "send body: filedescriptor (%u) larger than FD_SETSIZE (%u) "
+ "found, you probably need to rebuild Apache with a "
+ "larger FD_SETSIZE", fd, FD_SETSIZE);
+ return 0;
+ }
+#endif
+
+ ap_soft_timeout("send body", r);
+
+ FD_ZERO(&fds);
+ while (!r->connection->aborted) {
+#ifdef NDELAY_PIPE_RETURNS_ZERO
+ /* Contributed by dwd@bell-labs.com for UTS 2.1.2, where the fcntl */
+ /* O_NDELAY flag causes read to return 0 when there's nothing */
+ /* available when reading from a pipe. That makes it tricky */
+ /* to detect end-of-file :-(. This stupid bug is even documented */
+ /* in the read(2) man page where it says that everything but */
+ /* pipes return -1 and EAGAIN. That makes it a feature, right? */
+ int afterselect = 0;
+#endif
+ if ((length > 0) && (total_bytes_sent + IOBUFSIZE) > length)
+ len = length - total_bytes_sent;
+ else
+ len = IOBUFSIZE;
+
+ do {
+ n = ap_bread(fb, buf, len);
+#ifdef NDELAY_PIPE_RETURNS_ZERO
+ if ((n > 0) || (n == 0 && afterselect))
+ break;
+#else
+ if (n >= 0)
+ break;
+#endif
+ if (r->connection->aborted)
+ break;
+ if (n < 0 && errno != EAGAIN)
+ break;
+
+ /* we need to block, so flush the output first */
+ if (ap_bflush(r->connection->client) < 0) {
+ ap_log_rerror(APLOG_MARK, APLOG_INFO, r,
+ "client stopped connection before send body completed");
+ ap_bsetflag(r->connection->client, B_EOUT, 1);
+ r->connection->aborted = 1;
+ break;
+ }
+ FD_SET(fd, &fds);
+ /*
+ * we don't care what select says, we might as well loop back
+ * around and try another read
+ */
+ ap_select(fd + 1, &fds, NULL, NULL, NULL);
+#ifdef NDELAY_PIPE_RETURNS_ZERO
+ afterselect = 1;
+#endif
+ } while (!r->connection->aborted);
+
+ if (n < 1 || r->connection->aborted) {
+ break;
+ }
+ o = 0;
+
+ while (n && !r->connection->aborted) {
+ w = ap_bwrite(r->connection->client, &buf[o], n);
+ if (w > 0) {
+ ap_reset_timeout(r); /* reset timeout after successful write */
+ total_bytes_sent += w;
+ n -= w;
+ o += w;
+ }
+ else if (w < 0) {
+ if (!r->connection->aborted) {
+ ap_log_rerror(APLOG_MARK, APLOG_INFO, r,
+ "client stopped connection before send body completed");
+ ap_bsetflag(r->connection->client, B_EOUT, 1);
+ r->connection->aborted = 1;
+ }
+ break;
+ }
+ }
+ }
+
+ ap_kill_timeout(r);
+ SET_BYTES_SENT(r);
+ return total_bytes_sent;
+}
+
+
+
+/* The code writes MMAP_SEGMENT_SIZE bytes at a time. This is due to Apache's
+ * timeout model, which is a timeout per-write rather than a time for the
+ * entire transaction to complete. Essentially this should be small enough
+ * so that in one Timeout period, your slowest clients should be reasonably
+ * able to receive this many bytes.
+ *
+ * To take advantage of zero-copy TCP under Solaris 2.6 this should be a
+ * multiple of 16k. (And you need a SunATM2.0 network card.)
+ */
+#ifndef MMAP_SEGMENT_SIZE
+#define MMAP_SEGMENT_SIZE 32768
+#endif
+
+/* send data from an in-memory buffer */
+API_EXPORT(size_t) ap_send_mmap(void *mm, request_rec *r, size_t offset,
+ size_t length)
+{
+ size_t total_bytes_sent = 0;
+ int n, w;
+
+ if (length == 0)
+ return 0;
+
+ ap_soft_timeout("send mmap", r);
+
+ length += offset;
+ while (!r->connection->aborted && offset < length) {
+ if (length - offset > MMAP_SEGMENT_SIZE) {
+ n = MMAP_SEGMENT_SIZE;
+ }
+ else {
+ n = length - offset;
+ }
+
+ while (n && !r->connection->aborted) {
+ w = ap_bwrite(r->connection->client, (char *) mm + offset, n);
+ if (w > 0) {
+ ap_reset_timeout(r); /* reset timeout after successful write */
+ total_bytes_sent += w;
+ n -= w;
+ offset += w;
+ }
+ else if (w < 0) {
+ if (!r->connection->aborted) {
+ ap_log_rerror(APLOG_MARK, APLOG_INFO, r,
+ "client stopped connection before send mmap completed");
+ ap_bsetflag(r->connection->client, B_EOUT, 1);
+ r->connection->aborted = 1;
+ }
+ break;
+ }
+ }
+ }
+
+ ap_kill_timeout(r);
+ SET_BYTES_SENT(r);
+ return total_bytes_sent;
+}
+
+API_EXPORT(int) ap_rputc(int c, request_rec *r)
+{
+ if (r->connection->aborted)
+ return EOF;
+
+ if (ap_bputc(c, r->connection->client) < 0) {
+ if (!r->connection->aborted) {
+ ap_log_rerror(APLOG_MARK, APLOG_INFO, r,
+ "client stopped connection before rputc completed");
+ ap_bsetflag(r->connection->client, B_EOUT, 1);
+ r->connection->aborted = 1;
+ }
+ return EOF;
+ }
+ SET_BYTES_SENT(r);
+ return c;
+}
+
+API_EXPORT(int) ap_rputs(const char *str, request_rec *r)
+{
+ int rcode;
+
+ if (r->connection->aborted)
+ return EOF;
+
+ rcode = ap_bputs(str, r->connection->client);
+ if (rcode < 0) {
+ if (!r->connection->aborted) {
+ ap_log_rerror(APLOG_MARK, APLOG_INFO, r,
+ "client stopped connection before rputs completed");
+ ap_bsetflag(r->connection->client, B_EOUT, 1);
+ r->connection->aborted = 1;
+ }
+ return EOF;
+ }
+ SET_BYTES_SENT(r);
+ return rcode;
+}
+
+API_EXPORT(int) ap_rwrite(const void *buf, int nbyte, request_rec *r)
+{
+ int n;
+
+ if (r->connection->aborted)
+ return -1;
+
+ n = ap_bwrite(r->connection->client, buf, nbyte);
+ if (n < 0) {
+ if (!r->connection->aborted) {
+ ap_log_rerror(APLOG_MARK, APLOG_INFO, r,
+ "client stopped connection before rwrite completed");
+ ap_bsetflag(r->connection->client, B_EOUT, 1);
+ r->connection->aborted = 1;
+ }
+ return -1;
+ }
+ SET_BYTES_SENT(r);
+ return n;
+}
+
+API_EXPORT(int) ap_vrprintf(request_rec *r, const char *fmt, va_list ap)
+{
+ int n;
+
+ if (r->connection->aborted)
+ return -1;
+
+ n = ap_vbprintf(r->connection->client, fmt, ap);
+
+ if (n < 0) {
+ if (!r->connection->aborted) {
+ ap_log_rerror(APLOG_MARK, APLOG_INFO, r,
+ "client stopped connection before vrprintf completed");
+ ap_bsetflag(r->connection->client, B_EOUT, 1);
+ r->connection->aborted = 1;
+ }
+ return -1;
+ }
+ SET_BYTES_SENT(r);
+ return n;
+}
+
+API_EXPORT(int) ap_rprintf(request_rec *r, const char *fmt,...)
+{
+ va_list vlist;
+ int n;
+
+ if (r->connection->aborted)
+ return -1;
+
+ va_start(vlist, fmt);
+ n = ap_vbprintf(r->connection->client, fmt, vlist);
+ va_end(vlist);
+
+ if (n < 0) {
+ if (!r->connection->aborted) {
+ ap_log_rerror(APLOG_MARK, APLOG_INFO, r,
+ "client stopped connection before rprintf completed");
+ ap_bsetflag(r->connection->client, B_EOUT, 1);
+ r->connection->aborted = 1;
+ }
+ return -1;
+ }
+ SET_BYTES_SENT(r);
+ return n;
+}
+
+API_EXPORT_NONSTD(int) ap_rvputs(request_rec *r,...)
+{
+ va_list args;
+ int i, j, k;
+ const char *x;
+ BUFF *fb = r->connection->client;
+
+ if (r->connection->aborted)
+ return EOF;
+
+ va_start(args, r);
+ for (k = 0;;) {
+ x = va_arg(args, const char *);
+ if (x == NULL)
+ break;
+ j = strlen(x);
+ i = ap_bwrite(fb, x, j);
+ if (i != j) {
+ va_end(args);
+ if (!r->connection->aborted) {
+ ap_log_rerror(APLOG_MARK, APLOG_INFO, r,
+ "client stopped connection before rvputs completed");
+ ap_bsetflag(r->connection->client, B_EOUT, 1);
+ r->connection->aborted = 1;
+ }
+ return EOF;
+ }
+ k += i;
+ }
+ va_end(args);
+
+ SET_BYTES_SENT(r);
+ return k;
+}
+
+API_EXPORT(int) ap_rflush(request_rec *r)
+{
+ if (ap_bflush(r->connection->client) < 0) {
+ if (!r->connection->aborted) {
+ ap_log_rerror(APLOG_MARK, APLOG_INFO, r,
+ "client stopped connection before rflush completed");
+ ap_bsetflag(r->connection->client, B_EOUT, 1);
+ r->connection->aborted = 1;
+ }
+ return EOF;
+ }
+ return 0;
+}
+
+/* We should have named this send_canned_response, since it is used for any
+ * response that can be generated by the server from the request record.
+ * This includes all 204 (no content), 3xx (redirect), 4xx (client error),
+ * and 5xx (server error) messages that have not been redirected to another
+ * handler via the ErrorDocument feature.
+ */
+void ap_send_error_response(request_rec *r, int recursive_error)
+{
+ int status = r->status;
+ int idx = ap_index_of_response(status);
+ char *custom_response;
+ const char *location = ap_table_get(r->headers_out, "Location");
+
+ /*
+ * It's possible that the Location field might be in r->err_headers_out
+ * instead of r->headers_out; use the latter if possible, else the
+ * former.
+ */
+ if (location == NULL) {
+ location = ap_table_get(r->err_headers_out, "Location");
+ }
+ /* We need to special-case the handling of 204 and 304 responses,
+ * since they have specific HTTP requirements and do not include a
+ * message body. Note that being assbackwards here is not an option.
+ */
+ if (status == HTTP_NOT_MODIFIED) {
+ if (!ap_is_empty_table(r->err_headers_out))
+ r->headers_out = ap_overlay_tables(r->pool, r->err_headers_out,
+ r->headers_out);
+ ap_hard_timeout("send 304", r);
+
+ ap_basic_http_header(r);
+ ap_set_keepalive(r);
+
+ ap_table_do((int (*)(void *, const char *, const char *)) ap_send_header_field,
+ (void *) r, r->headers_out,
+ "Connection",
+ "Keep-Alive",
+ "ETag",
+ "Content-Location",
+ "Expires",
+ "Cache-Control",
+ "Vary",
+ "Warning",
+ "WWW-Authenticate",
+ "Proxy-Authenticate",
+ NULL);
+
+ terminate_header(r->connection->client);
+
+ ap_kill_timeout(r);
+ return;
+ }
+
+ if (status == HTTP_NO_CONTENT) {
+ ap_send_http_header(r);
+ ap_finalize_request_protocol(r);
+ return;
+ }
+
+ if (!r->assbackwards) {
+ table *tmp = r->headers_out;
+
+ /* For all HTTP/1.x responses for which we generate the message,
+ * we need to avoid inheriting the "normal status" header fields
+ * that may have been set by the request handler before the
+ * error or redirect, except for Location on external redirects.
+ */
+ r->headers_out = r->err_headers_out;
+ r->err_headers_out = tmp;
+ ap_clear_table(r->err_headers_out);
+
+ if (ap_is_HTTP_REDIRECT(status) || (status == HTTP_CREATED)) {
+ if ((location != NULL) && *location) {
+ ap_table_setn(r->headers_out, "Location", location);
+ }
+ else {
+ location = ""; /* avoids coredump when printing, below */
+ }
+ }
+
+ r->content_language = NULL;
+ r->content_languages = NULL;
+ r->content_encoding = NULL;
+ r->clength = 0;
+ r->content_type = "text/html";
+
+ if ((status == METHOD_NOT_ALLOWED) || (status == NOT_IMPLEMENTED))
+ ap_table_setn(r->headers_out, "Allow", make_allow(r));
+
+ ap_send_http_header(r);
+
+ if (r->header_only) {
+ ap_finalize_request_protocol(r);
+ ap_rflush(r);
+ return;
+ }
+ }
+
+ ap_hard_timeout("send error body", r);
+
+ if ((custom_response = ap_response_code_string(r, idx))) {
+ /*
+ * We have a custom response output. This should only be
+ * a text-string to write back. But if the ErrorDocument
+ * was a local redirect and the requested resource failed
+ * for any reason, the custom_response will still hold the
+ * redirect URL. We don't really want to output this URL
+ * as a text message, so first check the custom response
+ * string to ensure that it is a text-string (using the
+ * same test used in ap_die(), i.e. does it start with a ").
+ * If it doesn't, we've got a recursive error, so find
+ * the original error and output that as well.
+ */
+ if (custom_response[0] == '\"') {
+ ap_rputs(custom_response + 1, r);
+ ap_kill_timeout(r);
+ ap_finalize_request_protocol(r);
+ ap_rflush(r);
+ return;
+ }
+ /*
+ * Redirect failed, so get back the original error
+ */
+ while (r->prev && (r->prev->status != HTTP_OK))
+ r = r->prev;
+ }
+ {
+ const char *title = status_lines[idx];
+ const char *h1;
+ const char *error_notes;
+
+ /* Accept a status_line set by a module, but only if it begins
+ * with the 3 digit status code
+ */
+ if (r->status_line != NULL
+ && strlen(r->status_line) > 4 /* long enough */
+ && ap_isdigit(r->status_line[0])
+ && ap_isdigit(r->status_line[1])
+ && ap_isdigit(r->status_line[2])
+ && ap_isspace(r->status_line[3])
+ && ap_isalnum(r->status_line[4])) {
+ title = r->status_line;
+ }
+
+ /* folks decided they didn't want the error code in the H1 text */
+ h1 = &title[4];
+
+ ap_rvputs(r,
+ DOCTYPE_HTML_2_0
+ "\n", title,
+ "\n\n", h1, "\n",
+ NULL);
+
+ switch (status) {
+ case HTTP_MOVED_PERMANENTLY:
+ case HTTP_MOVED_TEMPORARILY:
+ case HTTP_TEMPORARY_REDIRECT:
+ ap_rvputs(r, "The document has moved pool, location), "\">here.\n",
+ NULL);
+ break;
+ case HTTP_SEE_OTHER:
+ ap_rvputs(r, "The answer to your request is located pool, location), "\">here. \n",
+ NULL);
+ break;
+ case HTTP_USE_PROXY:
+ ap_rvputs(r, "This resource is only accessible "
+ "through the proxy\n",
+ ap_escape_html(r->pool, location),
+ " \nYou will need to ",
+ "configure your client to use that proxy. \n", NULL);
+ break;
+ case HTTP_PROXY_AUTHENTICATION_REQUIRED:
+ case AUTH_REQUIRED:
+ ap_rputs("This server could not verify that you\n"
+ "are authorized to access the document\n"
+ "requested. Either you supplied the wrong\n"
+ "credentials (e.g., bad password), or your\n"
+ "browser doesn't understand how to supply\n"
+ "the credentials required. \n", r);
+ break;
+ case BAD_REQUEST:
+ ap_rputs("Your browser sent a request that "
+ "this server could not understand. \n", r);
+ if ((error_notes = ap_table_get(r->notes, "error-notes")) != NULL) {
+ ap_rvputs(r, error_notes, " \n", NULL);
+ }
+ break;
+ case HTTP_FORBIDDEN:
+ ap_rvputs(r, "You don't have permission to access ",
+ ap_escape_html(r->pool, r->uri),
+ "\non this server. \n", NULL);
+ break;
+ case NOT_FOUND:
+ ap_rvputs(r, "The requested URL ",
+ ap_escape_html(r->pool, r->uri),
+ " was not found on this server. \n", NULL);
+ break;
+ case METHOD_NOT_ALLOWED:
+ ap_rvputs(r, "The requested method ", r->method,
+ " is not allowed "
+ "for the URL ", ap_escape_html(r->pool, r->uri),
+ ". \n", NULL);
+ break;
+ case NOT_ACCEPTABLE:
+ ap_rvputs(r,
+ "An appropriate representation of the "
+ "requested resource ",
+ ap_escape_html(r->pool, r->uri),
+ " could not be found on this server. \n", NULL);
+ /* fall through */
+ case MULTIPLE_CHOICES:
+ {
+ const char *list;
+ if ((list = ap_table_get(r->notes, "variant-list")))
+ ap_rputs(list, r);
+ }
+ break;
+ case LENGTH_REQUIRED:
+ ap_rvputs(r, "A request of the requested method ", r->method,
+ " requires a valid Content-length. \n", NULL);
+ if ((error_notes = ap_table_get(r->notes, "error-notes")) != NULL) {
+ ap_rvputs(r, error_notes, " \n", NULL);
+ }
+ break;
+ case PRECONDITION_FAILED:
+ ap_rvputs(r, "The precondition on the request for the URL ",
+ ap_escape_html(r->pool, r->uri),
+ " evaluated to false. \n", NULL);
+ break;
+ case HTTP_NOT_IMPLEMENTED:
+ ap_rvputs(r, ap_escape_html(r->pool, r->method), " to ",
+ ap_escape_html(r->pool, r->uri),
+ " not supported. \n", NULL);
+ if ((error_notes = ap_table_get(r->notes, "error-notes")) != NULL) {
+ ap_rvputs(r, error_notes, " \n", NULL);
+ }
+ break;
+ case BAD_GATEWAY:
+ ap_rputs("The proxy server received an invalid\015\012"
+ "response from an upstream server. \015\012", r);
+ if ((error_notes = ap_table_get(r->notes, "error-notes")) != NULL) {
+ ap_rvputs(r, error_notes, " \n", NULL);
+ }
+ break;
+ case VARIANT_ALSO_VARIES:
+ ap_rvputs(r, "A variant for the requested resource\n \n",
+ ap_escape_html(r->pool, r->uri),
+ "\n \nis itself a negotiable resource. "
+ "This indicates a configuration error.\n", NULL);
+ break;
+ case HTTP_REQUEST_TIME_OUT:
+ ap_rputs("I'm tired of waiting for your request.\n", r);
+ break;
+ case HTTP_GONE:
+ ap_rvputs(r, "The requested resource ",
+ ap_escape_html(r->pool, r->uri),
+ " \nis no longer available on this server ",
+ "and there is no forwarding address.\n",
+ "Please remove all references to this resource.\n",
+ NULL);
+ break;
+ case HTTP_REQUEST_ENTITY_TOO_LARGE:
+ ap_rvputs(r, "The requested resource ",
+ ap_escape_html(r->pool, r->uri), " \n",
+ "does not allow request data with ", r->method,
+ " requests, or the amount of data provided in\n",
+ "the request exceeds the capacity limit.\n", NULL);
+ break;
+ case HTTP_REQUEST_URI_TOO_LARGE:
+ ap_rputs("The requested URL's length exceeds the capacity\n"
+ "limit for this server. \n", r);
+ if ((error_notes = ap_table_get(r->notes, "error-notes")) != NULL) {
+ ap_rvputs(r, error_notes, " \n", NULL);
+ }
+ break;
+ case HTTP_UNSUPPORTED_MEDIA_TYPE:
+ ap_rputs("The supplied request data is not in a format\n"
+ "acceptable for processing by this resource.\n", r);
+ break;
+ case HTTP_RANGE_NOT_SATISFIABLE:
+ ap_rputs("None of the range-specifier values in the Range\n"
+ "request-header field overlap the current extent\n"
+ "of the selected resource.\n", r);
+ break;
+ case HTTP_EXPECTATION_FAILED:
+ ap_rvputs(r, "The expectation given in the Expect request-header"
+ "\nfield could not be met by this server. \n"
+ "The client sent \n Expect: ",
+ ap_table_get(r->headers_in, "Expect"), "\n \n"
+ "but we only allow the 100-continue expectation.\n",
+ NULL);
+ break;
+ case HTTP_UNPROCESSABLE_ENTITY:
+ ap_rputs("The server understands the media type of the\n"
+ "request entity, but was unable to process the\n"
+ "contained instructions.\n", r);
+ break;
+ case HTTP_LOCKED:
+ ap_rputs("The requested resource is currently locked.\n"
+ "The lock must be released or proper identification\n"
+ "given before the method can be applied.\n", r);
+ break;
+ case HTTP_FAILED_DEPENDENCY:
+ ap_rputs("The method could not be performed on the resource\n"
+ "because the requested action depended on another\n"
+ "action and that other action failed.\n", r);
+ break;
+ case HTTP_INSUFFICIENT_STORAGE:
+ ap_rputs("The method could not be performed on the resource\n"
+ "because the server is unable to store the\n"
+ "representation needed to successfully complete the\n"
+ "request. There is insufficient free space left in\n"
+ "your storage allocation.\n", r);
+ break;
+ case HTTP_SERVICE_UNAVAILABLE:
+ ap_rputs("The server is temporarily unable to service your\n"
+ "request due to maintenance downtime or capacity\n"
+ "problems. Please try again later.\n", r);
+ break;
+ case HTTP_GATEWAY_TIME_OUT:
+ ap_rputs("The proxy server did not receive a timely response\n"
+ "from the upstream server.\n", r);
+ break;
+ case HTTP_NOT_EXTENDED:
+ ap_rputs("A mandatory extension policy in the request is not\n"
+ "accepted by the server for this resource.\n", r);
+ break;
+ default: /* HTTP_INTERNAL_SERVER_ERROR */
+ /*
+ * This comparison to expose error-notes could be modified to
+ * use a configuration directive and export based on that
+ * directive. For now "*" is used to designate an error-notes
+ * that is totally safe for any user to see (ie lacks paths,
+ * database passwords, etc.)
+ */
+ if (((error_notes = ap_table_get(r->notes, "error-notes")) != NULL)
+ && (h1 = ap_table_get(r->notes, "verbose-error-to")) != NULL
+ && (strcmp(h1, "*") == 0)) {
+ ap_rvputs(r, error_notes, "\n", NULL);
+ }
+ else {
+ ap_rvputs(r, "The server encountered an internal error or\n"
+ "misconfiguration and was unable to complete\n"
+ "your request. \n"
+ "Please contact the server administrator,\n ",
+ ap_escape_html(r->pool, r->server->server_admin),
+ " and inform them of the time the error occurred,\n"
+ "and anything you might have done that may have\n"
+ "caused the error. \n"
+ "More information about this error may be available\n"
+ "in the server error log. \n", NULL);
+ }
+ /*
+ * It would be nice to give the user the information they need to
+ * fix the problem directly since many users don't have access to
+ * the error_log (think University sites) even though they can easily
+ * get this error by misconfiguring an htaccess file. However, the
+ * error notes tend to include the real file pathname in this case,
+ * which some people consider to be a breach of privacy. Until we
+ * can figure out a way to remove the pathname, leave this commented.
+ *
+ * if ((error_notes = ap_table_get(r->notes, "error-notes")) != NULL) {
+ * ap_rvputs(r, error_notes, " \n", NULL);
+ * }
+ */
+ break;
+ }
+
+ if (recursive_error) {
+ ap_rvputs(r, " Additionally, a ",
+ status_lines[ap_index_of_response(recursive_error)],
+ "\nerror was encountered while trying to use an "
+ "ErrorDocument to handle the request.\n", NULL);
+ }
+ ap_rputs(ap_psignature(" \n", r), r);
+ ap_rputs("\n", r);
+ }
+ ap_kill_timeout(r);
+ ap_finalize_request_protocol(r);
+ ap_rflush(r);
+}
diff --git a/modules/http/http_request.c b/modules/http/http_request.c
new file mode 100644
index 00000000000..bc4d45f60f8
--- /dev/null
+++ b/modules/http/http_request.c
@@ -0,0 +1,1374 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+/*
+ * http_request.c: functions to get and process requests
+ *
+ * Rob McCool 3/21/93
+ *
+ * Thoroughly revamped by rst for Apache. NB this file reads
+ * best from the bottom up.
+ *
+ */
+
+#define CORE_PRIVATE
+#include "httpd.h"
+#include "http_config.h"
+#include "http_request.h"
+#include "http_core.h"
+#include "http_protocol.h"
+#include "http_conf_globals.h" /* for ap_extended_status */
+#include "http_log.h"
+#include "http_main.h"
+#include "scoreboard.h"
+#include "fnmatch.h"
+
+/*****************************************************************
+ *
+ * Getting and checking directory configuration. Also checks the
+ * FollowSymlinks and FollowSymOwner stuff, since this is really the
+ * only place that can happen (barring a new mid_dir_walk callout).
+ *
+ * We can't do it as an access_checker module function which gets
+ * called with the final per_dir_config, since we could have a directory
+ * with FollowSymLinks disabled, which contains a symlink to another
+ * with a .htaccess file which turns FollowSymLinks back on --- and
+ * access in such a case must be denied. So, whatever it is that
+ * checks FollowSymLinks needs to know the state of the options as
+ * they change, all the way down.
+ */
+
+/*
+ * We don't want people able to serve up pipes, or unix sockets, or other
+ * scary things. Note that symlink tests are performed later.
+ */
+static int check_safe_file(request_rec *r)
+{
+ if (r->finfo.st_mode == 0 /* doesn't exist */
+ || S_ISDIR(r->finfo.st_mode)
+ || S_ISREG(r->finfo.st_mode)
+ || S_ISLNK(r->finfo.st_mode)) {
+ return OK;
+ }
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "object is not a file, directory or symlink: %s",
+ r->filename);
+ return HTTP_FORBIDDEN;
+}
+
+
+static int check_symlinks(char *d, int opts)
+{
+#if defined(OS2) || defined(WIN32)
+ /* OS/2 doesn't have symlinks */
+ return OK;
+#else
+ struct stat lfi, fi;
+ char *lastp;
+ int res;
+
+ if (opts & OPT_SYM_LINKS)
+ return OK;
+
+ /*
+ * Strip trailing '/', if any, off what we're checking; trailing slashes
+ * make some systems follow symlinks to directories even in lstat().
+ * After we've done the lstat, put it back. Also, don't bother checking
+ * '/' at all...
+ *
+ * Note that we don't have to worry about multiple slashes here because of
+ * no2slash() below...
+ */
+
+ lastp = d + strlen(d) - 1;
+ if (lastp == d)
+ return OK; /* Root directory, '/' */
+
+ if (*lastp == '/')
+ *lastp = '\0';
+ else
+ lastp = NULL;
+
+ res = lstat(d, &lfi);
+
+ if (lastp)
+ *lastp = '/';
+
+ /*
+ * Note that we don't reject accesses to nonexistent files (multiviews or
+ * the like may cons up a way to run the transaction anyway)...
+ */
+
+ if (!(res >= 0) || !S_ISLNK(lfi.st_mode))
+ return OK;
+
+ /* OK, it's a symlink. May still be OK with OPT_SYM_OWNER */
+
+ if (!(opts & OPT_SYM_OWNER))
+ return HTTP_FORBIDDEN;
+
+ if (stat(d, &fi) < 0)
+ return HTTP_FORBIDDEN;
+
+ return (fi.st_uid == lfi.st_uid) ? OK : HTTP_FORBIDDEN;
+
+#endif
+}
+
+/* Dealing with the file system to get PATH_INFO
+ */
+static int get_path_info(request_rec *r)
+{
+ char *cp;
+ char *path = r->filename;
+ char *end = &path[strlen(path)];
+ char *last_cp = NULL;
+ int rv;
+#ifdef HAVE_DRIVE_LETTERS
+ char bStripSlash=1;
+#endif
+
+ if (r->finfo.st_mode) {
+ /* assume path_info already set */
+ return OK;
+ }
+
+#ifdef HAVE_DRIVE_LETTERS
+ /* If the directory is x:\, then we don't want to strip
+ * the trailing slash since x: is not a valid directory.
+ */
+ if (strlen(path) == 3 && path[1] == ':' && path[2] == '/')
+ bStripSlash = 0;
+
+
+ /* If UNC name == //machine/share/, do not
+ * advance over the trailing slash. Any other
+ * UNC name is OK to strip the slash.
+ */
+ cp = end;
+ if (strlen(path) > 2 && path[0] == '/' && path[1] == '/' &&
+ path[2] != '/' && cp[-1] == '/') {
+ char *p;
+ int iCount=0;
+ p = path;
+ while (p = strchr(p,'/')) {
+ p++;
+ iCount++;
+ }
+
+ if (iCount == 4)
+ bStripSlash = 0;
+ }
+
+ if (bStripSlash)
+#endif
+ /* Advance over trailing slashes ... NOT part of filename
+ * if file is not a UNC name (Win32 only).
+ */
+ for (cp = end; cp > path && cp[-1] == '/'; --cp)
+ continue;
+
+
+ while (cp > path) {
+
+ /* See if the pathname ending here exists... */
+
+ *cp = '\0';
+
+ /* We must not stat() filenames that may cause os-specific system
+ * problems, such as "/file/aux" on DOS-abused filesystems.
+ * So pretend that they do not exist by returning an ENOENT error.
+ * This will force us to drop that part of the path and keep
+ * looking back for a "real" file that exists, while still allowing
+ * the "invalid" path parts within the PATH_INFO.
+ */
+ if (!ap_os_is_filename_valid(path)) {
+ errno = ENOENT;
+ rv = -1;
+ }
+ else {
+ errno = 0;
+ rv = stat(path, &r->finfo);
+ }
+
+ if (cp != end)
+ *cp = '/';
+
+ if (!rv) {
+
+ /*
+ * Aha! Found something. If it was a directory, we will search
+ * contents of that directory for a multi_match, so the PATH_INFO
+ * argument starts with the component after that.
+ */
+
+ if (S_ISDIR(r->finfo.st_mode) && last_cp) {
+ r->finfo.st_mode = 0; /* No such file... */
+ cp = last_cp;
+ }
+
+ r->path_info = ap_pstrdup(r->pool, cp);
+ *cp = '\0';
+ return OK;
+ }
+ /* must set this to zero, some stat()s may have corrupted it
+ * even if they returned an error.
+ */
+ r->finfo.st_mode = 0;
+#if defined(ENOENT) && defined(ENOTDIR)
+ if (errno == ENOENT || errno == ENOTDIR) {
+ last_cp = cp;
+
+ while (--cp > path && *cp != '/')
+ continue;
+
+ while (cp > path && cp[-1] == '/')
+ --cp;
+ }
+ else {
+#if defined(EACCES)
+ if (errno != EACCES)
+#endif
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
+ "access to %s failed", r->uri);
+ return HTTP_FORBIDDEN;
+ }
+#else
+#error ENOENT || ENOTDIR not defined; please see the
+#error comments at this line in the source for a workaround.
+ /*
+ * If ENOENT || ENOTDIR is not defined in one of the your OS's
+ * include files, Apache does not know how to check to see why the
+ * stat() of the index file failed; there are cases where it can fail
+ * even though the file exists. This means that it is possible for
+ * someone to get a directory listing of a directory even though
+ * there is an index (eg. index.html) file in it. If you do not have
+ * a problem with this, delete the above #error lines and start the
+ * compile again. If you need to do this, please submit a bug report
+ * from http://www.apache.org/bug_report.html letting us know that
+ * you needed to do this. Please be sure to include the operating
+ * system you are using.
+ */
+ last_cp = cp;
+
+ while (--cp > path && *cp != '/')
+ continue;
+
+ while (cp > path && cp[-1] == '/')
+ --cp;
+#endif /* ENOENT && ENOTDIR */
+ }
+ return OK;
+}
+
+static int directory_walk(request_rec *r)
+{
+ core_server_config *sconf = ap_get_module_config(r->server->module_config,
+ &core_module);
+ void *per_dir_defaults = r->server->lookup_defaults;
+ void **sec = (void **) sconf->sec->elts;
+ int num_sec = sconf->sec->nelts;
+ char *test_filename;
+ char *test_dirname;
+ int res;
+ unsigned i, num_dirs, iStart;
+ int j, test_filename_len;
+
+ /*
+ * Are we dealing with a file? If not, we can (hopefuly) safely assume we
+ * have a handler that doesn't require one, but for safety's sake, and so
+ * we have something find_types() can get something out of, fake one. But
+ * don't run through the directory entries.
+ */
+
+ if (r->filename == NULL) {
+ r->filename = ap_pstrdup(r->pool, r->uri);
+ r->finfo.st_mode = 0; /* Not really a file... */
+ r->per_dir_config = per_dir_defaults;
+
+ return OK;
+ }
+
+ /*
+ * Go down the directory hierarchy. Where we have to check for symlinks,
+ * do so. Where a .htaccess file has permission to override anything,
+ * try to find one. If either of these things fails, we could poke
+ * around, see why, and adjust the lookup_rec accordingly --- this might
+ * save us a call to get_path_info (with the attendant stat()s); however,
+ * for the moment, that's not worth the trouble.
+ *
+ * Fake filenames (i.e. proxy:) only match Directory sections.
+ */
+
+ if (!ap_os_is_path_absolute(r->filename))
+ {
+ void *this_conf, *entry_config;
+ core_dir_config *entry_core;
+ char *entry_dir;
+
+ for (j = 0; j < num_sec; ++j) {
+
+ entry_config = sec[j];
+
+ entry_core = (core_dir_config *)
+ ap_get_module_config(entry_config, &core_module);
+ entry_dir = entry_core->d;
+
+ this_conf = NULL;
+ if (entry_core->r) {
+ if (!ap_regexec(entry_core->r, r->filename, 0, NULL, 0))
+ this_conf = entry_config;
+ }
+ else if (entry_core->d_is_fnmatch) {
+ if (!ap_fnmatch(entry_dir, r->filename, 0))
+ this_conf = entry_config;
+ }
+ else if (!strncmp(r->filename, entry_dir, strlen(entry_dir)))
+ this_conf = entry_config;
+
+ if (this_conf)
+ per_dir_defaults = ap_merge_per_dir_configs(r->pool,
+ per_dir_defaults,
+ this_conf);
+ }
+
+ r->per_dir_config = per_dir_defaults;
+
+ return OK;
+ }
+
+ r->filename = ap_os_case_canonical_filename(r->pool, r->filename);
+
+ res = get_path_info(r);
+ if (res != OK) {
+ return res;
+ }
+
+ r->filename = ap_os_canonical_filename(r->pool, r->filename);
+
+ test_filename = ap_pstrdup(r->pool, r->filename);
+
+ ap_no2slash(test_filename);
+ num_dirs = ap_count_dirs(test_filename);
+
+ if (!ap_os_is_filename_valid(r->filename)) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Filename is not valid: %s", r->filename);
+ return HTTP_FORBIDDEN;
+ }
+
+ if ((res = check_safe_file(r))) {
+ return res;
+ }
+
+ test_filename_len = strlen(test_filename);
+ if (test_filename[test_filename_len - 1] == '/')
+ --num_dirs;
+
+ if (S_ISDIR(r->finfo.st_mode))
+ ++num_dirs;
+
+ /*
+ * We will use test_dirname as scratch space while we build directory
+ * names during the walk. Profiling shows directory_walk to be a busy
+ * function so we try to avoid allocating lots of extra memory here.
+ * We need 2 extra bytes, one for trailing \0 and one because
+ * make_dirstr_prefix will add potentially one extra /.
+ */
+ test_dirname = ap_palloc(r->pool, test_filename_len + 2);
+
+ iStart = 1;
+#ifdef WIN32
+ /* If the name is a UNC name, then do not walk through the
+ * machine and share name (e.g. \\machine\share\)
+ */
+ if (num_dirs > 3 && test_filename[0] == '/' && test_filename[1] == '/')
+ iStart = 4;
+#endif
+
+ /* j keeps track of which section we're on, see core_reorder_directories */
+ j = 0;
+ for (i = iStart; i <= num_dirs; ++i) {
+ int overrides_here;
+ core_dir_config *core_dir = (core_dir_config *)
+ ap_get_module_config(per_dir_defaults, &core_module);
+
+ /*
+ * XXX: this could be made faster by only copying the next component
+ * rather than copying the entire thing all over.
+ */
+ ap_make_dirstr_prefix(test_dirname, test_filename, i);
+
+ /*
+ * Do symlink checks first, because they are done with the
+ * permissions appropriate to the *parent* directory...
+ */
+
+ if ((res = check_symlinks(test_dirname, core_dir->opts))) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Symbolic link not allowed: %s", test_dirname);
+ return res;
+ }
+
+ /*
+ * Begin *this* level by looking for matching sections
+ * from access.conf.
+ */
+
+ for (; j < num_sec; ++j) {
+ void *entry_config = sec[j];
+ core_dir_config *entry_core;
+ char *entry_dir;
+ void *this_conf;
+
+ entry_core = (core_dir_config *)
+ ap_get_module_config(entry_config, &core_module);
+ entry_dir = entry_core->d;
+
+ if (entry_core->r
+ || !ap_os_is_path_absolute(entry_dir)
+ || entry_core->d_components > i)
+ break;
+
+ this_conf = NULL;
+ if (entry_core->d_is_fnmatch) {
+ if (!ap_fnmatch(entry_dir, test_dirname, FNM_PATHNAME)) {
+ this_conf = entry_config;
+ }
+ }
+ else if (!strcmp(test_dirname, entry_dir))
+ this_conf = entry_config;
+
+ if (this_conf) {
+ per_dir_defaults = ap_merge_per_dir_configs(r->pool,
+ per_dir_defaults,
+ this_conf);
+ core_dir = (core_dir_config *)
+ ap_get_module_config(per_dir_defaults, &core_module);
+ }
+ }
+ overrides_here = core_dir->override;
+
+ /* If .htaccess files are enabled, check for one. */
+
+ if (overrides_here) {
+ void *htaccess_conf = NULL;
+
+ res = ap_parse_htaccess(&htaccess_conf, r, overrides_here,
+ ap_pstrdup(r->pool, test_dirname),
+ sconf->access_name);
+ if (res)
+ return res;
+
+ if (htaccess_conf) {
+ per_dir_defaults = ap_merge_per_dir_configs(r->pool,
+ per_dir_defaults,
+ htaccess_conf);
+ r->per_dir_config = per_dir_defaults;
+ }
+ }
+ }
+
+ /*
+ * There's two types of IS_SPECIAL sections (see http_core.c), and we've
+ * already handled the proxy:-style stuff. Now we'll deal with the
+ * regexes.
+ */
+ for (; j < num_sec; ++j) {
+ void *entry_config = sec[j];
+ core_dir_config *entry_core;
+
+ entry_core = (core_dir_config *)
+ ap_get_module_config(entry_config, &core_module);
+
+ if (entry_core->r) {
+ if (!ap_regexec(entry_core->r, test_dirname, 0, NULL, REG_NOTEOL)) {
+ per_dir_defaults =
+ ap_merge_per_dir_configs(r->pool, per_dir_defaults,
+ entry_config);
+ }
+ }
+ }
+ r->per_dir_config = per_dir_defaults;
+
+ /*
+ * Symlink permissions are determined by the parent. If the request is
+ * for a directory then applying the symlink test here would use the
+ * permissions of the directory as opposed to its parent. Consider a
+ * symlink pointing to a dir with a .htaccess disallowing symlinks. If
+ * you access /symlink (or /symlink/) you would get a 403 without this
+ * S_ISDIR test. But if you accessed /symlink/index.html, for example,
+ * you would *not* get the 403.
+ */
+ if (!S_ISDIR(r->finfo.st_mode)
+ && (res = check_symlinks(r->filename, ap_allow_options(r)))) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Symbolic link not allowed: %s", r->filename);
+ return res;
+ }
+ return OK; /* Can only "fail" if access denied by the
+ * symlink goop. */
+}
+
+static int location_walk(request_rec *r)
+{
+ core_server_config *sconf = ap_get_module_config(r->server->module_config,
+ &core_module);
+ void *per_dir_defaults = r->per_dir_config;
+ void **url = (void **) sconf->sec_url->elts;
+ int len, num_url = sconf->sec_url->nelts;
+ char *test_location;
+ void *this_conf, *entry_config;
+ core_dir_config *entry_core;
+ char *entry_url;
+ int j;
+
+ if (!num_url) {
+ return OK;
+ }
+
+ /* Location and LocationMatch differ on their behaviour w.r.t. multiple
+ * slashes. Location matches multiple slashes with a single slash,
+ * LocationMatch doesn't. An exception, for backwards brokenness is
+ * absoluteURIs... in which case neither match multiple slashes.
+ */
+ if (r->uri[0] != '/') {
+ test_location = r->uri;
+ }
+ else {
+ test_location = ap_pstrdup(r->pool, r->uri);
+ ap_no2slash(test_location);
+ }
+
+ /* Go through the location entries, and check for matches. */
+
+ /* we apply the directive sections in some order;
+ * should really try them with the most general first.
+ */
+ for (j = 0; j < num_url; ++j) {
+
+ entry_config = url[j];
+
+ entry_core = (core_dir_config *)
+ ap_get_module_config(entry_config, &core_module);
+ entry_url = entry_core->d;
+
+ len = strlen(entry_url);
+
+ this_conf = NULL;
+
+ if (entry_core->r) {
+ if (!ap_regexec(entry_core->r, r->uri, 0, NULL, 0))
+ this_conf = entry_config;
+ }
+ else if (entry_core->d_is_fnmatch) {
+ if (!ap_fnmatch(entry_url, test_location, FNM_PATHNAME)) {
+ this_conf = entry_config;
+ }
+ }
+ else if (!strncmp(test_location, entry_url, len) &&
+ (entry_url[len - 1] == '/' ||
+ test_location[len] == '/' || test_location[len] == '\0'))
+ this_conf = entry_config;
+
+ if (this_conf)
+ per_dir_defaults = ap_merge_per_dir_configs(r->pool,
+ per_dir_defaults, this_conf);
+ }
+ r->per_dir_config = per_dir_defaults;
+
+ return OK;
+}
+
+static int file_walk(request_rec *r)
+{
+ core_dir_config *conf = ap_get_module_config(r->per_dir_config, &core_module);
+ void *per_dir_defaults = r->per_dir_config;
+ void **file = (void **) conf->sec->elts;
+ int num_files = conf->sec->nelts;
+ char *test_file;
+
+ /* get the basename */
+ test_file = strrchr(r->filename, '/');
+ if (test_file == NULL) {
+ test_file = r->filename;
+ }
+ else {
+ ++test_file;
+ }
+
+ /* Go through the file entries, and check for matches. */
+
+ if (num_files) {
+ void *this_conf, *entry_config;
+ core_dir_config *entry_core;
+ char *entry_file;
+ int j;
+
+ /* we apply the directive sections in some order;
+ * should really try them with the most general first.
+ */
+ for (j = 0; j < num_files; ++j) {
+
+ entry_config = file[j];
+
+ entry_core = (core_dir_config *)
+ ap_get_module_config(entry_config, &core_module);
+ entry_file = entry_core->d;
+
+ this_conf = NULL;
+
+ if (entry_core->r) {
+ if (!ap_regexec(entry_core->r, test_file, 0, NULL, 0))
+ this_conf = entry_config;
+ }
+ else if (entry_core->d_is_fnmatch) {
+ if (!ap_fnmatch(entry_file, test_file, FNM_PATHNAME)) {
+ this_conf = entry_config;
+ }
+ }
+ else if (!strcmp(test_file, entry_file)) {
+ this_conf = entry_config;
+ }
+
+ if (this_conf)
+ per_dir_defaults = ap_merge_per_dir_configs(r->pool,
+ per_dir_defaults,
+ this_conf);
+ }
+ r->per_dir_config = per_dir_defaults;
+ }
+ return OK;
+}
+
+/*****************************************************************
+ *
+ * The sub_request mechanism.
+ *
+ * Fns to look up a relative URI from, e.g., a map file or SSI document.
+ * These do all access checks, etc., but don't actually run the transaction
+ * ... use run_sub_req below for that. Also, be sure to use destroy_sub_req
+ * as appropriate if you're likely to be creating more than a few of these.
+ * (An early Apache version didn't destroy the sub_reqs used in directory
+ * indexing. The result, when indexing a directory with 800-odd files in
+ * it, was massively excessive storage allocation).
+ *
+ * Note more manipulation of protocol-specific vars in the request
+ * structure...
+ */
+
+static request_rec *make_sub_request(const request_rec *r)
+{
+ pool *rrp = ap_make_sub_pool(r->pool);
+ request_rec *rr = ap_pcalloc(rrp, sizeof(request_rec));
+
+ rr->pool = rrp;
+ return rr;
+}
+
+API_EXPORT(request_rec *) ap_sub_req_method_uri(const char *method,
+ const char *new_file,
+ const request_rec *r)
+{
+ request_rec *rnew;
+ int res;
+ char *udir;
+
+ rnew = make_sub_request(r);
+ rnew->hostname = r->hostname;
+ rnew->request_time = r->request_time;
+ rnew->connection = r->connection;
+ rnew->server = r->server;
+ rnew->request_config = ap_create_request_config(rnew->pool);
+ rnew->htaccess = r->htaccess;
+ rnew->per_dir_config = r->server->lookup_defaults;
+
+ ap_set_sub_req_protocol(rnew, r);
+
+ /* would be nicer to pass "method" to ap_set_sub_req_protocol */
+ rnew->method = method;
+ rnew->method_number = ap_method_number_of(method);
+
+ if (new_file[0] == '/')
+ ap_parse_uri(rnew, new_file);
+ else {
+ udir = ap_make_dirstr_parent(rnew->pool, r->uri);
+ udir = ap_escape_uri(rnew->pool, udir); /* re-escape it */
+ ap_parse_uri(rnew, ap_make_full_path(rnew->pool, udir, new_file));
+ }
+
+ res = ap_unescape_url(rnew->uri);
+ if (res) {
+ rnew->status = res;
+ return rnew;
+ }
+
+ ap_getparents(rnew->uri);
+
+ if ((res = location_walk(rnew))) {
+ rnew->status = res;
+ return rnew;
+ }
+
+ res = ap_translate_name(rnew);
+ if (res) {
+ rnew->status = res;
+ return rnew;
+ }
+
+ /*
+ * We could be clever at this point, and avoid calling directory_walk,
+ * etc. However, we'd need to test that the old and new filenames contain
+ * the same directory components, so it would require duplicating the
+ * start of translate_name. Instead we rely on the cache of .htaccess
+ * results.
+ *
+ * NB: directory_walk() clears the per_dir_config, so we don't inherit
+ * from location_walk() above
+ */
+
+ if ((res = directory_walk(rnew))
+ || (res = file_walk(rnew))
+ || (res = location_walk(rnew))
+ || ((ap_satisfies(rnew) == SATISFY_ALL
+ || ap_satisfies(rnew) == SATISFY_NOSPEC)
+ ? ((res = ap_check_access(rnew))
+ || (ap_some_auth_required(rnew)
+ && ((res = ap_check_user_id(rnew))
+ || (res = ap_check_auth(rnew)))))
+ : ((res = ap_check_access(rnew))
+ && (!ap_some_auth_required(rnew)
+ || ((res = ap_check_user_id(rnew))
+ || (res = ap_check_auth(rnew)))))
+ )
+ || (res = ap_find_types(rnew))
+ || (res = ap_run_fixups(rnew))
+ ) {
+ rnew->status = res;
+ }
+ return rnew;
+}
+
+API_EXPORT(request_rec *) ap_sub_req_lookup_uri(const char *new_file,
+ const request_rec *r)
+{
+ return ap_sub_req_method_uri("GET", new_file, r);
+}
+
+API_EXPORT(request_rec *) ap_sub_req_lookup_file(const char *new_file,
+ const request_rec *r)
+{
+ request_rec *rnew;
+ int res;
+ char *fdir;
+
+ rnew = make_sub_request(r);
+ rnew->hostname = r->hostname;
+ rnew->request_time = r->request_time;
+ rnew->connection = r->connection;
+ rnew->server = r->server;
+ rnew->request_config = ap_create_request_config(rnew->pool);
+ rnew->htaccess = r->htaccess;
+
+ ap_set_sub_req_protocol(rnew, r);
+ fdir = ap_make_dirstr_parent(rnew->pool, r->filename);
+
+ /*
+ * Check for a special case... if there are no '/' characters in new_file
+ * at all, then we are looking at a relative lookup in the same
+ * directory. That means we won't have to redo directory_walk, and we may
+ * not even have to redo access checks.
+ */
+
+ if (strchr(new_file, '/') == NULL) {
+ char *udir = ap_make_dirstr_parent(rnew->pool, r->uri);
+
+ rnew->uri = ap_make_full_path(rnew->pool, udir, new_file);
+ rnew->filename = ap_make_full_path(rnew->pool, fdir, new_file);
+ ap_parse_uri(rnew, rnew->uri); /* fill in parsed_uri values */
+ if (stat(rnew->filename, &rnew->finfo) < 0) {
+ rnew->finfo.st_mode = 0;
+ }
+
+ if ((res = check_safe_file(rnew))) {
+ rnew->status = res;
+ return rnew;
+ }
+
+ rnew->per_dir_config = r->per_dir_config;
+
+ /*
+ * no matter what, if it's a subdirectory, we need to re-run
+ * directory_walk
+ */
+ if (S_ISDIR(rnew->finfo.st_mode)) {
+ res = directory_walk(rnew);
+ if (!res) {
+ res = file_walk(rnew);
+ }
+ }
+ else {
+ if ((res = check_symlinks(rnew->filename, ap_allow_options(rnew)))) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, rnew,
+ "Symbolic link not allowed: %s", rnew->filename);
+ rnew->status = res;
+ return rnew;
+ }
+ /*
+ * do a file_walk, if it doesn't change the per_dir_config then
+ * we know that we don't have to redo all the access checks
+ */
+ if ((res = file_walk(rnew))) {
+ rnew->status = res;
+ return rnew;
+ }
+ if (rnew->per_dir_config == r->per_dir_config) {
+ if ((res = ap_find_types(rnew)) || (res = ap_run_fixups(rnew))) {
+ rnew->status = res;
+ }
+ return rnew;
+ }
+ }
+ }
+ else {
+ /* XXX: @@@: What should be done with the parsed_uri values? */
+ ap_parse_uri(rnew, new_file); /* fill in parsed_uri values */
+ /*
+ * XXX: this should be set properly like it is in the same-dir case
+ * but it's actually sometimes to impossible to do it... because the
+ * file may not have a uri associated with it -djg
+ */
+ rnew->uri = "INTERNALLY GENERATED file-relative req";
+ rnew->filename = ((ap_os_is_path_absolute(new_file)) ?
+ ap_pstrdup(rnew->pool, new_file) :
+ ap_make_full_path(rnew->pool, fdir, new_file));
+ rnew->per_dir_config = r->server->lookup_defaults;
+ res = directory_walk(rnew);
+ if (!res) {
+ res = file_walk(rnew);
+ }
+ }
+
+ if (res
+ || ((ap_satisfies(rnew) == SATISFY_ALL
+ || ap_satisfies(rnew) == SATISFY_NOSPEC)
+ ? ((res = ap_check_access(rnew))
+ || (ap_some_auth_required(rnew)
+ && ((res = ap_check_user_id(rnew))
+ || (res = ap_check_auth(rnew)))))
+ : ((res = ap_check_access(rnew))
+ && (!ap_some_auth_required(rnew)
+ || ((res = ap_check_user_id(rnew))
+ || (res = ap_check_auth(rnew)))))
+ )
+ || (res = ap_find_types(rnew))
+ || (res = ap_run_fixups(rnew))
+ ) {
+ rnew->status = res;
+ }
+ return rnew;
+}
+
+API_EXPORT(int) ap_run_sub_req(request_rec *r)
+{
+#ifndef CHARSET_EBCDIC
+ int retval = ap_invoke_handler(r);
+#else /*CHARSET_EBCDIC*/
+ /* Save the EBCDIC conversion setting of the caller across subrequests */
+ int convert = ap_bgetflag(r->connection->client, B_EBCDIC2ASCII);
+ int retval = ap_invoke_handler(r);
+ ap_bsetflag(r->connection->client, B_EBCDIC2ASCII, convert);
+#endif /*CHARSET_EBCDIC*/
+ ap_finalize_sub_req_protocol(r);
+ return retval;
+}
+
+API_EXPORT(void) ap_destroy_sub_req(request_rec *r)
+{
+ /* Reclaim the space */
+ ap_destroy_pool(r->pool);
+}
+
+/*****************************************************************
+ *
+ * Mainline request processing...
+ */
+
+API_EXPORT(void) ap_die(int type, request_rec *r)
+{
+ int error_index = ap_index_of_response(type);
+ char *custom_response = ap_response_code_string(r, error_index);
+ int recursive_error = 0;
+
+ if (type == DONE) {
+ ap_finalize_request_protocol(r);
+ return;
+ }
+
+ /*
+ * The following takes care of Apache redirects to custom response URLs
+ * Note that if we are already dealing with the response to some other
+ * error condition, we just report on the original error, and give up on
+ * any attempt to handle the other thing "intelligently"...
+ */
+
+ if (r->status != HTTP_OK) {
+ recursive_error = type;
+
+ while (r->prev && (r->prev->status != HTTP_OK))
+ r = r->prev; /* Get back to original error */
+
+ type = r->status;
+ custom_response = NULL; /* Do NOT retry the custom thing! */
+ }
+
+ r->status = type;
+
+ /*
+ * This test is done here so that none of the auth modules needs to know
+ * about proxy authentication. They treat it like normal auth, and then
+ * we tweak the status.
+ */
+ if (r->status == AUTH_REQUIRED && r->proxyreq) {
+ r->status = HTTP_PROXY_AUTHENTICATION_REQUIRED;
+ }
+
+ /*
+ * If we want to keep the connection, be sure that the request body
+ * (if any) has been read.
+ */
+ if ((r->status != HTTP_NOT_MODIFIED) && (r->status != HTTP_NO_CONTENT)
+ && !ap_status_drops_connection(r->status)
+ && r->connection && (r->connection->keepalive != -1)) {
+
+ (void) ap_discard_request_body(r);
+ }
+
+ /*
+ * Two types of custom redirects --- plain text, and URLs. Plain text has
+ * a leading '"', so the URL code, here, is triggered on its absence
+ */
+
+ if (custom_response && custom_response[0] != '"') {
+
+ if (ap_is_url(custom_response)) {
+ /*
+ * The URL isn't local, so lets drop through the rest of this
+ * apache code, and continue with the usual REDIRECT handler.
+ * But note that the client will ultimately see the wrong
+ * status...
+ */
+ r->status = REDIRECT;
+ ap_table_setn(r->headers_out, "Location", custom_response);
+ }
+ else if (custom_response[0] == '/') {
+ const char *error_notes;
+ r->no_local_copy = 1; /* Do NOT send USE_LOCAL_COPY for
+ * error documents! */
+ /*
+ * This redirect needs to be a GET no matter what the original
+ * method was.
+ */
+ ap_table_setn(r->subprocess_env, "REQUEST_METHOD", r->method);
+
+ /*
+ * Provide a special method for modules to communicate
+ * more informative (than the plain canned) messages to us.
+ * Propagate them to ErrorDocuments via the ERROR_NOTES variable:
+ */
+ if ((error_notes = ap_table_get(r->notes, "error-notes")) != NULL) {
+ ap_table_setn(r->subprocess_env, "ERROR_NOTES", error_notes);
+ }
+ r->method = ap_pstrdup(r->pool, "GET");
+ r->method_number = M_GET;
+ ap_internal_redirect(custom_response, r);
+ return;
+ }
+ else {
+ /*
+ * Dumb user has given us a bad url to redirect to --- fake up
+ * dying with a recursive server error...
+ */
+ recursive_error = SERVER_ERROR;
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Invalid error redirection directive: %s",
+ custom_response);
+ }
+ }
+ ap_send_error_response(r, recursive_error);
+}
+
+static void decl_die(int status, char *phase, request_rec *r)
+{
+ if (status == DECLINED) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_CRIT, r,
+ "configuration error: couldn't %s: %s", phase, r->uri);
+ ap_die(SERVER_ERROR, r);
+ }
+ else
+ ap_die(status, r);
+}
+
+API_EXPORT(int) ap_some_auth_required(request_rec *r)
+{
+ /* Is there a require line configured for the type of *this* req? */
+
+ const array_header *reqs_arr = ap_requires(r);
+ require_line *reqs;
+ int i;
+
+ if (!reqs_arr)
+ return 0;
+
+ reqs = (require_line *) reqs_arr->elts;
+
+ for (i = 0; i < reqs_arr->nelts; ++i)
+ if (reqs[i].method_mask & (1 << r->method_number))
+ return 1;
+
+ return 0;
+}
+
+static void process_request_internal(request_rec *r)
+{
+ int access_status;
+
+ /* Ignore embedded %2F's in path for proxy requests */
+ if (!r->proxyreq && r->parsed_uri.path) {
+ access_status = ap_unescape_url(r->parsed_uri.path);
+ if (access_status) {
+ ap_die(access_status, r);
+ return;
+ }
+ }
+
+ ap_getparents(r->uri); /* OK --- shrinking transformations... */
+
+ if ((access_status = location_walk(r))) {
+ ap_die(access_status, r);
+ return;
+ }
+
+ if ((access_status = ap_translate_name(r))) {
+ decl_die(access_status, "translate", r);
+ return;
+ }
+
+ if (!r->proxyreq) {
+ /*
+ * We don't want TRACE to run through the normal handler set, we
+ * handle it specially.
+ */
+ if (r->method_number == M_TRACE) {
+ if ((access_status = ap_send_http_trace(r)))
+ ap_die(access_status, r);
+ else
+ ap_finalize_request_protocol(r);
+ return;
+ }
+ }
+
+ if (r->proto_num > HTTP_VERSION(1,0) && ap_table_get(r->subprocess_env, "downgrade-1.0")) {
+ r->proto_num = HTTP_VERSION(1,0);
+ }
+
+ /*
+ * NB: directory_walk() clears the per_dir_config, so we don't inherit
+ * from location_walk() above
+ */
+
+ if ((access_status = directory_walk(r))) {
+ ap_die(access_status, r);
+ return;
+ }
+
+ if ((access_status = file_walk(r))) {
+ ap_die(access_status, r);
+ return;
+ }
+
+ if ((access_status = location_walk(r))) {
+ ap_die(access_status, r);
+ return;
+ }
+
+ if ((access_status = ap_header_parse(r))) {
+ ap_die(access_status, r);
+ return;
+ }
+
+ switch (ap_satisfies(r)) {
+ case SATISFY_ALL:
+ case SATISFY_NOSPEC:
+ if ((access_status = ap_check_access(r)) != 0) {
+ decl_die(access_status, "check access", r);
+ return;
+ }
+ if (ap_some_auth_required(r)) {
+ if (((access_status = ap_check_user_id(r)) != 0) || !ap_auth_type(r)) {
+ decl_die(access_status, ap_auth_type(r)
+ ? "check user. No user file?"
+ : "perform authentication. AuthType not set!", r);
+ return;
+ }
+ if (((access_status = ap_check_auth(r)) != 0) || !ap_auth_type(r)) {
+ decl_die(access_status, ap_auth_type(r)
+ ? "check access. No groups file?"
+ : "perform authentication. AuthType not set!", r);
+ return;
+ }
+ }
+ break;
+ case SATISFY_ANY:
+ if (((access_status = ap_check_access(r)) != 0) || !ap_auth_type(r)) {
+ if (!ap_some_auth_required(r)) {
+ decl_die(access_status, ap_auth_type(r)
+ ? "check access"
+ : "perform authentication. AuthType not set!", r);
+ return;
+ }
+ if (((access_status = ap_check_user_id(r)) != 0) || !ap_auth_type(r)) {
+ decl_die(access_status, ap_auth_type(r)
+ ? "check user. No user file?"
+ : "perform authentication. AuthType not set!", r);
+ return;
+ }
+ if (((access_status = ap_check_auth(r)) != 0) || !ap_auth_type(r)) {
+ decl_die(access_status, ap_auth_type(r)
+ ? "check access. No groups file?"
+ : "perform authentication. AuthType not set!", r);
+ return;
+ }
+ }
+ break;
+ }
+
+ if (! (r->proxyreq
+ && r->parsed_uri.scheme != NULL
+ && strcmp(r->parsed_uri.scheme, "http") == 0) ) {
+ if ((access_status = ap_find_types(r)) != 0) {
+ decl_die(access_status, "find types", r);
+ return;
+ }
+ }
+
+ if ((access_status = ap_run_fixups(r)) != 0) {
+ ap_die(access_status, r);
+ return;
+ }
+
+ if ((access_status = ap_invoke_handler(r)) != 0) {
+ ap_die(access_status, r);
+ return;
+ }
+
+ /* Take care of little things that need to happen when we're done */
+ ap_finalize_request_protocol(r);
+}
+
+void ap_process_request(request_rec *r)
+{
+ int old_stat;
+
+ if (ap_extended_status)
+ ap_time_process_request(r->connection->child_num, START_PREQUEST);
+
+ process_request_internal(r);
+
+ old_stat = ap_update_child_status(r->connection->child_num,
+ SERVER_BUSY_LOG, r);
+
+ /*
+ * We want to flush the last packet if this isn't a pipelining connection
+ * *before* we start into logging. Suppose that the logging causes a DNS
+ * lookup to occur, which may have a high latency. If we hold off on
+ * this packet, then it'll appear like the link is stalled when really
+ * it's the application that's stalled.
+ */
+ ap_bhalfduplex(r->connection->client);
+ ap_log_transaction(r);
+
+ (void) ap_update_child_status(r->connection->child_num, old_stat, r);
+ if (ap_extended_status)
+ ap_time_process_request(r->connection->child_num, STOP_PREQUEST);
+}
+
+static table *rename_original_env(pool *p, table *t)
+{
+ array_header *env_arr = ap_table_elts(t);
+ table_entry *elts = (table_entry *) env_arr->elts;
+ table *new = ap_make_table(p, env_arr->nalloc);
+ int i;
+
+ for (i = 0; i < env_arr->nelts; ++i) {
+ if (!elts[i].key)
+ continue;
+ ap_table_setn(new, ap_pstrcat(p, "REDIRECT_", elts[i].key, NULL),
+ elts[i].val);
+ }
+
+ return new;
+}
+
+static request_rec *internal_internal_redirect(const char *new_uri, request_rec *r)
+{
+ int access_status;
+ request_rec *new = (request_rec *) ap_pcalloc(r->pool, sizeof(request_rec));
+
+ new->connection = r->connection;
+ new->server = r->server;
+ new->pool = r->pool;
+
+ /*
+ * A whole lot of this really ought to be shared with http_protocol.c...
+ * another missing cleanup. It's particularly inappropriate to be
+ * setting header_only, etc., here.
+ */
+
+ new->method = r->method;
+ new->method_number = r->method_number;
+ ap_parse_uri(new, new_uri);
+ new->request_config = ap_create_request_config(r->pool);
+ new->per_dir_config = r->server->lookup_defaults;
+
+ new->prev = r;
+ r->next = new;
+
+ /* Inherit the rest of the protocol info... */
+
+ new->the_request = r->the_request;
+
+ new->allowed = r->allowed;
+
+ new->status = r->status;
+ new->assbackwards = r->assbackwards;
+ new->header_only = r->header_only;
+ new->protocol = r->protocol;
+ new->proto_num = r->proto_num;
+ new->hostname = r->hostname;
+ new->request_time = r->request_time;
+ new->main = r->main;
+
+ new->headers_in = r->headers_in;
+ new->headers_out = ap_make_table(r->pool, 12);
+ new->err_headers_out = r->err_headers_out;
+ new->subprocess_env = rename_original_env(r->pool, r->subprocess_env);
+ new->notes = ap_make_table(r->pool, 5);
+
+ new->htaccess = r->htaccess;
+ new->no_cache = r->no_cache;
+ new->expecting_100 = r->expecting_100;
+ new->no_local_copy = r->no_local_copy;
+ new->read_length = r->read_length; /* We can only read it once */
+ new->vlist_validator = r->vlist_validator;
+
+ ap_table_setn(new->subprocess_env, "REDIRECT_STATUS",
+ ap_psprintf(r->pool, "%d", r->status));
+
+ /*
+ * XXX: hmm. This is because mod_setenvif and mod_unique_id really need
+ * to do their thing on internal redirects as well. Perhaps this is a
+ * misnamed function.
+ */
+ if ((access_status = ap_run_post_read_request(new))) {
+ ap_die(access_status, new);
+ return NULL;
+ }
+
+ return new;
+}
+
+API_EXPORT(void) ap_internal_redirect(const char *new_uri, request_rec *r)
+{
+ request_rec *new = internal_internal_redirect(new_uri, r);
+ process_request_internal(new);
+}
+
+/* This function is designed for things like actions or CGI scripts, when
+ * using AddHandler, and you want to preserve the content type across
+ * an internal redirect.
+ */
+API_EXPORT(void) ap_internal_redirect_handler(const char *new_uri, request_rec *r)
+{
+ request_rec *new = internal_internal_redirect(new_uri, r);
+ if (r->handler)
+ new->content_type = r->content_type;
+ process_request_internal(new);
+}
+
+/*
+ * Is it the initial main request, which we only get *once* per HTTP request?
+ */
+API_EXPORT(int) ap_is_initial_req(request_rec *r)
+{
+ return
+ (r->main == NULL) /* otherwise, this is a sub-request */
+ &&
+ (r->prev == NULL); /* otherwise, this is an internal redirect */
+}
+
+/*
+ * Function to set the r->mtime field to the specified value if it's later
+ * than what's already there.
+ */
+API_EXPORT(time_t) ap_update_mtime(request_rec *r, time_t dependency_mtime)
+{
+ if (r->mtime < dependency_mtime) {
+ r->mtime = dependency_mtime;
+ }
+ return r->mtime;
+}
diff --git a/modules/http/mod_mime.c b/modules/http/mod_mime.c
new file mode 100644
index 00000000000..f27356bfdd3
--- /dev/null
+++ b/modules/http/mod_mime.c
@@ -0,0 +1,402 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+/*
+ * http_mime.c: Sends/gets MIME headers for requests
+ *
+ * Rob McCool
+ *
+ */
+
+#define MIME_PRIVATE
+
+#include "httpd.h"
+#include "http_config.h"
+#include "http_log.h"
+
+typedef struct handlers_info {
+ char *name;
+} handlers_info;
+
+typedef struct {
+ table *forced_types; /* Additional AddTyped stuff */
+ table *encoding_types; /* Added with AddEncoding... */
+ table *language_types; /* Added with AddLanguage... */
+ table *handlers; /* Added with AddHandler... */
+ array_header *handlers_remove; /* List of handlers to remove */
+
+ char *type; /* Type forced with ForceType */
+ char *handler; /* Handler forced with SetHandler */
+ char *default_language; /* Language if no AddLanguage ext found */
+} mime_dir_config;
+
+module MODULE_VAR_EXPORT mime_module;
+
+static void *create_mime_dir_config(pool *p, char *dummy)
+{
+ mime_dir_config *new =
+ (mime_dir_config *) ap_palloc(p, sizeof(mime_dir_config));
+
+ new->forced_types = ap_make_table(p, 4);
+ new->encoding_types = ap_make_table(p, 4);
+ new->language_types = ap_make_table(p, 4);
+ new->handlers = ap_make_table(p, 4);
+ new->handlers_remove = ap_make_array(p, 4, sizeof(handlers_info));
+
+ new->type = NULL;
+ new->handler = NULL;
+ new->default_language = NULL;
+
+ return new;
+}
+
+static void *merge_mime_dir_configs(pool *p, void *basev, void *addv)
+{
+ mime_dir_config *base = (mime_dir_config *) basev;
+ mime_dir_config *add = (mime_dir_config *) addv;
+ mime_dir_config *new =
+ (mime_dir_config *) ap_palloc(p, sizeof(mime_dir_config));
+ int i;
+ handlers_info *hand;
+
+ hand = (handlers_info *) add->handlers_remove->elts;
+ for (i = 0; i < add->handlers_remove->nelts; i++) {
+ ap_table_unset(base->handlers, hand[i].name);
+ }
+
+ new->forced_types = ap_overlay_tables(p, add->forced_types,
+ base->forced_types);
+ new->encoding_types = ap_overlay_tables(p, add->encoding_types,
+ base->encoding_types);
+ new->language_types = ap_overlay_tables(p, add->language_types,
+ base->language_types);
+ new->handlers = ap_overlay_tables(p, add->handlers,
+ base->handlers);
+
+ new->type = add->type ? add->type : base->type;
+ new->handler = add->handler ? add->handler : base->handler;
+ new->default_language = add->default_language ?
+ add->default_language : base->default_language;
+
+ return new;
+}
+
+static const char *add_type(cmd_parms *cmd, mime_dir_config * m, char *ct,
+ char *ext)
+{
+ if (*ext == '.')
+ ++ext;
+ ap_str_tolower(ct);
+ ap_table_setn(m->forced_types, ext, ct);
+ return NULL;
+}
+
+static const char *add_encoding(cmd_parms *cmd, mime_dir_config * m, char *enc,
+ char *ext)
+{
+ if (*ext == '.')
+ ++ext;
+ ap_str_tolower(enc);
+ ap_table_setn(m->encoding_types, ext, enc);
+ return NULL;
+}
+
+static const char *add_language(cmd_parms *cmd, mime_dir_config * m, char *lang,
+ char *ext)
+{
+ if (*ext == '.')
+ ++ext;
+ ap_str_tolower(lang);
+ ap_table_setn(m->language_types, ext, lang);
+ return NULL;
+}
+
+static const char *add_handler(cmd_parms *cmd, mime_dir_config * m, char *hdlr,
+ char *ext)
+{
+ if (*ext == '.')
+ ++ext;
+ ap_str_tolower(hdlr);
+ ap_table_setn(m->handlers, ext, hdlr);
+ return NULL;
+}
+
+/*
+ * Note handler names that should be un-added for this location. This
+ * will keep the association from being inherited, as well, but not
+ * from being re-added at a subordinate level.
+ */
+static const char *remove_handler(cmd_parms *cmd, void *m, char *ext)
+{
+ mime_dir_config *mcfg = (mime_dir_config *) m;
+ handlers_info *hand;
+
+ if (*ext == '.') {
+ ++ext;
+ }
+ hand = (handlers_info *) ap_push_array(mcfg->handlers_remove);
+ hand->name = ap_pstrdup(cmd->pool, ext);
+ return NULL;
+}
+
+/* The sole bit of server configuration that the MIME module has is
+ * the name of its config file, so...
+ */
+
+static const char *set_types_config(cmd_parms *cmd, void *dummy, char *arg)
+{
+ ap_set_module_config(cmd->server->module_config, &mime_module, arg);
+ return NULL;
+}
+
+static const command_rec mime_cmds[] =
+{
+ {"AddType", add_type, NULL, OR_FILEINFO, ITERATE2,
+ "a mime type followed by one or more file extensions"},
+ {"AddEncoding", add_encoding, NULL, OR_FILEINFO, ITERATE2,
+ "an encoding (e.g., gzip), followed by one or more file extensions"},
+ {"AddLanguage", add_language, NULL, OR_FILEINFO, ITERATE2,
+ "a language (e.g., fr), followed by one or more file extensions"},
+ {"AddHandler", add_handler, NULL, OR_FILEINFO, ITERATE2,
+ "a handler name followed by one or more file extensions"},
+ {"ForceType", ap_set_string_slot_lower,
+ (void *)XtOffsetOf(mime_dir_config, type), OR_FILEINFO, TAKE1,
+ "a media type"},
+ {"RemoveHandler", remove_handler, NULL, OR_FILEINFO, ITERATE,
+ "one or more file extensions"},
+ {"SetHandler", ap_set_string_slot_lower,
+ (void *)XtOffsetOf(mime_dir_config, handler), OR_FILEINFO, TAKE1,
+ "a handler name"},
+ {"TypesConfig", set_types_config, NULL, RSRC_CONF, TAKE1,
+ "the MIME types config file"},
+ {"DefaultLanguage", ap_set_string_slot,
+ (void*)XtOffsetOf(mime_dir_config, default_language), OR_FILEINFO, TAKE1,
+ "language to use for documents with no other language file extension" },
+ {NULL}
+};
+
+/* Hash table --- only one of these per daemon; virtual hosts can
+ * get private versions through AddType...
+ */
+
+#define MIME_HASHSIZE (32)
+#define hash(i) (ap_tolower(i) % MIME_HASHSIZE)
+
+static table *hash_buckets[MIME_HASHSIZE];
+
+static void init_mime(server_rec *s, pool *p)
+{
+ configfile_t *f;
+ char l[MAX_STRING_LEN];
+ int x;
+ char *types_confname = ap_get_module_config(s->module_config, &mime_module);
+
+ if (!types_confname)
+ types_confname = TYPES_CONFIG_FILE;
+
+ types_confname = ap_server_root_relative(p, types_confname);
+
+ if (!(f = ap_pcfg_openfile(p, types_confname))) {
+ ap_log_error(APLOG_MARK, APLOG_ERR, s,
+ "could not open mime types log file %s.", types_confname);
+ exit(1);
+ }
+
+ for (x = 0; x < MIME_HASHSIZE; x++)
+ hash_buckets[x] = ap_make_table(p, 10);
+
+ while (!(ap_cfg_getline(l, MAX_STRING_LEN, f))) {
+ const char *ll = l, *ct;
+
+ if (l[0] == '#')
+ continue;
+ ct = ap_getword_conf(p, &ll);
+
+ while (ll[0]) {
+ char *ext = ap_getword_conf(p, &ll);
+ ap_str_tolower(ext); /* ??? */
+ ap_table_setn(hash_buckets[hash(ext[0])], ext, ct);
+ }
+ }
+ ap_cfg_closefile(f);
+}
+
+static int find_ct(request_rec *r)
+{
+ const char *fn = strrchr(r->filename, '/');
+ mime_dir_config *conf =
+ (mime_dir_config *) ap_get_module_config(r->per_dir_config, &mime_module);
+ char *ext;
+ const char *orighandler = r->handler;
+ const char *type;
+
+ if (S_ISDIR(r->finfo.st_mode)) {
+ r->content_type = DIR_MAGIC_TYPE;
+ return OK;
+ }
+
+ /* TM -- FIXME
+ * if r->filename does not contain a '/', the following passes a null
+ * pointer to getword, causing a SEGV ..
+ */
+
+ if (fn == NULL)
+ fn = r->filename;
+
+ /* Parse filename extensions, which can be in any order */
+ while ((ext = ap_getword(r->pool, &fn, '.')) && *ext) {
+ int found = 0;
+
+ /* Check for Content-Type */
+ if ((type = ap_table_get(conf->forced_types, ext))
+ || (type = ap_table_get(hash_buckets[hash(*ext)], ext))) {
+ r->content_type = type;
+ found = 1;
+ }
+
+ /* Check for Content-Language */
+ if ((type = ap_table_get(conf->language_types, ext))) {
+ const char **new;
+
+ r->content_language = type; /* back compat. only */
+ if (!r->content_languages)
+ r->content_languages = ap_make_array(r->pool, 2, sizeof(char *));
+ new = (const char **) ap_push_array(r->content_languages);
+ *new = type;
+ found = 1;
+ }
+
+ /* Check for Content-Encoding */
+ if ((type = ap_table_get(conf->encoding_types, ext))) {
+ if (!r->content_encoding)
+ r->content_encoding = type;
+ else
+ r->content_encoding = ap_pstrcat(r->pool, r->content_encoding,
+ ", ", type, NULL);
+ found = 1;
+ }
+
+ /* Check for a special handler, but not for proxy request */
+ if ((type = ap_table_get(conf->handlers, ext)) && !r->proxyreq) {
+ r->handler = type;
+ found = 1;
+ }
+
+ /* This is to deal with cases such as foo.gif.bak, which we want
+ * to not have a type. So if we find an unknown extension, we
+ * zap the type/language/encoding and reset the handler
+ */
+
+ if (!found) {
+ r->content_type = NULL;
+ r->content_language = NULL;
+ r->content_languages = NULL;
+ r->content_encoding = NULL;
+ r->handler = orighandler;
+ }
+
+ }
+
+ /* Set default language, if none was specified by the extensions
+ * and we have a DefaultLanguage setting in force
+ */
+
+ if (!r->content_languages && conf->default_language) {
+ const char **new;
+
+ r->content_language = conf->default_language; /* back compat. only */
+ if (!r->content_languages)
+ r->content_languages = ap_make_array(r->pool, 2, sizeof(char *));
+ new = (const char **) ap_push_array(r->content_languages);
+ *new = conf->default_language;
+ }
+
+ /* Check for overrides with ForceType/SetHandler */
+
+ if (conf->type && strcmp(conf->type, "none"))
+ r->content_type = conf->type;
+ if (conf->handler && strcmp(conf->handler, "none"))
+ r->handler = conf->handler;
+
+ if (!r->content_type)
+ return DECLINED;
+
+ return OK;
+}
+
+module MODULE_VAR_EXPORT mime_module =
+{
+ STANDARD_MODULE_STUFF,
+ init_mime, /* initializer */
+ create_mime_dir_config, /* dir config creator */
+ merge_mime_dir_configs, /* dir config merger */
+ NULL, /* server config */
+ NULL, /* merge server config */
+ mime_cmds, /* command table */
+ NULL, /* handlers */
+ NULL, /* filename translation */
+ NULL, /* check_user_id */
+ NULL, /* check auth */
+ NULL, /* check access */
+ find_ct, /* type_checker */
+ NULL, /* fixups */
+ NULL, /* logger */
+ NULL, /* header parser */
+ NULL, /* child_init */
+ NULL, /* child_exit */
+ NULL /* post read-request */
+};
diff --git a/modules/loggers/.indent.pro b/modules/loggers/.indent.pro
new file mode 100644
index 00000000000..a9fbe9f9a1f
--- /dev/null
+++ b/modules/loggers/.indent.pro
@@ -0,0 +1,54 @@
+-i4 -npsl -di0 -br -nce -d0 -cli0 -npcs -nfc1
+-TBUFF
+-TFILE
+-TTRANS
+-TUINT4
+-T_trans
+-Tallow_options_t
+-Tapache_sfio
+-Tarray_header
+-Tbool_int
+-Tbuf_area
+-Tbuff_struct
+-Tbuffy
+-Tcmd_how
+-Tcmd_parms
+-Tcommand_rec
+-Tcommand_struct
+-Tconn_rec
+-Tcore_dir_config
+-Tcore_server_config
+-Tdir_maker_func
+-Tevent
+-Tglobals_s
+-Thandler_func
+-Thandler_rec
+-Tjoblist_s
+-Tlisten_rec
+-Tmerger_func
+-Tmode_t
+-Tmodule
+-Tmodule_struct
+-Tmutex
+-Tn_long
+-Tother_child_rec
+-Toverrides_t
+-Tparent_score
+-Tpid_t
+-Tpiped_log
+-Tpool
+-Trequest_rec
+-Trequire_line
+-Trlim_t
+-Tscoreboard
+-Tsemaphore
+-Tserver_addr_rec
+-Tserver_rec
+-Tserver_rec_chain
+-Tshort_score
+-Ttable
+-Ttable_entry
+-Tthread
+-Tu_wide_int
+-Tvtime_t
+-Twide_int
diff --git a/modules/loggers/mod_log_config.c b/modules/loggers/mod_log_config.c
new file mode 100644
index 00000000000..fcdebcc4f95
--- /dev/null
+++ b/modules/loggers/mod_log_config.c
@@ -0,0 +1,1137 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+/*
+ * Modified by djm@va.pubnix.com:
+ * If no TransferLog is given explicitly, decline to log.
+ *
+ * This is module implements the TransferLog directive (same as the
+ * common log module), and additional directives, LogFormat and CustomLog.
+ *
+ *
+ * Syntax:
+ *
+ * TransferLog fn Logs transfers to fn in standard log format, unless
+ * a custom format is set with LogFormat
+ * LogFormat format Set a log format from TransferLog files
+ * CustomLog fn format
+ * Log to file fn with format given by the format
+ * argument
+ *
+ * CookieLog fn For backwards compatability with old Cookie
+ * logging module - now deprecated.
+ *
+ * There can be any number of TransferLog and CustomLog
+ * commands. Each request will be logged to _ALL_ the
+ * named files, in the appropriate format.
+ *
+ * If no TransferLog or CustomLog directive appears in a VirtualHost,
+ * the request will be logged to the log file(s) defined outside
+ * the virtual host section. If a TransferLog or CustomLog directive
+ * appears in the VirtualHost section, the log files defined outside
+ * the VirtualHost will _not_ be used. This makes this module compatable
+ * with the CLF and config log modules, where the use of TransferLog
+ * inside the VirtualHost section overrides its use outside.
+ *
+ * Examples:
+ *
+ * TransferLog logs/access_log
+ *
+ * LogFormat "... custom format ..."
+ * TransferLog log/virtual_only
+ * CustomLog log/virtual_useragents "%t %{user-agent}i"
+ *
+ *
+ * This will log using CLF to access_log any requests handled by the
+ * main server, while any requests to the virtual host will be logged
+ * with the "... custom format..." to virtual_only _AND_ using
+ * the custom user-agent log to virtual_useragents.
+ *
+ * Note that the NCSA referer and user-agent logs are easily added with
+ * CustomLog:
+ * CustomLog logs/referer "%{referer}i -> %U"
+ * CustomLog logs/agent "%{user-agent}i"
+ *
+ * RefererIgnore functionality can be obtained with conditional
+ * logging (SetEnvIf and CustomLog ... env=!VAR).
+ *
+ * But using this method allows much easier modification of the
+ * log format, e.g. to log hosts along with UA:
+ * CustomLog logs/referer "%{referer}i %U %h"
+ *
+ * The argument to LogFormat and CustomLog is a string, which can include
+ * literal characters copied into the log files, and '%' directives as
+ * follows:
+ *
+ * %...b: bytes sent, excluding HTTP headers.
+ * %...{FOOBAR}e: The contents of the environment variable FOOBAR
+ * %...f: filename
+ * %...h: remote host
+ * %...a: remote IP-address
+ * %...A: local IP-address
+ * %...{Foobar}i: The contents of Foobar: header line(s) in the request
+ * sent to the client.
+ * %...l: remote logname (from identd, if supplied)
+ * %...{Foobar}n: The contents of note "Foobar" from another module.
+ * %...{Foobar}o: The contents of Foobar: header line(s) in the reply.
+ * %...p: the port the request was served to
+ * %...P: the process ID of the child that serviced the request.
+ * %...r: first line of request
+ * %...s: status. For requests that got internally redirected, this
+ * is status of the *original* request --- %...>s for the last.
+ * %...t: time, in common log format time format
+ * %...{format}t: The time, in the form given by format, which should
+ * be in strftime(3) format.
+ * %...T: the time taken to serve the request, in seconds.
+ * %...u: remote user (from auth; may be bogus if return status (%s) is 401)
+ * %...U: the URL path requested.
+ * %...v: the configured name of the server (i.e. which virtual host?)
+ * %...V: the server name according to the UseCanonicalName setting
+ *
+ * The '...' can be nothing at all (e.g. "%h %u %r %s %b"), or it can
+ * indicate conditions for inclusion of the item (which will cause it
+ * to be replaced with '-' if the condition is not met). Note that
+ * there is no escaping performed on the strings from %r, %...i and
+ * %...o; some with long memories may remember that I thought this was
+ * a bad idea, once upon a time, and I'm still not comfortable with
+ * it, but it is difficult to see how to "do the right thing" with all
+ * of '%..i', unless we URL-escape everything and break with CLF.
+ *
+ * The forms of condition are a list of HTTP status codes, which may
+ * or may not be preceded by '!'. Thus, '%400,501{User-agent}i' logs
+ * User-agent: on 400 errors and 501 errors (Bad Request, Not
+ * Implemented) only; '%!200,304,302{Referer}i' logs Referer: on all
+ * requests which did *not* return some sort of normal status.
+ *
+ * The default LogFormat reproduces CLF; see below.
+ *
+ * The way this is supposed to work with virtual hosts is as follows:
+ * a virtual host can have its own LogFormat, or its own TransferLog.
+ * If it doesn't have its own LogFormat, it inherits from the main
+ * server. If it doesn't have its own TransferLog, it writes to the
+ * same descriptor (meaning the same process for "| ...").
+ *
+ * --- rst */
+
+#define DEFAULT_LOG_FORMAT "%h %l %u %t \"%r\" %>s %b"
+
+#include "httpd.h"
+#include "http_config.h"
+#include "http_core.h" /* For REMOTE_NAME */
+#include "http_log.h"
+#include
+
+module MODULE_VAR_EXPORT config_log_module;
+
+static int xfer_flags = (O_WRONLY | O_APPEND | O_CREAT);
+#if defined(OS2) || defined(WIN32)
+/* OS/2 dosen't support users and groups */
+static mode_t xfer_mode = (S_IREAD | S_IWRITE);
+#else
+static mode_t xfer_mode = (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
+#endif
+
+/* POSIX.1 defines PIPE_BUF as the maximum number of bytes that is
+ * guaranteed to be atomic when writing a pipe. And PIPE_BUF >= 512
+ * is guaranteed. So we'll just guess 512 in the event the system
+ * doesn't have this. Now, for file writes there is actually no limit,
+ * the entire write is atomic. Whether all systems implement this
+ * correctly is another question entirely ... so we'll just use PIPE_BUF
+ * because it's probably a good guess as to what is implemented correctly
+ * everywhere.
+ */
+#ifdef PIPE_BUF
+#define LOG_BUFSIZE PIPE_BUF
+#else
+#define LOG_BUFSIZE (512)
+#endif
+
+/*
+ * multi_log_state is our per-(virtual)-server configuration. We store
+ * an array of the logs we are going to use, each of type config_log_state.
+ * If a default log format is given by LogFormat, store in default_format
+ * (backward compat. with mod_log_config). We also store for each virtual
+ * server a pointer to the logs specified for the main server, so that if this
+ * vhost has no logs defined, we can use the main server's logs instead.
+ *
+ * So, for the main server, config_logs contains a list of the log files
+ * and server_config_logs in empty. For a vhost, server_config_logs
+ * points to the same array as config_logs in the main server, and
+ * config_logs points to the array of logs defined inside this vhost,
+ * which might be empty.
+ */
+
+typedef struct {
+ char *default_format_string;
+ array_header *default_format;
+ array_header *config_logs;
+ array_header *server_config_logs;
+ table *formats;
+} multi_log_state;
+
+/*
+ * config_log_state holds the status of a single log file. fname might
+ * be NULL, which means this module does no logging for this
+ * request. format might be NULL, in which case the default_format
+ * from the multi_log_state should be used, or if that is NULL as
+ * well, use the CLF. log_fd is -1 before the log file is opened and
+ * set to a valid fd after it is opened.
+ */
+
+typedef struct {
+ char *fname;
+ char *format_string;
+ array_header *format;
+ int log_fd;
+ char *condition_var;
+#ifdef BUFFERED_LOGS
+ int outcnt;
+ char outbuf[LOG_BUFSIZE];
+#endif
+} config_log_state;
+
+/*
+ * Format items...
+ * Note that many of these could have ap_sprintfs replaced with static buffers.
+ */
+
+typedef const char *(*item_key_func) (request_rec *, char *);
+
+typedef struct {
+ item_key_func func;
+ char *arg;
+ int condition_sense;
+ int want_orig;
+ array_header *conditions;
+} log_format_item;
+
+static char *format_integer(pool *p, int i)
+{
+ return ap_psprintf(p, "%d", i);
+}
+
+static char *pfmt(pool *p, int i)
+{
+ if (i <= 0) {
+ return "-";
+ }
+ else {
+ return format_integer(p, i);
+ }
+}
+
+static const char *constant_item(request_rec *dummy, char *stuff)
+{
+ return stuff;
+}
+
+static const char *log_remote_host(request_rec *r, char *a)
+{
+ return ap_get_remote_host(r->connection, r->per_dir_config,
+ REMOTE_NAME);
+}
+
+static const char *log_remote_address(request_rec *r, char *a)
+{
+ return r->connection->remote_ip;
+}
+
+static const char *log_local_address(request_rec *r, char *a)
+{
+ return r->connection->local_ip;
+}
+
+static const char *log_remote_logname(request_rec *r, char *a)
+{
+ return ap_get_remote_logname(r);
+}
+
+static const char *log_remote_user(request_rec *r, char *a)
+{
+ char *rvalue = r->connection->user;
+
+ if (rvalue == NULL) {
+ rvalue = "-";
+ }
+ else if (strlen(rvalue) == 0) {
+ rvalue = "\"\"";
+ }
+ return rvalue;
+}
+
+static const char *log_request_line(request_rec *r, char *a)
+{
+ /* NOTE: If the original request contained a password, we
+ * re-write the request line here to contain XXXXXX instead:
+ * (note the truncation before the protocol string for HTTP/0.9 requests)
+ * (note also that r->the_request contains the unmodified request)
+ */
+ return (r->parsed_uri.password) ? ap_pstrcat(r->pool, r->method, " ",
+ ap_unparse_uri_components(r->pool, &r->parsed_uri, 0),
+ r->assbackwards ? NULL : " ", r->protocol, NULL)
+ : r->the_request;
+}
+
+static const char *log_request_file(request_rec *r, char *a)
+{
+ return r->filename;
+}
+static const char *log_request_uri(request_rec *r, char *a)
+{
+ return r->uri;
+}
+static const char *log_status(request_rec *r, char *a)
+{
+ return pfmt(r->pool, r->status);
+}
+
+static const char *log_bytes_sent(request_rec *r, char *a)
+{
+ if (!r->sent_bodyct) {
+ return "-";
+ }
+ else {
+ long int bs;
+ ap_bgetopt(r->connection->client, BO_BYTECT, &bs);
+ return ap_psprintf(r->pool, "%ld", bs);
+ }
+}
+
+static const char *log_header_in(request_rec *r, char *a)
+{
+ return ap_table_get(r->headers_in, a);
+}
+
+static const char *log_header_out(request_rec *r, char *a)
+{
+ const char *cp = ap_table_get(r->headers_out, a);
+ if (!strcasecmp(a, "Content-type") && r->content_type) {
+ cp = r->content_type;
+ }
+ if (cp) {
+ return cp;
+ }
+ return ap_table_get(r->err_headers_out, a);
+}
+
+static const char *log_note(request_rec *r, char *a)
+{
+ return ap_table_get(r->notes, a);
+}
+static const char *log_env_var(request_rec *r, char *a)
+{
+ return ap_table_get(r->subprocess_env, a);
+}
+
+static const char *log_request_time(request_rec *r, char *a)
+{
+ int timz;
+ struct tm *t;
+ char tstr[MAX_STRING_LEN];
+
+ t = ap_get_gmtoff(&timz);
+
+ if (a && *a) { /* Custom format */
+ strftime(tstr, MAX_STRING_LEN, a, t);
+ }
+ else { /* CLF format */
+ char sign = (timz < 0 ? '-' : '+');
+
+ if (timz < 0) {
+ timz = -timz;
+ }
+ ap_snprintf(tstr, sizeof(tstr), "[%02d/%s/%d:%02d:%02d:%02d %c%.2d%.2d]",
+ t->tm_mday, ap_month_snames[t->tm_mon], t->tm_year+1900,
+ t->tm_hour, t->tm_min, t->tm_sec,
+ sign, timz / 60, timz % 60);
+ }
+
+ return ap_pstrdup(r->pool, tstr);
+}
+
+static const char *log_request_duration(request_rec *r, char *a)
+{
+ return ap_psprintf(r->pool, "%ld", time(NULL) - r->request_time);
+}
+
+/* These next two routines use the canonical name:port so that log
+ * parsers don't need to duplicate all the vhost parsing crud.
+ */
+static const char *log_virtual_host(request_rec *r, char *a)
+{
+ return r->server->server_hostname;
+}
+
+static const char *log_server_port(request_rec *r, char *a)
+{
+ return ap_psprintf(r->pool, "%u",
+ r->server->port ? r->server->port : ap_default_port(r));
+}
+
+/* This respects the setting of UseCanonicalName so that
+ * the dynamic mass virtual hosting trick works better.
+ */
+static const char *log_server_name(request_rec *r, char *a)
+{
+ return ap_get_server_name(r);
+}
+
+static const char *log_child_pid(request_rec *r, char *a)
+{
+ return ap_psprintf(r->pool, "%ld", (long) getpid());
+}
+
+/*****************************************************************
+ *
+ * Parsing the log format string
+ */
+
+static struct log_item_list {
+ char ch;
+ item_key_func func;
+ int want_orig_default;
+} log_item_keys[] = {
+
+ {
+ 'h', log_remote_host, 0
+ },
+ {
+ 'a', log_remote_address, 0
+ },
+ {
+ 'A', log_local_address, 0
+ },
+ {
+ 'l', log_remote_logname, 0
+ },
+ {
+ 'u', log_remote_user, 0
+ },
+ {
+ 't', log_request_time, 0
+ },
+ {
+ 'T', log_request_duration, 1
+ },
+ {
+ 'r', log_request_line, 1
+ },
+ {
+ 'f', log_request_file, 0
+ },
+ {
+ 'U', log_request_uri, 1
+ },
+ {
+ 's', log_status, 1
+ },
+ {
+ 'b', log_bytes_sent, 0
+ },
+ {
+ 'i', log_header_in, 0
+ },
+ {
+ 'o', log_header_out, 0
+ },
+ {
+ 'n', log_note, 0
+ },
+ {
+ 'e', log_env_var, 0
+ },
+ {
+ 'V', log_server_name, 0
+ },
+ {
+ 'v', log_virtual_host, 0
+ },
+ {
+ 'p', log_server_port, 0
+ },
+ {
+ 'P', log_child_pid, 0
+ },
+ {
+ '\0'
+ }
+};
+
+static struct log_item_list *find_log_func(char k)
+{
+ int i;
+
+ for (i = 0; log_item_keys[i].ch; ++i)
+ if (k == log_item_keys[i].ch) {
+ return &log_item_keys[i];
+ }
+
+ return NULL;
+}
+
+static char *parse_log_misc_string(pool *p, log_format_item *it,
+ const char **sa)
+{
+ const char *s;
+ char *d;
+
+ it->func = constant_item;
+ it->conditions = NULL;
+
+ s = *sa;
+ while (*s && *s != '%') {
+ s++;
+ }
+ /*
+ * This might allocate a few chars extra if there's a backslash
+ * escape in the format string.
+ */
+ it->arg = ap_palloc(p, s - *sa + 1);
+
+ d = it->arg;
+ s = *sa;
+ while (*s && *s != '%') {
+ if (*s != '\\') {
+ *d++ = *s++;
+ }
+ else {
+ s++;
+ switch (*s) {
+ case '\\':
+ *d++ = '\\';
+ s++;
+ break;
+ case 'n':
+ *d++ = '\n';
+ s++;
+ break;
+ case 't':
+ *d++ = '\t';
+ s++;
+ break;
+ default:
+ /* copy verbatim */
+ *d++ = '\\';
+ /*
+ * Allow the loop to deal with this *s in the normal
+ * fashion so that it handles end of string etc.
+ * properly.
+ */
+ break;
+ }
+ }
+ }
+ *d = '\0';
+
+ *sa = s;
+ return NULL;
+}
+
+static char *parse_log_item(pool *p, log_format_item *it, const char **sa)
+{
+ const char *s = *sa;
+
+ if (*s != '%') {
+ return parse_log_misc_string(p, it, sa);
+ }
+
+ ++s;
+ it->condition_sense = 0;
+ it->conditions = NULL;
+ it->want_orig = -1;
+ it->arg = ""; /* For safety's sake... */
+
+ while (*s) {
+ int i;
+ struct log_item_list *l;
+
+ switch (*s) {
+ case '!':
+ ++s;
+ it->condition_sense = !it->condition_sense;
+ break;
+
+ case '<':
+ ++s;
+ it->want_orig = 1;
+ break;
+
+ case '>':
+ ++s;
+ it->want_orig = 0;
+ break;
+
+ case ',':
+ ++s;
+ break;
+
+ case '{':
+ ++s;
+ it->arg = ap_getword(p, &s, '}');
+ break;
+
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ i = *s - '0';
+ while (ap_isdigit(*++s)) {
+ i = i * 10 + (*s) - '0';
+ }
+ if (!it->conditions) {
+ it->conditions = ap_make_array(p, 4, sizeof(int));
+ }
+ *(int *) ap_push_array(it->conditions) = i;
+ break;
+
+ default:
+ l = find_log_func(*s++);
+ if (!l) {
+ char dummy[2];
+
+ dummy[0] = s[-1];
+ dummy[1] = '\0';
+ return ap_pstrcat(p, "Unrecognized LogFormat directive %",
+ dummy, NULL);
+ }
+ it->func = l->func;
+ if (it->want_orig == -1) {
+ it->want_orig = l->want_orig_default;
+ }
+ *sa = s;
+ return NULL;
+ }
+ }
+
+ return "Ran off end of LogFormat parsing args to some directive";
+}
+
+static array_header *parse_log_string(pool *p, const char *s, const char **err)
+{
+ array_header *a = ap_make_array(p, 30, sizeof(log_format_item));
+ char *res;
+
+ while (*s) {
+ if ((res = parse_log_item(p, (log_format_item *) ap_push_array(a), &s))) {
+ *err = res;
+ return NULL;
+ }
+ }
+
+ s = "\n";
+ parse_log_item(p, (log_format_item *) ap_push_array(a), &s);
+ return a;
+}
+
+/*****************************************************************
+ *
+ * Actually logging.
+ */
+
+static const char *process_item(request_rec *r, request_rec *orig,
+ log_format_item *item)
+{
+ const char *cp;
+
+ /* First, see if we need to process this thing at all... */
+
+ if (item->conditions && item->conditions->nelts != 0) {
+ int i;
+ int *conds = (int *) item->conditions->elts;
+ int in_list = 0;
+
+ for (i = 0; i < item->conditions->nelts; ++i) {
+ if (r->status == conds[i]) {
+ in_list = 1;
+ break;
+ }
+ }
+
+ if ((item->condition_sense && in_list)
+ || (!item->condition_sense && !in_list)) {
+ return "-";
+ }
+ }
+
+ /* We do. Do it... */
+
+ cp = (*item->func) (item->want_orig ? orig : r, item->arg);
+ return cp ? cp : "-";
+}
+
+#ifdef BUFFERED_LOGS
+static void flush_log(config_log_state *cls)
+{
+ if (cls->outcnt && cls->log_fd != -1) {
+ write(cls->log_fd, cls->outbuf, cls->outcnt);
+ cls->outcnt = 0;
+ }
+}
+#endif
+
+static int config_log_transaction(request_rec *r, config_log_state *cls,
+ array_header *default_format)
+{
+ log_format_item *items;
+ char *str, *s;
+ const char **strs;
+ int *strl;
+ request_rec *orig;
+ int i;
+ int len = 0;
+ array_header *format;
+ char *envar;
+
+ if (cls->fname == NULL) {
+ return DECLINED;
+ }
+
+ /*
+ * See if we've got any conditional envariable-controlled logging decisions
+ * to make.
+ */
+ if (cls->condition_var != NULL) {
+ envar = cls->condition_var;
+ if (*envar != '!') {
+ if (ap_table_get(r->subprocess_env, envar) == NULL) {
+ return DECLINED;
+ }
+ }
+ else {
+ if (ap_table_get(r->subprocess_env, &envar[1]) != NULL) {
+ return DECLINED;
+ }
+ }
+ }
+
+ format = cls->format ? cls->format : default_format;
+
+ strs = ap_palloc(r->pool, sizeof(char *) * (format->nelts));
+ strl = ap_palloc(r->pool, sizeof(int) * (format->nelts));
+ items = (log_format_item *) format->elts;
+
+ orig = r;
+ while (orig->prev) {
+ orig = orig->prev;
+ }
+ while (r->next) {
+ r = r->next;
+ }
+
+ for (i = 0; i < format->nelts; ++i) {
+ strs[i] = process_item(r, orig, &items[i]);
+ }
+
+ for (i = 0; i < format->nelts; ++i) {
+ len += strl[i] = strlen(strs[i]);
+ }
+
+#ifdef BUFFERED_LOGS
+ if (len + cls->outcnt > LOG_BUFSIZE) {
+ flush_log(cls);
+ }
+ if (len >= LOG_BUFSIZE) {
+ str = ap_palloc(r->pool, len + 1);
+ for (i = 0, s = str; i < format->nelts; ++i) {
+ memcpy(s, strs[i], strl[i]);
+ s += strl[i];
+ }
+ write(cls->log_fd, str, len);
+ }
+ else {
+ for (i = 0, s = &cls->outbuf[cls->outcnt]; i < format->nelts; ++i) {
+ memcpy(s, strs[i], strl[i]);
+ s += strl[i];
+ }
+ cls->outcnt += len;
+ }
+#else
+ str = ap_palloc(r->pool, len + 1);
+
+ for (i = 0, s = str; i < format->nelts; ++i) {
+ memcpy(s, strs[i], strl[i]);
+ s += strl[i];
+ }
+
+ write(cls->log_fd, str, len);
+#endif
+
+ return OK;
+}
+
+static int multi_log_transaction(request_rec *r)
+{
+ multi_log_state *mls = ap_get_module_config(r->server->module_config,
+ &config_log_module);
+ config_log_state *clsarray;
+ int i;
+
+ /*
+ * Log this transaction..
+ */
+ if (mls->config_logs->nelts) {
+ clsarray = (config_log_state *) mls->config_logs->elts;
+ for (i = 0; i < mls->config_logs->nelts; ++i) {
+ config_log_state *cls = &clsarray[i];
+
+ config_log_transaction(r, cls, mls->default_format);
+ }
+ }
+ else if (mls->server_config_logs) {
+ clsarray = (config_log_state *) mls->server_config_logs->elts;
+ for (i = 0; i < mls->server_config_logs->nelts; ++i) {
+ config_log_state *cls = &clsarray[i];
+
+ config_log_transaction(r, cls, mls->default_format);
+ }
+ }
+
+ return OK;
+}
+
+/*****************************************************************
+ *
+ * Module glue...
+ */
+
+static void *make_config_log_state(pool *p, server_rec *s)
+{
+ multi_log_state *mls;
+
+ mls = (multi_log_state *) ap_palloc(p, sizeof(multi_log_state));
+ mls->config_logs = ap_make_array(p, 1, sizeof(config_log_state));
+ mls->default_format_string = NULL;
+ mls->default_format = NULL;
+ mls->server_config_logs = NULL;
+ mls->formats = ap_make_table(p, 4);
+ ap_table_setn(mls->formats, "CLF", DEFAULT_LOG_FORMAT);
+
+ return mls;
+}
+
+/*
+ * Use the merger to simply add a pointer from the vhost log state
+ * to the log of logs specified for the non-vhost configuration. Make sure
+ * vhosts inherit any globally-defined format names.
+ */
+
+static void *merge_config_log_state(pool *p, void *basev, void *addv)
+{
+ multi_log_state *base = (multi_log_state *) basev;
+ multi_log_state *add = (multi_log_state *) addv;
+
+ add->server_config_logs = base->config_logs;
+ if (!add->default_format) {
+ add->default_format_string = base->default_format_string;
+ add->default_format = base->default_format;
+ }
+ add->formats = ap_overlay_tables(p, base->formats, add->formats);
+
+ return add;
+}
+
+/*
+ * Set the default logfile format, or define a nickname for a format string.
+ */
+static const char *log_format(cmd_parms *cmd, void *dummy, char *fmt,
+ char *name)
+{
+ const char *err_string = NULL;
+ multi_log_state *mls = ap_get_module_config(cmd->server->module_config,
+ &config_log_module);
+
+ /*
+ * If we were given two arguments, the second is a name to be given to the
+ * format. This syntax just defines the nickname - it doesn't actually
+ * make the format the default.
+ */
+ if (name != NULL) {
+ parse_log_string(cmd->pool, fmt, &err_string);
+ if (err_string == NULL) {
+ ap_table_setn(mls->formats, name, fmt);
+ }
+ }
+ else {
+ mls->default_format_string = fmt;
+ mls->default_format = parse_log_string(cmd->pool, fmt, &err_string);
+ }
+ return err_string;
+}
+
+
+static const char *add_custom_log(cmd_parms *cmd, void *dummy, char *fn,
+ char *fmt, char *envclause)
+{
+ const char *err_string = NULL;
+ multi_log_state *mls = ap_get_module_config(cmd->server->module_config,
+ &config_log_module);
+ config_log_state *cls;
+
+ cls = (config_log_state *) ap_push_array(mls->config_logs);
+ cls->condition_var = NULL;
+ if (envclause != NULL) {
+ if (strncasecmp(envclause, "env=", 4) != 0) {
+ return "error in condition clause";
+ }
+ if ((envclause[4] == '\0')
+ || ((envclause[4] == '!') && (envclause[5] == '\0'))) {
+ return "missing environment variable name";
+ }
+ cls->condition_var = ap_pstrdup(cmd->pool, &envclause[4]);
+ }
+
+ cls->fname = fn;
+ cls->format_string = fmt;
+ if (fmt == NULL) {
+ cls->format = NULL;
+ }
+ else {
+ cls->format = parse_log_string(cmd->pool, fmt, &err_string);
+ }
+ cls->log_fd = -1;
+
+ return err_string;
+}
+
+static const char *set_transfer_log(cmd_parms *cmd, void *dummy, char *fn)
+{
+ return add_custom_log(cmd, dummy, fn, NULL, NULL);
+}
+
+static const char *set_cookie_log(cmd_parms *cmd, void *dummy, char *fn)
+{
+ return add_custom_log(cmd, dummy, fn, "%{Cookie}n \"%r\" %t", NULL);
+}
+
+static const command_rec config_log_cmds[] =
+{
+ {"CustomLog", add_custom_log, NULL, RSRC_CONF, TAKE23,
+ "a file name, a custom log format string or format name, "
+ "and an optional \"env=\" clause (see docs)"},
+ {"TransferLog", set_transfer_log, NULL, RSRC_CONF, TAKE1,
+ "the filename of the access log"},
+ {"LogFormat", log_format, NULL, RSRC_CONF, TAKE12,
+ "a log format string (see docs) and an optional format name"},
+ {"CookieLog", set_cookie_log, NULL, RSRC_CONF, TAKE1,
+ "the filename of the cookie log"},
+ {NULL}
+};
+
+static config_log_state *open_config_log(server_rec *s, pool *p,
+ config_log_state *cls,
+ array_header *default_format)
+{
+ if (cls->log_fd > 0) {
+ return cls; /* virtual config shared w/main server */
+ }
+
+ if (cls->fname == NULL) {
+ return cls; /* Leave it NULL to decline. */
+ }
+
+ if (*cls->fname == '|') {
+ piped_log *pl;
+
+ pl = ap_open_piped_log(p, cls->fname + 1);
+ if (pl == NULL) {
+ exit(1);
+ }
+ cls->log_fd = ap_piped_log_write_fd(pl);
+ }
+ else {
+ char *fname = ap_server_root_relative(p, cls->fname);
+ if ((cls->log_fd = ap_popenf(p, fname, xfer_flags, xfer_mode)) < 0) {
+ ap_log_error(APLOG_MARK, APLOG_ERR, s,
+ "could not open transfer log file %s.", fname);
+ exit(1);
+ }
+ }
+#ifdef BUFFERED_LOGS
+ cls->outcnt = 0;
+#endif
+
+ return cls;
+}
+
+static config_log_state *open_multi_logs(server_rec *s, pool *p)
+{
+ int i;
+ multi_log_state *mls = ap_get_module_config(s->module_config,
+ &config_log_module);
+ config_log_state *clsarray;
+ const char *dummy;
+ const char *format;
+
+ if (mls->default_format_string) {
+ format = ap_table_get(mls->formats, mls->default_format_string);
+ if (format) {
+ mls->default_format = parse_log_string(p, format, &dummy);
+ }
+ }
+
+ if (!mls->default_format) {
+ mls->default_format = parse_log_string(p, DEFAULT_LOG_FORMAT, &dummy);
+ }
+
+ if (mls->config_logs->nelts) {
+ clsarray = (config_log_state *) mls->config_logs->elts;
+ for (i = 0; i < mls->config_logs->nelts; ++i) {
+ config_log_state *cls = &clsarray[i];
+
+ if (cls->format_string) {
+ format = ap_table_get(mls->formats, cls->format_string);
+ if (format) {
+ cls->format = parse_log_string(p, format, &dummy);
+ }
+ }
+
+ cls = open_config_log(s, p, cls, mls->default_format);
+ }
+ }
+ else if (mls->server_config_logs) {
+ clsarray = (config_log_state *) mls->server_config_logs->elts;
+ for (i = 0; i < mls->server_config_logs->nelts; ++i) {
+ config_log_state *cls = &clsarray[i];
+
+ if (cls->format_string) {
+ format = ap_table_get(mls->formats, cls->format_string);
+ if (format) {
+ cls->format = parse_log_string(p, format, &dummy);
+ }
+ }
+
+ cls = open_config_log(s, p, cls, mls->default_format);
+ }
+ }
+
+ return NULL;
+}
+
+static void init_config_log(server_rec *s, pool *p)
+{
+ /* First, do "physical" server, which gets default log fd and format
+ * for the virtual servers, if they don't override...
+ */
+
+ open_multi_logs(s, p);
+
+ /* Then, virtual servers */
+
+ for (s = s->next; s; s = s->next) {
+ open_multi_logs(s, p);
+ }
+}
+
+#ifdef BUFFERED_LOGS
+static void flush_all_logs(server_rec *s, pool *p)
+{
+ multi_log_state *mls;
+ array_header *log_list;
+ config_log_state *clsarray;
+ int i;
+
+ for (; s; s = s->next) {
+ mls = ap_get_module_config(s->module_config, &config_log_module);
+ log_list = NULL;
+ if (mls->config_logs->nelts) {
+ log_list = mls->config_logs;
+ }
+ else if (mls->server_config_logs) {
+ log_list = mls->server_config_logs;
+ }
+ if (log_list) {
+ clsarray = (config_log_state *) log_list->elts;
+ for (i = 0; i < log_list->nelts; ++i) {
+ flush_log(&clsarray[i]);
+ }
+ }
+ }
+}
+#endif
+
+module MODULE_VAR_EXPORT config_log_module =
+{
+ STANDARD_MODULE_STUFF,
+ init_config_log, /* initializer */
+ NULL, /* create per-dir config */
+ NULL, /* merge per-dir config */
+ make_config_log_state, /* server config */
+ merge_config_log_state, /* merge server config */
+ config_log_cmds, /* command table */
+ NULL, /* handlers */
+ NULL, /* filename translation */
+ NULL, /* check_user_id */
+ NULL, /* check auth */
+ NULL, /* check access */
+ NULL, /* type_checker */
+ NULL, /* fixups */
+ multi_log_transaction, /* logger */
+ NULL, /* header parser */
+ NULL, /* child_init */
+#ifdef BUFFERED_LOGS
+ flush_all_logs, /* child_exit */
+#else
+ NULL,
+#endif
+ NULL /* post read-request */
+};
diff --git a/modules/mappers/.indent.pro b/modules/mappers/.indent.pro
new file mode 100644
index 00000000000..a9fbe9f9a1f
--- /dev/null
+++ b/modules/mappers/.indent.pro
@@ -0,0 +1,54 @@
+-i4 -npsl -di0 -br -nce -d0 -cli0 -npcs -nfc1
+-TBUFF
+-TFILE
+-TTRANS
+-TUINT4
+-T_trans
+-Tallow_options_t
+-Tapache_sfio
+-Tarray_header
+-Tbool_int
+-Tbuf_area
+-Tbuff_struct
+-Tbuffy
+-Tcmd_how
+-Tcmd_parms
+-Tcommand_rec
+-Tcommand_struct
+-Tconn_rec
+-Tcore_dir_config
+-Tcore_server_config
+-Tdir_maker_func
+-Tevent
+-Tglobals_s
+-Thandler_func
+-Thandler_rec
+-Tjoblist_s
+-Tlisten_rec
+-Tmerger_func
+-Tmode_t
+-Tmodule
+-Tmodule_struct
+-Tmutex
+-Tn_long
+-Tother_child_rec
+-Toverrides_t
+-Tparent_score
+-Tpid_t
+-Tpiped_log
+-Tpool
+-Trequest_rec
+-Trequire_line
+-Trlim_t
+-Tscoreboard
+-Tsemaphore
+-Tserver_addr_rec
+-Tserver_rec
+-Tserver_rec_chain
+-Tshort_score
+-Ttable
+-Ttable_entry
+-Tthread
+-Tu_wide_int
+-Tvtime_t
+-Twide_int
diff --git a/modules/mappers/mod_actions.c b/modules/mappers/mod_actions.c
new file mode 100644
index 00000000000..5906ee4c43a
--- /dev/null
+++ b/modules/mappers/mod_actions.c
@@ -0,0 +1,232 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+/*
+ * mod_actions.c: executes scripts based on MIME type or HTTP method
+ *
+ * by Alexei Kosut; based on mod_cgi.c, mod_mime.c and mod_includes.c,
+ * adapted by rst from original NCSA code by Rob McCool
+ *
+ * Usage instructions:
+ *
+ * Action mime/type /cgi-bin/script
+ *
+ * will activate /cgi-bin/script when a file of content type mime/type is
+ * requested. It sends the URL and file path of the requested document using
+ * the standard CGI PATH_INFO and PATH_TRANSLATED environment variables.
+ *
+ * Script PUT /cgi-bin/script
+ *
+ * will activate /cgi-bin/script when a request is received with the
+ * HTTP method "PUT". The available method names are defined in httpd.h.
+ * If the method is GET, the script will only be activated if the requested
+ * URI includes query information (stuff after a ?-mark).
+ */
+
+#include "httpd.h"
+#include "http_config.h"
+#include "http_request.h"
+#include "http_core.h"
+#include "http_protocol.h"
+#include "http_main.h"
+#include "http_log.h"
+#include "util_script.h"
+
+typedef struct {
+ table *action_types; /* Added with Action... */
+ char *scripted[METHODS]; /* Added with Script... */
+} action_dir_config;
+
+module action_module;
+
+static void *create_action_dir_config(pool *p, char *dummy)
+{
+ action_dir_config *new =
+ (action_dir_config *) ap_palloc(p, sizeof(action_dir_config));
+
+ new->action_types = ap_make_table(p, 4);
+ memset(new->scripted, 0, sizeof(new->scripted));
+
+ return new;
+}
+
+static void *merge_action_dir_configs(pool *p, void *basev, void *addv)
+{
+ action_dir_config *base = (action_dir_config *) basev;
+ action_dir_config *add = (action_dir_config *) addv;
+ action_dir_config *new = (action_dir_config *) ap_palloc(p,
+ sizeof(action_dir_config));
+ int i;
+
+ new->action_types = ap_overlay_tables(p, add->action_types,
+ base->action_types);
+
+ for (i = 0; i < METHODS; ++i) {
+ new->scripted[i] = add->scripted[i] ? add->scripted[i]
+ : base->scripted[i];
+ }
+ return new;
+}
+
+static const char *add_action(cmd_parms *cmd, action_dir_config * m, char *type,
+ char *script)
+{
+ ap_table_setn(m->action_types, type, script);
+ return NULL;
+}
+
+static const char *set_script(cmd_parms *cmd, action_dir_config * m,
+ char *method, char *script)
+{
+ int methnum;
+
+ methnum = ap_method_number_of(method);
+ if (methnum == M_TRACE)
+ return "TRACE not allowed for Script";
+ else if (methnum == M_INVALID)
+ return "Unknown method type for Script";
+ else
+ m->scripted[methnum] = script;
+
+ return NULL;
+}
+
+static const command_rec action_cmds[] =
+{
+ {"Action", add_action, NULL, OR_FILEINFO, TAKE2,
+ "a media type followed by a script name"},
+ {"Script", set_script, NULL, ACCESS_CONF | RSRC_CONF, TAKE2,
+ "a method followed by a script name"},
+ {NULL}
+};
+
+static int action_handler(request_rec *r)
+{
+ action_dir_config *conf = (action_dir_config *)
+ ap_get_module_config(r->per_dir_config, &action_module);
+ const char *t, *action = r->handler ? r->handler : r->content_type;
+ const char *script;
+ int i;
+
+ /* Set allowed stuff */
+ for (i = 0; i < METHODS; ++i) {
+ if (conf->scripted[i])
+ r->allowed |= (1 << i);
+ }
+
+ /* First, check for the method-handling scripts */
+ if (r->method_number == M_GET) {
+ if (r->args)
+ script = conf->scripted[M_GET];
+ else
+ script = NULL;
+ }
+ else {
+ script = conf->scripted[r->method_number];
+ }
+
+ /* Check for looping, which can happen if the CGI script isn't */
+ if (script && r->prev && r->prev->prev)
+ return DECLINED;
+
+ /* Second, check for actions (which override the method scripts) */
+ if ((t = ap_table_get(conf->action_types,
+ action ? action : ap_default_type(r)))) {
+ script = t;
+ if (r->finfo.st_mode == 0) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "File does not exist: %s", r->filename);
+ return NOT_FOUND;
+ }
+ }
+
+ if (script == NULL)
+ return DECLINED;
+
+ ap_internal_redirect_handler(ap_pstrcat(r->pool, script, ap_escape_uri(r->pool,
+ r->uri), r->args ? "?" : NULL, r->args, NULL), r);
+ return OK;
+}
+
+static const handler_rec action_handlers[] =
+{
+ {"*/*", action_handler},
+ {NULL}
+};
+
+module action_module =
+{
+ STANDARD_MODULE_STUFF,
+ NULL, /* initializer */
+ create_action_dir_config, /* dir config creater */
+ merge_action_dir_configs, /* dir merger --- default is to override */
+ NULL, /* server config */
+ NULL, /* merge server config */
+ action_cmds, /* command table */
+ action_handlers, /* handlers */
+ NULL, /* filename translation */
+ NULL, /* check_user_id */
+ NULL, /* check auth */
+ NULL, /* check access */
+ NULL, /* type_checker */
+ NULL, /* fixups */
+ NULL, /* logger */
+ NULL, /* header parser */
+ NULL, /* child_init */
+ NULL, /* child_exit */
+ NULL /* post read-request */
+};
diff --git a/modules/mappers/mod_alias.c b/modules/mappers/mod_alias.c
new file mode 100644
index 00000000000..f92d982d233
--- /dev/null
+++ b/modules/mappers/mod_alias.c
@@ -0,0 +1,418 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+/*
+ * http_alias.c: Stuff for dealing with directory aliases
+ *
+ * Original by Rob McCool, rewritten in succession by David Robinson
+ * and rst.
+ *
+ */
+
+#include "httpd.h"
+#include "http_config.h"
+
+typedef struct {
+ char *real;
+ char *fake;
+ char *handler;
+ regex_t *regexp;
+ int redir_status; /* 301, 302, 303, 410, etc */
+} alias_entry;
+
+typedef struct {
+ array_header *aliases;
+ array_header *redirects;
+} alias_server_conf;
+
+typedef struct {
+ array_header *redirects;
+} alias_dir_conf;
+
+module MODULE_VAR_EXPORT alias_module;
+
+static void *create_alias_config(pool *p, server_rec *s)
+{
+ alias_server_conf *a =
+ (alias_server_conf *) ap_pcalloc(p, sizeof(alias_server_conf));
+
+ a->aliases = ap_make_array(p, 20, sizeof(alias_entry));
+ a->redirects = ap_make_array(p, 20, sizeof(alias_entry));
+ return a;
+}
+
+static void *create_alias_dir_config(pool *p, char *d)
+{
+ alias_dir_conf *a =
+ (alias_dir_conf *) ap_pcalloc(p, sizeof(alias_dir_conf));
+ a->redirects = ap_make_array(p, 2, sizeof(alias_entry));
+ return a;
+}
+
+static void *merge_alias_config(pool *p, void *basev, void *overridesv)
+{
+ alias_server_conf *a =
+ (alias_server_conf *) ap_pcalloc(p, sizeof(alias_server_conf));
+ alias_server_conf *base = (alias_server_conf *) basev, *overrides = (alias_server_conf *) overridesv;
+
+ a->aliases = ap_append_arrays(p, overrides->aliases, base->aliases);
+ a->redirects = ap_append_arrays(p, overrides->redirects, base->redirects);
+ return a;
+}
+
+static void *merge_alias_dir_config(pool *p, void *basev, void *overridesv)
+{
+ alias_dir_conf *a =
+ (alias_dir_conf *) ap_pcalloc(p, sizeof(alias_dir_conf));
+ alias_dir_conf *base = (alias_dir_conf *) basev, *overrides = (alias_dir_conf *) overridesv;
+ a->redirects = ap_append_arrays(p, overrides->redirects, base->redirects);
+ return a;
+}
+
+static const char *add_alias_internal(cmd_parms *cmd, void *dummy, char *f, char *r,
+ int use_regex)
+{
+ server_rec *s = cmd->server;
+ alias_server_conf *conf =
+ (alias_server_conf *) ap_get_module_config(s->module_config, &alias_module);
+ alias_entry *new = ap_push_array(conf->aliases);
+
+ /* XX r can NOT be relative to DocumentRoot here... compat bug. */
+
+ if (use_regex) {
+ new->regexp = ap_pregcomp(cmd->pool, f, REG_EXTENDED);
+ if (new->regexp == NULL)
+ return "Regular expression could not be compiled.";
+ }
+
+ new->fake = f;
+ new->real = r;
+ new->handler = cmd->info;
+
+ return NULL;
+}
+
+static const char *add_alias(cmd_parms *cmd, void *dummy, char *f, char *r)
+{
+ return add_alias_internal(cmd, dummy, f, r, 0);
+}
+
+static const char *add_alias_regex(cmd_parms *cmd, void *dummy, char *f, char *r)
+{
+ return add_alias_internal(cmd, dummy, f, r, 1);
+}
+
+static const char *add_redirect_internal(cmd_parms *cmd, alias_dir_conf * dirconf,
+ char *arg1, char *arg2, char *arg3,
+ int use_regex)
+{
+ alias_entry *new;
+ server_rec *s = cmd->server;
+ alias_server_conf *serverconf =
+ (alias_server_conf *) ap_get_module_config(s->module_config, &alias_module);
+ int status = (int) (long) cmd->info;
+ regex_t *r = NULL;
+ char *f = arg2;
+ char *url = arg3;
+
+ if (!strcasecmp(arg1, "gone"))
+ status = HTTP_GONE;
+ else if (!strcasecmp(arg1, "permanent"))
+ status = HTTP_MOVED_PERMANENTLY;
+ else if (!strcasecmp(arg1, "temp"))
+ status = HTTP_MOVED_TEMPORARILY;
+ else if (!strcasecmp(arg1, "seeother"))
+ status = HTTP_SEE_OTHER;
+ else if (ap_isdigit(*arg1))
+ status = atoi(arg1);
+ else {
+ f = arg1;
+ url = arg2;
+ }
+
+ if (use_regex) {
+ r = ap_pregcomp(cmd->pool, f, REG_EXTENDED);
+ if (r == NULL)
+ return "Regular expression could not be compiled.";
+ }
+
+ if (ap_is_HTTP_REDIRECT(status)) {
+ if (!url)
+ return "URL to redirect to is missing";
+ if (!use_regex && !ap_is_url(url))
+ return "Redirect to non-URL";
+ }
+ else {
+ if (url)
+ return "Redirect URL not valid for this status";
+ }
+
+ if (cmd->path)
+ new = ap_push_array(dirconf->redirects);
+ else
+ new = ap_push_array(serverconf->redirects);
+
+ new->fake = f;
+ new->real = url;
+ new->regexp = r;
+ new->redir_status = status;
+ return NULL;
+}
+
+static const char *add_redirect(cmd_parms *cmd, alias_dir_conf * dirconf, char *arg1,
+ char *arg2, char *arg3)
+{
+ return add_redirect_internal(cmd, dirconf, arg1, arg2, arg3, 0);
+}
+
+static const char *add_redirect_regex(cmd_parms *cmd, alias_dir_conf * dirconf,
+ char *arg1, char *arg2, char *arg3)
+{
+ return add_redirect_internal(cmd, dirconf, arg1, arg2, arg3, 1);
+}
+
+static const command_rec alias_cmds[] =
+{
+ {"Alias", add_alias, NULL, RSRC_CONF, TAKE2,
+ "a fakename and a realname"},
+ {"ScriptAlias", add_alias, "cgi-script", RSRC_CONF, TAKE2,
+ "a fakename and a realname"},
+ {"Redirect", add_redirect, (void *) HTTP_MOVED_TEMPORARILY,
+ OR_FILEINFO, TAKE23,
+ "an optional status, then document to be redirected and destination URL"},
+ {"AliasMatch", add_alias_regex, NULL, RSRC_CONF, TAKE2,
+ "a regular expression and a filename"},
+ {"ScriptAliasMatch", add_alias_regex, "cgi-script", RSRC_CONF, TAKE2,
+ "a regular expression and a filename"},
+ {"RedirectMatch", add_redirect_regex, (void *) HTTP_MOVED_TEMPORARILY,
+ OR_FILEINFO, TAKE23,
+ "an optional status, then a regular expression and destination URL"},
+ {"RedirectTemp", add_redirect, (void *) HTTP_MOVED_TEMPORARILY,
+ OR_FILEINFO, TAKE2,
+ "a document to be redirected, then the destination URL"},
+ {"RedirectPermanent", add_redirect, (void *) HTTP_MOVED_PERMANENTLY,
+ OR_FILEINFO, TAKE2,
+ "a document to be redirected, then the destination URL"},
+ {NULL}
+};
+
+static int alias_matches(const char *uri, const char *alias_fakename)
+{
+ const char *end_fakename = alias_fakename + strlen(alias_fakename);
+ const char *aliasp = alias_fakename, *urip = uri;
+
+ while (aliasp < end_fakename) {
+ if (*aliasp == '/') {
+ /* any number of '/' in the alias matches any number in
+ * the supplied URI, but there must be at least one...
+ */
+ if (*urip != '/')
+ return 0;
+
+ while (*aliasp == '/')
+ ++aliasp;
+ while (*urip == '/')
+ ++urip;
+ }
+ else {
+ /* Other characters are compared literally */
+ if (*urip++ != *aliasp++)
+ return 0;
+ }
+ }
+
+ /* Check last alias path component matched all the way */
+
+ if (aliasp[-1] != '/' && *urip != '\0' && *urip != '/')
+ return 0;
+
+ /* Return number of characters from URI which matched (may be
+ * greater than length of alias, since we may have matched
+ * doubled slashes)
+ */
+
+ return urip - uri;
+}
+
+static char *try_alias_list(request_rec *r, array_header *aliases, int doesc, int *status)
+{
+ alias_entry *entries = (alias_entry *) aliases->elts;
+ regmatch_t regm[10];
+ char *found = NULL;
+ int i;
+
+ for (i = 0; i < aliases->nelts; ++i) {
+ alias_entry *p = &entries[i];
+ int l;
+
+ if (p->regexp) {
+ if (!ap_regexec(p->regexp, r->uri, p->regexp->re_nsub + 1, regm, 0)) {
+ if (p->real) {
+ found = ap_pregsub(r->pool, p->real, r->uri,
+ p->regexp->re_nsub + 1, regm);
+ if (found && doesc) {
+ found = ap_escape_uri(r->pool, found);
+ }
+ }
+ else {
+ /* need something non-null */
+ found = ap_pstrdup(r->pool, "");
+ }
+ }
+ }
+ else {
+ l = alias_matches(r->uri, p->fake);
+
+ if (l > 0) {
+ if (doesc) {
+ char *escurl;
+ escurl = ap_os_escape_path(r->pool, r->uri + l, 1);
+
+ found = ap_pstrcat(r->pool, p->real, escurl, NULL);
+ }
+ else
+ found = ap_pstrcat(r->pool, p->real, r->uri + l, NULL);
+ }
+ }
+
+ if (found) {
+ if (p->handler) { /* Set handler, and leave a note for mod_cgi */
+ r->handler = p->handler;
+ ap_table_setn(r->notes, "alias-forced-type", r->handler);
+ }
+
+ *status = p->redir_status;
+
+ return found;
+ }
+
+ }
+
+ return NULL;
+}
+
+static int translate_alias_redir(request_rec *r)
+{
+ void *sconf = r->server->module_config;
+ alias_server_conf *serverconf =
+ (alias_server_conf *) ap_get_module_config(sconf, &alias_module);
+ char *ret;
+ int status;
+
+ if (r->uri[0] != '/' && r->uri[0] != '\0')
+ return DECLINED;
+
+ if ((ret = try_alias_list(r, serverconf->redirects, 1, &status)) != NULL) {
+ if (ap_is_HTTP_REDIRECT(status)) {
+ /* include QUERY_STRING if any */
+ if (r->args) {
+ ret = ap_pstrcat(r->pool, ret, "?", r->args, NULL);
+ }
+ ap_table_setn(r->headers_out, "Location", ret);
+ }
+ return status;
+ }
+
+ if ((ret = try_alias_list(r, serverconf->aliases, 0, &status)) != NULL) {
+ r->filename = ret;
+ return OK;
+ }
+
+ return DECLINED;
+}
+
+static int fixup_redir(request_rec *r)
+{
+ void *dconf = r->per_dir_config;
+ alias_dir_conf *dirconf =
+ (alias_dir_conf *) ap_get_module_config(dconf, &alias_module);
+ char *ret;
+ int status;
+
+ /* It may have changed since last time, so try again */
+
+ if ((ret = try_alias_list(r, dirconf->redirects, 1, &status)) != NULL) {
+ if (ap_is_HTTP_REDIRECT(status))
+ ap_table_setn(r->headers_out, "Location", ret);
+ return status;
+ }
+
+ return DECLINED;
+}
+
+module MODULE_VAR_EXPORT alias_module =
+{
+ STANDARD_MODULE_STUFF,
+ NULL, /* initializer */
+ create_alias_dir_config, /* dir config creater */
+ merge_alias_dir_config, /* dir merger --- default is to override */
+ create_alias_config, /* server config */
+ merge_alias_config, /* merge server configs */
+ alias_cmds, /* command table */
+ NULL, /* handlers */
+ translate_alias_redir, /* filename translation */
+ NULL, /* check_user_id */
+ NULL, /* check auth */
+ NULL, /* check access */
+ NULL, /* type_checker */
+ fixup_redir, /* fixups */
+ NULL, /* logger */
+ NULL, /* header parser */
+ NULL, /* child_init */
+ NULL, /* child_exit */
+ NULL /* post read-request */
+};
diff --git a/modules/mappers/mod_dir.c b/modules/mappers/mod_dir.c
new file mode 100644
index 00000000000..a32b390a88b
--- /dev/null
+++ b/modules/mappers/mod_dir.c
@@ -0,0 +1,246 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+/*
+ * mod_dir.c: handle default index files, and trailing-/ redirects
+ */
+
+#include "httpd.h"
+#include "http_config.h"
+#include "http_core.h"
+#include "http_request.h"
+#include "http_protocol.h"
+#include "http_log.h"
+#include "http_main.h"
+#include "util_script.h"
+
+module MODULE_VAR_EXPORT dir_module;
+
+typedef struct dir_config_struct {
+ array_header *index_names;
+} dir_config_rec;
+
+#define DIR_CMD_PERMS OR_INDEXES
+
+static const char *add_index(cmd_parms *cmd, void *dummy, char *arg)
+{
+ dir_config_rec *d = dummy;
+
+ if (!d->index_names) {
+ d->index_names = ap_make_array(cmd->pool, 2, sizeof(char *));
+ }
+ *(char **)ap_push_array(d->index_names) = arg;
+ return NULL;
+}
+
+static const command_rec dir_cmds[] =
+{
+ {"DirectoryIndex", add_index, NULL,
+ DIR_CMD_PERMS, ITERATE,
+ "a list of file names"},
+ {NULL}
+};
+
+static void *create_dir_config(pool *p, char *dummy)
+{
+ dir_config_rec *new =
+ (dir_config_rec *) ap_pcalloc(p, sizeof(dir_config_rec));
+
+ new->index_names = NULL;
+ return (void *) new;
+}
+
+static void *merge_dir_configs(pool *p, void *basev, void *addv)
+{
+ dir_config_rec *new = (dir_config_rec *) ap_pcalloc(p, sizeof(dir_config_rec));
+ dir_config_rec *base = (dir_config_rec *) basev;
+ dir_config_rec *add = (dir_config_rec *) addv;
+
+ new->index_names = add->index_names ? add->index_names : base->index_names;
+ return new;
+}
+
+static int handle_dir(request_rec *r)
+{
+ dir_config_rec *d =
+ (dir_config_rec *) ap_get_module_config(r->per_dir_config,
+ &dir_module);
+ char *dummy_ptr[1];
+ char **names_ptr;
+ int num_names;
+ int error_notfound = 0;
+
+ if (r->uri[0] == '\0' || r->uri[strlen(r->uri) - 1] != '/') {
+ char *ifile;
+ if (r->args != NULL)
+ ifile = ap_pstrcat(r->pool, ap_escape_uri(r->pool, r->uri),
+ "/", "?", r->args, NULL);
+ else
+ ifile = ap_pstrcat(r->pool, ap_escape_uri(r->pool, r->uri),
+ "/", NULL);
+
+ ap_table_setn(r->headers_out, "Location",
+ ap_construct_url(r->pool, ifile, r));
+ return HTTP_MOVED_PERMANENTLY;
+ }
+
+ /* KLUDGE --- make the sub_req lookups happen in the right directory.
+ * Fixing this in the sub_req_lookup functions themselves is difficult,
+ * and would probably break virtual includes...
+ */
+
+ if (r->filename[strlen(r->filename) - 1] != '/') {
+ r->filename = ap_pstrcat(r->pool, r->filename, "/", NULL);
+ }
+
+ if (d->index_names) {
+ names_ptr = (char **)d->index_names->elts;
+ num_names = d->index_names->nelts;
+ }
+ else {
+ dummy_ptr[0] = DEFAULT_INDEX;
+ names_ptr = dummy_ptr;
+ num_names = 1;
+ }
+
+ for (; num_names; ++names_ptr, --num_names) {
+ char *name_ptr = *names_ptr;
+ request_rec *rr = ap_sub_req_lookup_uri(name_ptr, r);
+
+ if (rr->status == HTTP_OK && S_ISREG(rr->finfo.st_mode)) {
+ char *new_uri = ap_escape_uri(r->pool, rr->uri);
+
+ if (rr->args != NULL)
+ new_uri = ap_pstrcat(r->pool, new_uri, "?", rr->args, NULL);
+ else if (r->args != NULL)
+ new_uri = ap_pstrcat(r->pool, new_uri, "?", r->args, NULL);
+
+ ap_destroy_sub_req(rr);
+ ap_internal_redirect(new_uri, r);
+ return OK;
+ }
+
+ /* If the request returned a redirect, propagate it to the client */
+
+ if (ap_is_HTTP_REDIRECT(rr->status) ||
+ (rr->status == HTTP_NOT_ACCEPTABLE && num_names == 1)) {
+
+ ap_pool_join(r->pool, rr->pool);
+ error_notfound = rr->status;
+ r->notes = ap_overlay_tables(r->pool, r->notes, rr->notes);
+ r->headers_out = ap_overlay_tables(r->pool, r->headers_out,
+ rr->headers_out);
+ r->err_headers_out = ap_overlay_tables(r->pool, r->err_headers_out,
+ rr->err_headers_out);
+ return error_notfound;
+ }
+
+ /* If the request returned something other than 404 (or 200),
+ * it means the module encountered some sort of problem. To be
+ * secure, we should return the error, rather than create
+ * along a (possibly unsafe) directory index.
+ *
+ * So we store the error, and if none of the listed files
+ * exist, we return the last error response we got, instead
+ * of a directory listing.
+ */
+ if (rr->status && rr->status != HTTP_NOT_FOUND && rr->status != HTTP_OK)
+ error_notfound = rr->status;
+
+ ap_destroy_sub_req(rr);
+ }
+
+ if (error_notfound)
+ return error_notfound;
+
+ if (r->method_number != M_GET)
+ return DECLINED;
+
+ /* nothing for us to do, pass on through */
+
+ return DECLINED;
+}
+
+
+static const handler_rec dir_handlers[] =
+{
+ {DIR_MAGIC_TYPE, handle_dir},
+ {NULL}
+};
+
+module MODULE_VAR_EXPORT dir_module =
+{
+ STANDARD_MODULE_STUFF,
+ NULL, /* initializer */
+ create_dir_config, /* dir config creater */
+ merge_dir_configs, /* dir merger --- default is to override */
+ NULL, /* server config */
+ NULL, /* merge server config */
+ dir_cmds, /* command table */
+ dir_handlers, /* handlers */
+ NULL, /* filename translation */
+ NULL, /* check_user_id */
+ NULL, /* check auth */
+ NULL, /* check access */
+ NULL, /* type_checker */
+ NULL, /* fixups */
+ NULL, /* logger */
+ NULL, /* header parser */
+ NULL, /* child_init */
+ NULL, /* child_exit */
+ NULL /* post read-request */
+};
diff --git a/modules/mappers/mod_imap.c b/modules/mappers/mod_imap.c
new file mode 100644
index 00000000000..c5152e71e40
--- /dev/null
+++ b/modules/mappers/mod_imap.c
@@ -0,0 +1,919 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * IT'S CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+/*
+ * This imagemap module started as a port of the original imagemap.c
+ * written by Rob McCool (11/13/93 robm@ncsa.uiuc.edu).
+ * This version includes the mapping algorithms found in version 1.3
+ * of imagemap.c.
+ *
+ * Contributors to this code include:
+ *
+ * Kevin Hughes, kevinh@pulua.hcc.hawaii.edu
+ *
+ * Eric Haines, erich@eye.com
+ * "macmartinized" polygon code copyright 1992 by Eric Haines, erich@eye.com
+ *
+ * Randy Terbush, randy@zyzzyva.com
+ * port to Apache module format, "base_uri" and support for relative URLs
+ *
+ * James H. Cloos, Jr., cloos@jhcloos.com
+ * Added point datatype, using code in NCSA's version 1.8 imagemap.c
+ * program, as distributed with version 1.4.1 of their server.
+ * The point code is originally added by Craig Milo Rogers, Rogers@ISI.Edu
+ *
+ * Nathan Kurz, nate@tripod.com
+ * Rewrite/reorganization. New handling of default, base and relative URLs.
+ * New Configuration directives:
+ * ImapMenu {none, formatted, semiformatted, unformatted}
+ * ImapDefault {error, nocontent, referer, menu, URL}
+ * ImapBase {map, referer, URL}
+ * Support for creating non-graphical menu added. (backwards compatible):
+ * Old: directive URL [x,y ...]
+ * New: directive URL "Menu text" [x,y ...]
+ * or: directive URL x,y ... "Menu text"
+ * Map format and menu concept courtesy Joshua Bell, jsbell@acs.ucalgary.ca.
+ *
+ * Mark Cox, mark@ukweb.com, Allow relative URLs even when no base specified
+ */
+
+#include "httpd.h"
+#include "http_config.h"
+#include "http_request.h"
+#include "http_core.h"
+#include "http_protocol.h"
+#include "http_main.h"
+#include "http_log.h"
+#include "util_script.h"
+
+#define IMAP_MAGIC_TYPE "application/x-httpd-imap"
+#define MAXVERTS 100
+#define X 0
+#define Y 1
+
+#define IMAP_MENU_DEFAULT "formatted"
+#define IMAP_DEFAULT_DEFAULT "nocontent"
+#define IMAP_BASE_DEFAULT "map"
+
+#ifdef SUNOS4
+double strtod(); /* SunOS needed this */
+#endif
+
+module MODULE_VAR_EXPORT imap_module;
+
+typedef struct {
+ char *imap_menu;
+ char *imap_default;
+ char *imap_base;
+} imap_conf_rec;
+
+static void *create_imap_dir_config(pool *p, char *dummy)
+{
+ imap_conf_rec *icr =
+ (imap_conf_rec *) ap_palloc(p, sizeof(imap_conf_rec));
+
+ icr->imap_menu = NULL;
+ icr->imap_default = NULL;
+ icr->imap_base = NULL;
+
+ return icr;
+}
+
+static void *merge_imap_dir_configs(pool *p, void *basev, void *addv)
+{
+ imap_conf_rec *new = (imap_conf_rec *) ap_pcalloc(p, sizeof(imap_conf_rec));
+ imap_conf_rec *base = (imap_conf_rec *) basev;
+ imap_conf_rec *add = (imap_conf_rec *) addv;
+
+ new->imap_menu = add->imap_menu ? add->imap_menu : base->imap_menu;
+ new->imap_default = add->imap_default ? add->imap_default
+ : base->imap_default;
+ new->imap_base = add->imap_base ? add->imap_base : base->imap_base;
+
+ return new;
+}
+
+
+static const command_rec imap_cmds[] =
+{
+ {"ImapMenu", ap_set_string_slot,
+ (void *) XtOffsetOf(imap_conf_rec, imap_menu), OR_INDEXES, TAKE1,
+ "the type of menu generated: none, formatted, semiformatted, unformatted"},
+ {"ImapDefault", ap_set_string_slot,
+ (void *) XtOffsetOf(imap_conf_rec, imap_default), OR_INDEXES, TAKE1,
+ "the action taken if no match: error, nocontent, referer, menu, URL"},
+ {"ImapBase", ap_set_string_slot,
+ (void *) XtOffsetOf(imap_conf_rec, imap_base), OR_INDEXES, TAKE1,
+ "the base for all URL's: map, referer, URL (or start of)"},
+ {NULL}
+};
+
+static int pointinrect(const double point[2], double coords[MAXVERTS][2])
+{
+ double max[2], min[2];
+ if (coords[0][X] > coords[1][X]) {
+ max[0] = coords[0][X];
+ min[0] = coords[1][X];
+ }
+ else {
+ max[0] = coords[1][X];
+ min[0] = coords[0][X];
+ }
+
+ if (coords[0][Y] > coords[1][Y]) {
+ max[1] = coords[0][Y];
+ min[1] = coords[1][Y];
+ }
+ else {
+ max[1] = coords[1][Y];
+ min[1] = coords[0][Y];
+ }
+
+ return ((point[X] >= min[0] && point[X] <= max[0]) &&
+ (point[Y] >= min[1] && point[Y] <= max[1]));
+}
+
+static int pointincircle(const double point[2], double coords[MAXVERTS][2])
+{
+ double radius1, radius2;
+
+ radius1 = ((coords[0][Y] - coords[1][Y]) * (coords[0][Y] - coords[1][Y]))
+ + ((coords[0][X] - coords[1][X]) * (coords[0][X] - coords[1][X]));
+
+ radius2 = ((coords[0][Y] - point[Y]) * (coords[0][Y] - point[Y]))
+ + ((coords[0][X] - point[X]) * (coords[0][X] - point[X]));
+
+ return (radius2 <= radius1);
+}
+
+#define fmin(a,b) (((a)>(b))?(b):(a))
+#define fmax(a,b) (((a)>(b))?(a):(b))
+
+static int pointinpoly(const double point[2], double pgon[MAXVERTS][2])
+{
+ int i, numverts, crossings = 0;
+ double x = point[X], y = point[Y];
+
+ for (numverts = 0; pgon[numverts][X] != -1 && numverts < MAXVERTS;
+ numverts++) {
+ /* just counting the vertexes */
+ }
+
+ for (i = 0; i < numverts; i++) {
+ double x1=pgon[i][X];
+ double y1=pgon[i][Y];
+ double x2=pgon[(i + 1) % numverts][X];
+ double y2=pgon[(i + 1) % numverts][Y];
+ double d=(y - y1) * (x2 - x1) - (x - x1) * (y2 - y1);
+
+ if ((y1 >= y) != (y2 >= y)) {
+ crossings +=y2 - y1 >= 0 ? d >= 0 : d <= 0;
+ }
+ if (!d && fmin(x1,x2) <= x && x <= fmax(x1,x2)
+ && fmin(y1,y2) <= y && y <= fmax(y1,y2)) {
+ return 1;
+ }
+ }
+ return crossings & 0x01;
+}
+
+
+static int is_closer(const double point[2], double coords[MAXVERTS][2],
+ double *closest)
+{
+ double dist_squared = ((point[X] - coords[0][X])
+ * (point[X] - coords[0][X]))
+ + ((point[Y] - coords[0][Y])
+ * (point[Y] - coords[0][Y]));
+
+ if (point[X] < 0 || point[Y] < 0) {
+ return (0); /* don't mess around with negative coordinates */
+ }
+
+ if (*closest < 0 || dist_squared < *closest) {
+ *closest = dist_squared;
+ return (1); /* if this is the first point or is the closest yet
+ set 'closest' equal to this distance^2 */
+ }
+
+ return (0); /* if it's not the first or closest */
+
+}
+
+static double get_x_coord(const char *args)
+{
+ char *endptr; /* we want it non-null */
+ double x_coord = -1; /* -1 is returned if no coordinate is given */
+
+ if (args == NULL) {
+ return (-1); /* in case we aren't passed anything */
+ }
+
+ while (*args && !ap_isdigit(*args) && *args != ',') {
+ args++; /* jump to the first digit, but not past
+ a comma or end */
+ }
+
+ x_coord = strtod(args, &endptr);
+
+ if (endptr > args) { /* if a conversion was made */
+ return (x_coord);
+ }
+
+ return (-1); /* else if no conversion was made,
+ or if no args was given */
+}
+
+static double get_y_coord(const char *args)
+{
+ char *endptr; /* we want it non-null */
+ char *start_of_y = NULL;
+ double y_coord = -1; /* -1 is returned on error */
+
+ if (args == NULL) {
+ return (-1); /* in case we aren't passed anything */
+ }
+
+ start_of_y = strchr(args, ','); /* the comma */
+
+ if (start_of_y) {
+
+ start_of_y++; /* start looking at the character after
+ the comma */
+
+ while (*start_of_y && !ap_isdigit(*start_of_y)) {
+ start_of_y++; /* jump to the first digit, but not
+ past the end */
+ }
+
+ y_coord = strtod(start_of_y, &endptr);
+
+ if (endptr > start_of_y) {
+ return (y_coord);
+ }
+ }
+
+ return (-1); /* if no conversion was made, or
+ no comma was found in args */
+}
+
+
+/* See if string has a "quoted part", and if so set *quoted_part to
+ * the first character of the quoted part, then hammer a \0 onto the
+ * trailing quote, and set *string to point at the first character
+ * past the second quote.
+ *
+ * Otherwise set *quoted_part to NULL, and leave *string alone.
+ */
+static void read_quoted(char **string, char **quoted_part)
+{
+ char *strp = *string;
+
+ /* assume there's no quoted part */
+ *quoted_part = NULL;
+
+ while (ap_isspace(*strp)) {
+ strp++; /* go along string until non-whitespace */
+ }
+
+ if (*strp == '"') { /* if that character is a double quote */
+ strp++; /* step over it */
+ *quoted_part = strp; /* note where the quoted part begins */
+
+ while (*strp && *strp != '"') {
+ ++strp; /* skip the quoted portion */
+ }
+
+ *strp = '\0'; /* end the string with a NUL */
+
+ strp++; /* step over the last double quote */
+ *string = strp;
+ }
+}
+
+/*
+ * returns the mapped URL or NULL.
+ */
+static char *imap_url(request_rec *r, const char *base, const char *value)
+{
+/* translates a value into a URL. */
+ int slen, clen;
+ char *string_pos = NULL;
+ const char *string_pos_const = NULL;
+ char *directory = NULL;
+ const char *referer = NULL;
+ char *my_base;
+
+ if (!strcasecmp(value, "map") || !strcasecmp(value, "menu")) {
+ return ap_construct_url(r->pool, r->uri, r);
+ }
+
+ if (!strcasecmp(value, "nocontent") || !strcasecmp(value, "error")) {
+ return ap_pstrdup(r->pool, value); /* these are handled elsewhere,
+ so just copy them */
+ }
+
+ if (!strcasecmp(value, "referer")) {
+ referer = ap_table_get(r->headers_in, "Referer");
+ if (referer && *referer) {
+ return ap_pstrdup(r->pool, referer);
+ }
+ else {
+ /* XXX: This used to do *value = '\0'; ... which is totally bogus
+ * because it hammers the passed in value, which can be a string
+ * constant, or part of a config, or whatever. Total garbage.
+ * This works around that without changing the rest of this
+ * code much
+ */
+ value = ""; /* if 'referer' but no referring page,
+ null the value */
+ }
+ }
+
+ string_pos_const = value;
+ while (ap_isalpha(*string_pos_const)) {
+ string_pos_const++; /* go along the URL from the map
+ until a non-letter */
+ }
+ if (*string_pos_const == ':') {
+ /* if letters and then a colon (like http:) */
+ /* it's an absolute URL, so use it! */
+ return ap_pstrdup(r->pool, value);
+ }
+
+ if (!base || !*base) {
+ if (value && *value) {
+ return ap_pstrdup(r->pool, value); /* no base: use what is given */
+ }
+ /* no base, no value: pick a simple default */
+ return ap_construct_url(r->pool, "/", r);
+ }
+
+ /* must be a relative URL to be combined with base */
+ if (strchr(base, '/') == NULL && (!strncmp(value, "../", 3)
+ || !strcmp(value, ".."))) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "invalid base directive in map file: %s", r->uri);
+ return NULL;
+ }
+ my_base = ap_pstrdup(r->pool, base);
+ string_pos = my_base;
+ while (*string_pos) {
+ if (*string_pos == '/' && *(string_pos + 1) == '/') {
+ string_pos += 2; /* if there are two slashes, jump over them */
+ continue;
+ }
+ if (*string_pos == '/') { /* the first single slash */
+ if (value[0] == '/') {
+ *string_pos = '\0';
+ } /* if the URL from the map starts from root,
+ end the base URL string at the first single
+ slash */
+ else {
+ directory = string_pos; /* save the start of
+ the directory portion */
+
+ string_pos = strrchr(string_pos, '/'); /* now reuse
+ string_pos */
+ string_pos++; /* step over that last slash */
+ *string_pos = '\0';
+ } /* but if the map url is relative, leave the
+ slash on the base (if there is one) */
+ break;
+ }
+ string_pos++; /* until we get to the end of my_base without
+ finding a slash by itself */
+ }
+
+ while (!strncmp(value, "../", 3) || !strcmp(value, "..")) {
+
+ if (directory && (slen = strlen(directory))) {
+
+ /* for each '..', knock a directory off the end
+ by ending the string right at the last slash.
+ But only consider the directory portion: don't eat
+ into the server name. And only try if a directory
+ portion was found */
+
+ clen = slen - 1;
+
+ while ((slen - clen) == 1) {
+
+ if ((string_pos = strrchr(directory, '/'))) {
+ *string_pos = '\0';
+ }
+ clen = strlen(directory);
+ if (clen == 0) {
+ break;
+ }
+ }
+
+ value += 2; /* jump over the '..' that we found in the
+ value */
+ }
+ else if (directory) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "invalid directory name in map file: %s", r->uri);
+ return NULL;
+ }
+
+ if (!strncmp(value, "/../", 4) || !strcmp(value, "/..")) {
+ value++; /* step over the '/' if there are more '..'
+ to do. This way, we leave the starting
+ '/' on value after the last '..', but get
+ rid of it otherwise */
+ }
+
+ } /* by this point, value does not start
+ with '..' */
+
+ if (value && *value) {
+ return ap_pstrcat(r->pool, my_base, value, NULL);
+ }
+ return my_base;
+}
+
+static int imap_reply(request_rec *r, char *redirect)
+{
+ if (!strcasecmp(redirect, "error")) {
+ return SERVER_ERROR; /* they actually requested an error! */
+ }
+ if (!strcasecmp(redirect, "nocontent")) {
+ return HTTP_NO_CONTENT; /* tell the client to keep the page it has */
+ }
+ if (redirect && *redirect) {
+ ap_table_setn(r->headers_out, "Location", redirect);
+ return REDIRECT; /* must be a URL, so redirect to it */
+ }
+ return SERVER_ERROR;
+}
+
+static void menu_header(request_rec *r, char *menu)
+{
+ r->content_type = "text/html";
+ ap_send_http_header(r);
+ ap_hard_timeout("send menu", r); /* killed in menu_footer */
+
+ ap_rvputs(r, DOCTYPE_HTML_3_2, "\nMenu for ", r->uri,
+ "\n\n", NULL);
+
+ if (!strcasecmp(menu, "formatted")) {
+ ap_rvputs(r, "Menu for ", r->uri, "\n \n\n", NULL);
+ }
+
+ return;
+}
+
+static void menu_blank(request_rec *r, char *menu)
+{
+ if (!strcasecmp(menu, "formatted")) {
+ ap_rputs("\n", r);
+ }
+ if (!strcasecmp(menu, "semiformatted")) {
+ ap_rputs(" \n", r);
+ }
+ if (!strcasecmp(menu, "unformatted")) {
+ ap_rputs("\n", r);
+ }
+ return;
+}
+
+static void menu_comment(request_rec *r, char *menu, char *comment)
+{
+ if (!strcasecmp(menu, "formatted")) {
+ ap_rputs("\n", r); /* print just a newline if 'formatted' */
+ }
+ if (!strcasecmp(menu, "semiformatted") && *comment) {
+ ap_rvputs(r, comment, "\n", NULL);
+ }
+ if (!strcasecmp(menu, "unformatted") && *comment) {
+ ap_rvputs(r, comment, "\n", NULL);
+ }
+ return; /* comments are ignored in the
+ 'formatted' form */
+}
+
+static void menu_default(request_rec *r, char *menu, char *href, char *text)
+{
+ if (!strcasecmp(href, "error") || !strcasecmp(href, "nocontent")) {
+ return; /* don't print such lines, these aren't
+ really href's */
+ }
+ if (!strcasecmp(menu, "formatted")) {
+ ap_rvputs(r, "(Default) ", text,
+ " \n", NULL);
+ }
+ if (!strcasecmp(menu, "semiformatted")) {
+ ap_rvputs(r, "(Default) ", text,
+ " \n", NULL);
+ }
+ if (!strcasecmp(menu, "unformatted")) {
+ ap_rvputs(r, "", text, "", NULL);
+ }
+ return;
+}
+
+static void menu_directive(request_rec *r, char *menu, char *href, char *text)
+{
+ if (!strcasecmp(href, "error") || !strcasecmp(href, "nocontent")) {
+ return; /* don't print such lines, as this isn't
+ really an href */
+ }
+ if (!strcasecmp(menu, "formatted")) {
+ ap_rvputs(r, " ", text,
+ " \n", NULL);
+ }
+ if (!strcasecmp(menu, "semiformatted")) {
+ ap_rvputs(r, " ", text,
+ " \n", NULL);
+ }
+ if (!strcasecmp(menu, "unformatted")) {
+ ap_rvputs(r, "", text, "", NULL);
+ }
+ return;
+}
+
+static void menu_footer(request_rec *r)
+{
+ ap_rputs("\n\n\n\n", r); /* finish the menu */
+ ap_kill_timeout(r);
+}
+
+static int imap_handler(request_rec *r)
+{
+ char input[MAX_STRING_LEN];
+ char *directive;
+ char *value;
+ char *href_text;
+ char *base;
+ char *redirect;
+ char *mapdflt;
+ char *closest = NULL;
+ double closest_yet = -1;
+
+ double testpoint[2];
+ double pointarray[MAXVERTS + 1][2];
+ int vertex;
+
+ char *string_pos;
+ int showmenu = 0;
+
+ imap_conf_rec *icr = ap_get_module_config(r->per_dir_config, &imap_module);
+
+ char *imap_menu = icr->imap_menu ? icr->imap_menu : IMAP_MENU_DEFAULT;
+ char *imap_default = icr->imap_default
+ ? icr->imap_default : IMAP_DEFAULT_DEFAULT;
+ char *imap_base = icr->imap_base ? icr->imap_base : IMAP_BASE_DEFAULT;
+
+ configfile_t *imap;
+
+ if (r->method_number != M_GET) {
+ return DECLINED;
+ }
+
+ imap = ap_pcfg_openfile(r->pool, r->filename);
+
+ if (!imap) {
+ return NOT_FOUND;
+ }
+
+ base = imap_url(r, NULL, imap_base); /* set base according
+ to default */
+ if (!base) {
+ return HTTP_INTERNAL_SERVER_ERROR;
+ }
+ mapdflt = imap_url(r, NULL, imap_default); /* and default to
+ global default */
+ if (!mapdflt) {
+ return HTTP_INTERNAL_SERVER_ERROR;
+ }
+
+ testpoint[X] = get_x_coord(r->args);
+ testpoint[Y] = get_y_coord(r->args);
+
+ if ((testpoint[X] == -1 || testpoint[Y] == -1) ||
+ (testpoint[X] == 0 && testpoint[Y] == 0)) {
+ /* if either is -1 or if both are zero (new Lynx) */
+ /* we don't have valid coordinates */
+ testpoint[X] = -1;
+ testpoint[Y] = -1;
+ if (strncasecmp(imap_menu, "none", 2)) {
+ showmenu = 1; /* show the menu _unless_ ImapMenu is
+ 'none' or 'no' */
+ }
+ }
+
+ if (showmenu) { /* send start of imagemap menu if
+ we're going to */
+ menu_header(r, imap_menu);
+ }
+
+ while (!ap_cfg_getline(input, sizeof(input), imap)) {
+ if (!input[0]) {
+ if (showmenu) {
+ menu_blank(r, imap_menu);
+ }
+ continue;
+ }
+
+ if (input[0] == '#') {
+ if (showmenu) {
+ menu_comment(r, imap_menu, input + 1);
+ }
+ continue;
+ } /* blank lines and comments are ignored
+ if we aren't printing a menu */
+
+ /* find the first two space delimited fields, recall that
+ * ap_cfg_getline has removed leading/trailing whitespace.
+ *
+ * note that we're tokenizing as we go... if we were to use the
+ * ap_getword() class of functions we would end up allocating extra
+ * memory for every line of the map file
+ */
+ string_pos = input;
+ if (!*string_pos) { /* need at least two fields */
+ goto need_2_fields;
+ }
+
+ directive = string_pos;
+ while (*string_pos && !ap_isspace(*string_pos)) { /* past directive */
+ ++string_pos;
+ }
+ if (!*string_pos) { /* need at least two fields */
+ goto need_2_fields;
+ }
+ *string_pos++ = '\0';
+
+ if (!*string_pos) { /* need at least two fields */
+ goto need_2_fields;
+ }
+ while(*string_pos && ap_isspace(*string_pos)) { /* past whitespace */
+ ++string_pos;
+ }
+
+ value = string_pos;
+ while (*string_pos && !ap_isspace(*string_pos)) { /* past value */
+ ++string_pos;
+ }
+ if (ap_isspace(*string_pos)) {
+ *string_pos++ = '\0';
+ }
+ else {
+ /* end of input, don't advance past it */
+ *string_pos = '\0';
+ }
+
+ if (!strncasecmp(directive, "base", 4)) { /* base, base_uri */
+ base = imap_url(r, NULL, value);
+ if (!base) {
+ goto menu_bail;
+ }
+ continue; /* base is never printed to a menu */
+ }
+
+ read_quoted(&string_pos, &href_text);
+
+ if (!strcasecmp(directive, "default")) { /* default */
+ mapdflt = imap_url(r, NULL, value);
+ if (!mapdflt) {
+ goto menu_bail;
+ }
+ if (showmenu) { /* print the default if there's a menu */
+ redirect = imap_url(r, base, mapdflt);
+ if (!redirect) {
+ goto menu_bail;
+ }
+ menu_default(r, imap_menu, redirect,
+ href_text ? href_text : mapdflt);
+ }
+ continue;
+ }
+
+ vertex = 0;
+ while (vertex < MAXVERTS &&
+ sscanf(string_pos, "%lf%*[, ]%lf",
+ &pointarray[vertex][X], &pointarray[vertex][Y]) == 2) {
+ /* Now skip what we just read... we can't use ANSIism %n */
+ while (ap_isspace(*string_pos)) { /* past whitespace */
+ string_pos++;
+ }
+ while (ap_isdigit(*string_pos)) { /* and the 1st number */
+ string_pos++;
+ }
+ string_pos++; /* skip the ',' */
+ while (ap_isspace(*string_pos)) { /* past any more whitespace */
+ string_pos++;
+ }
+ while (ap_isdigit(*string_pos)) { /* 2nd number */
+ string_pos++;
+ }
+ vertex++;
+ } /* so long as there are more vertices to
+ read, and we have room, read them in.
+ We start where we left off of the last
+ sscanf, not at the beginning. */
+
+ pointarray[vertex][X] = -1; /* signals the end of vertices */
+
+ if (showmenu) {
+ if (!href_text) {
+ read_quoted(&string_pos, &href_text); /* href text could
+ be here instead */
+ }
+ redirect = imap_url(r, base, value);
+ if (!redirect) {
+ goto menu_bail;
+ }
+ menu_directive(r, imap_menu, redirect,
+ href_text ? href_text : value);
+ continue;
+ }
+ /* note that we don't make it past here if we are making a menu */
+
+ if (testpoint[X] == -1 || pointarray[0][X] == -1) {
+ continue; /* don't try the following tests if testpoints
+ are invalid, or if there are no
+ coordinates */
+ }
+
+ if (!strcasecmp(directive, "poly")) { /* poly */
+
+ if (pointinpoly(testpoint, pointarray)) {
+ ap_cfg_closefile(imap);
+ redirect = imap_url(r, base, value);
+ if (!redirect) {
+ return HTTP_INTERNAL_SERVER_ERROR;
+ }
+ return (imap_reply(r, redirect));
+ }
+ continue;
+ }
+
+ if (!strcasecmp(directive, "circle")) { /* circle */
+
+ if (pointincircle(testpoint, pointarray)) {
+ ap_cfg_closefile(imap);
+ redirect = imap_url(r, base, value);
+ if (!redirect) {
+ return HTTP_INTERNAL_SERVER_ERROR;
+ }
+ return (imap_reply(r, redirect));
+ }
+ continue;
+ }
+
+ if (!strcasecmp(directive, "rect")) { /* rect */
+
+ if (pointinrect(testpoint, pointarray)) {
+ ap_cfg_closefile(imap);
+ redirect = imap_url(r, base, value);
+ if (!redirect) {
+ return HTTP_INTERNAL_SERVER_ERROR;
+ }
+ return (imap_reply(r, redirect));
+ }
+ continue;
+ }
+
+ if (!strcasecmp(directive, "point")) { /* point */
+
+ if (is_closer(testpoint, pointarray, &closest_yet)) {
+ closest = ap_pstrdup(r->pool, value);
+ }
+
+ continue;
+ } /* move on to next line whether it's
+ closest or not */
+
+ } /* nothing matched, so we get another line! */
+
+ ap_cfg_closefile(imap); /* we are done with the map file; close it */
+
+ if (showmenu) {
+ menu_footer(r); /* finish the menu and we are done */
+ return OK;
+ }
+
+ if (closest) { /* if a 'point' directive has been seen */
+ redirect = imap_url(r, base, closest);
+ if (!redirect) {
+ return HTTP_INTERNAL_SERVER_ERROR;
+ }
+ return (imap_reply(r, redirect));
+ }
+
+ if (mapdflt) { /* a default should be defined, even if
+ only 'nocontent' */
+ redirect = imap_url(r, base, mapdflt);
+ if (!redirect) {
+ return HTTP_INTERNAL_SERVER_ERROR;
+ }
+ return (imap_reply(r, redirect));
+ }
+
+ return HTTP_INTERNAL_SERVER_ERROR; /* If we make it this far,
+ we failed. They lose! */
+
+need_2_fields:
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "map file %s, line %d syntax error: requires at "
+ "least two fields", r->uri, imap->line_number);
+ /* fall through */
+menu_bail:
+ ap_cfg_closefile(imap);
+ if (showmenu) {
+ /* There's not much else we can do ... we've already sent the headers
+ * to the client.
+ */
+ ap_rputs("\n\n[an internal server error occured]\n", r);
+ menu_footer(r);
+ return OK;
+ }
+ return HTTP_INTERNAL_SERVER_ERROR;
+}
+
+
+static const handler_rec imap_handlers[] =
+{
+ {IMAP_MAGIC_TYPE, imap_handler},
+ {"imap-file", imap_handler},
+ {NULL}
+};
+
+module MODULE_VAR_EXPORT imap_module =
+{
+ STANDARD_MODULE_STUFF,
+ NULL, /* initializer */
+ create_imap_dir_config, /* dir config creater */
+ merge_imap_dir_configs, /* dir merger --- default is to override */
+ NULL, /* server config */
+ NULL, /* merge server config */
+ imap_cmds, /* command table */
+ imap_handlers, /* handlers */
+ NULL, /* filename translation */
+ NULL, /* check_user_id */
+ NULL, /* check auth */
+ NULL, /* check access */
+ NULL, /* type_checker */
+ NULL, /* fixups */
+ NULL, /* logger */
+ NULL, /* header parser */
+ NULL, /* child_init */
+ NULL, /* child_exit */
+ NULL /* post read-request */
+};
diff --git a/modules/mappers/mod_negotiation.c b/modules/mappers/mod_negotiation.c
new file mode 100644
index 00000000000..5f7411260c2
--- /dev/null
+++ b/modules/mappers/mod_negotiation.c
@@ -0,0 +1,2748 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+/*
+ * mod_negotiation.c: keeps track of MIME types the client is willing to
+ * accept, and contains code to handle type arbitration.
+ *
+ * rst
+ */
+
+#include "httpd.h"
+#include "http_config.h"
+#include "http_request.h"
+#include "http_protocol.h"
+#include "http_core.h"
+#include "http_log.h"
+#include "util_script.h"
+
+/* Commands --- configuring document caching on a per (virtual?)
+ * server basis...
+ */
+
+typedef struct {
+ array_header *language_priority;
+} neg_dir_config;
+
+module MODULE_VAR_EXPORT negotiation_module;
+
+static void *create_neg_dir_config(pool *p, char *dummy)
+{
+ neg_dir_config *new = (neg_dir_config *) ap_palloc(p, sizeof(neg_dir_config));
+
+ new->language_priority = ap_make_array(p, 4, sizeof(char *));
+ return new;
+}
+
+static void *merge_neg_dir_configs(pool *p, void *basev, void *addv)
+{
+ neg_dir_config *base = (neg_dir_config *) basev;
+ neg_dir_config *add = (neg_dir_config *) addv;
+ neg_dir_config *new = (neg_dir_config *) ap_palloc(p, sizeof(neg_dir_config));
+
+ /* give priority to the config in the subdirectory */
+ new->language_priority = ap_append_arrays(p, add->language_priority,
+ base->language_priority);
+ return new;
+}
+
+static const char *set_language_priority(cmd_parms *cmd, void *n, char *lang)
+{
+ array_header *arr = ((neg_dir_config *) n)->language_priority;
+ char **langp = (char **) ap_push_array(arr);
+
+ *langp = lang;
+ return NULL;
+}
+
+static const char *cache_negotiated_docs(cmd_parms *cmd, void *dummy,
+ char *dummy2)
+{
+ void *server_conf = cmd->server->module_config;
+
+ ap_set_module_config(server_conf, &negotiation_module, "Cache");
+ return NULL;
+}
+
+static int do_cache_negotiated_docs(server_rec *s)
+{
+ return (ap_get_module_config(s->module_config, &negotiation_module) != NULL);
+}
+
+static const command_rec negotiation_cmds[] =
+{
+ {"CacheNegotiatedDocs", cache_negotiated_docs, NULL, RSRC_CONF, NO_ARGS,
+ "no arguments (either present or absent)"},
+ {"LanguagePriority", set_language_priority, NULL, OR_FILEINFO, ITERATE,
+ "space-delimited list of MIME language abbreviations"},
+ {NULL}
+};
+
+/*
+ * Record of available info on a media type specified by the client
+ * (we also use 'em for encodings and languages)
+ */
+
+typedef struct accept_rec {
+ char *name; /* MUST be lowercase */
+ float quality;
+ float level;
+ char *charset; /* for content-type only */
+} accept_rec;
+
+/*
+ * Record of available info on a particular variant
+ *
+ * Note that a few of these fields are updated by the actual negotiation
+ * code. These are:
+ *
+ * level_matched --- initialized to zero. Set to the value of level
+ * if the client actually accepts this media type at that
+ * level (and *not* if it got in on a wildcard). See level_cmp
+ * below.
+ * mime_stars -- initialized to zero. Set to the number of stars
+ * present in the best matching Accept header element.
+ * 1 for star/star, 2 for type/star and 3 for
+ * type/subtype.
+ *
+ * definite -- initialized to 1. Set to 0 if there is a match which
+ * makes the variant non-definite according to the rules
+ * in rfc2296.
+ */
+
+typedef struct var_rec {
+ request_rec *sub_req; /* May be NULL (is, for map files) */
+ char *mime_type; /* MUST be lowercase */
+ char *file_name;
+ const char *content_encoding;
+ array_header *content_languages; /* list of languages for this variant */
+ char *content_charset;
+ char *description;
+
+ /* The next five items give the quality values for the dimensions
+ * of negotiation for this variant. They are obtained from the
+ * appropriate header lines, except for source_quality, which
+ * is obtained from the variant itself (the 'qs' parameter value
+ * from the variant's mime-type). Apart from source_quality,
+ * these values are set when we find the quality for each variant
+ * (see best_match()). source_quality is set from the 'qs' parameter
+ * of the variant description or mime type: see set_mime_fields().
+ */
+ float lang_quality; /* quality of this variant's language */
+ float encoding_quality; /* ditto encoding */
+ float charset_quality; /* ditto charset */
+ float mime_type_quality; /* ditto media type */
+ float source_quality; /* source quality for this variant */
+
+ /* Now some special values */
+ float level; /* Auxiliary to content-type... */
+ float bytes; /* content length, if known */
+ int lang_index; /* pre HTTP/1.1 language priority stuff */
+ int is_pseudo_html; /* text/html, *or* the INCLUDES_MAGIC_TYPEs */
+
+ /* Above are all written-once properties of the variant. The
+ * three fields below are changed during negotiation:
+ */
+
+ float level_matched;
+ int mime_stars;
+ int definite;
+} var_rec;
+
+/* Something to carry around the state of negotiation (and to keep
+ * all of this thread-safe)...
+ */
+
+typedef struct {
+ pool *pool;
+ request_rec *r;
+ char *dir_name;
+ int accept_q; /* 1 if an Accept item has a q= param */
+ float default_lang_quality; /* fiddle lang q for variants with no lang */
+
+ /* the array pointers below are NULL if the corresponding accept
+ * headers are not present
+ */
+ array_header *accepts; /* accept_recs */
+ array_header *accept_encodings; /* accept_recs */
+ array_header *accept_charsets; /* accept_recs */
+ array_header *accept_langs; /* accept_recs */
+
+ array_header *avail_vars; /* available variants */
+
+ int count_multiviews_variants; /* number of variants found on disk */
+
+ int is_transparent; /* 1 if this resource is trans. negotiable */
+
+ int dont_fiddle_headers; /* 1 if we may not fiddle with accept hdrs */
+ int ua_supports_trans; /* 1 if ua supports trans negotiation */
+ int send_alternates; /* 1 if we want to send an Alternates header */
+ int may_choose; /* 1 if we may choose a variant for the client */
+ int use_rvsa; /* 1 if we must use RVSA/1.0 negotiation algo */
+} negotiation_state;
+
+/* A few functions to manipulate var_recs.
+ * Cleaning out the fields...
+ */
+
+static void clean_var_rec(var_rec *mime_info)
+{
+ mime_info->sub_req = NULL;
+ mime_info->mime_type = "";
+ mime_info->file_name = "";
+ mime_info->content_encoding = NULL;
+ mime_info->content_languages = NULL;
+ mime_info->content_charset = "";
+ mime_info->description = "";
+
+ mime_info->is_pseudo_html = 0;
+ mime_info->level = 0.0f;
+ mime_info->level_matched = 0.0f;
+ mime_info->bytes = 0.0f;
+ mime_info->lang_index = -1;
+ mime_info->mime_stars = 0;
+ mime_info->definite = 1;
+
+ mime_info->charset_quality = 1.0f;
+ mime_info->encoding_quality = 1.0f;
+ mime_info->lang_quality = 1.0f;
+ mime_info->mime_type_quality = 1.0f;
+ mime_info->source_quality = 0.0f;
+}
+
+/* Initializing the relevant fields of a variant record from the
+ * accept_info read out of its content-type, one way or another.
+ */
+
+static void set_mime_fields(var_rec *var, accept_rec *mime_info)
+{
+ var->mime_type = mime_info->name;
+ var->source_quality = mime_info->quality;
+ var->level = mime_info->level;
+ var->content_charset = mime_info->charset;
+
+ var->is_pseudo_html = (!strcmp(var->mime_type, "text/html")
+ || !strcmp(var->mime_type, INCLUDES_MAGIC_TYPE)
+ || !strcmp(var->mime_type, INCLUDES_MAGIC_TYPE3));
+}
+
+/* Create a variant list validator in r using info from vlistr. */
+
+static void set_vlist_validator(request_rec *r, request_rec *vlistr)
+{
+ /* Calculating the variant list validator is similar to
+ * calculating an etag for the source of the variant list
+ * information, so we use ap_make_etag(). Note that this
+ * validator can be 'weak' in extreme case.
+ */
+
+ ap_update_mtime (vlistr, vlistr->finfo.st_mtime);
+ r->vlist_validator = ap_make_etag(vlistr, 0);
+
+ /* ap_set_etag will later take r->vlist_validator into account
+ * when creating the etag header
+ */
+}
+
+
+/*****************************************************************
+ *
+ * Parsing (lists of) media types and their parameters, as seen in
+ * HTTPD header lines and elsewhere.
+ */
+
+/*
+ * Get a single mime type entry --- one media type and parameters;
+ * enter the values we recognize into the argument accept_rec
+ */
+
+static const char *get_entry(pool *p, accept_rec *result,
+ const char *accept_line)
+{
+ result->quality = 1.0f;
+ result->level = 0.0f;
+ result->charset = "";
+
+ /*
+ * Note that this handles what I gather is the "old format",
+ *
+ * Accept: text/html text/plain moo/zot
+ *
+ * without any compatibility kludges --- if the token after the
+ * MIME type begins with a semicolon, we know we're looking at parms,
+ * otherwise, we know we aren't. (So why all the pissing and moaning
+ * in the CERN server code? I must be missing something).
+ */
+
+ result->name = ap_get_token(p, &accept_line, 0);
+ ap_str_tolower(result->name); /* You want case-insensitive,
+ * you'll *get* case-insensitive.
+ */
+
+ /* KLUDGE!!! Default HTML to level 2.0 unless the browser
+ * *explicitly* says something else.
+ */
+
+ if (!strcmp(result->name, "text/html") && (result->level == 0.0)) {
+ result->level = 2.0f;
+ }
+ else if (!strcmp(result->name, INCLUDES_MAGIC_TYPE)) {
+ result->level = 2.0f;
+ }
+ else if (!strcmp(result->name, INCLUDES_MAGIC_TYPE3)) {
+ result->level = 3.0f;
+ }
+
+ while (*accept_line == ';') {
+ /* Parameters ... */
+
+ char *parm;
+ char *cp;
+ char *end;
+
+ ++accept_line;
+ parm = ap_get_token(p, &accept_line, 1);
+
+ /* Look for 'var = value' --- and make sure the var is in lcase. */
+
+ for (cp = parm; (*cp && !ap_isspace(*cp) && *cp != '='); ++cp) {
+ *cp = ap_tolower(*cp);
+ }
+
+ if (!*cp) {
+ continue; /* No '='; just ignore it. */
+ }
+
+ *cp++ = '\0'; /* Delimit var */
+ while (*cp && (ap_isspace(*cp) || *cp == '=')) {
+ ++cp;
+ }
+
+ if (*cp == '"') {
+ ++cp;
+ for (end = cp;
+ (*end && *end != '\n' && *end != '\r' && *end != '\"');
+ end++);
+ }
+ else {
+ for (end = cp; (*end && !ap_isspace(*end)); end++);
+ }
+ if (*end) {
+ *end = '\0'; /* strip ending quote or return */
+ }
+ ap_str_tolower(cp);
+
+ if (parm[0] == 'q'
+ && (parm[1] == '\0' || (parm[1] == 's' && parm[2] == '\0'))) {
+ result->quality = atof(cp);
+ }
+ else if (parm[0] == 'l' && !strcmp(&parm[1], "evel")) {
+ result->level = atof(cp);
+ }
+ else if (!strcmp(parm, "charset")) {
+ result->charset = cp;
+ }
+ }
+
+ if (*accept_line == ',') {
+ ++accept_line;
+ }
+
+ return accept_line;
+}
+
+/*****************************************************************
+ *
+ * Dealing with header lines ...
+ *
+ * Accept, Accept-Charset, Accept-Language and Accept-Encoding
+ * are handled by do_header_line() - they all have the same
+ * basic structure of a list of items of the format
+ * name; q=N; charset=TEXT
+ *
+ * where charset is only valid in Accept.
+ */
+
+static array_header *do_header_line(pool *p, const char *accept_line)
+{
+ array_header *accept_recs;
+
+ if (!accept_line) {
+ return NULL;
+ }
+
+ accept_recs = ap_make_array(p, 40, sizeof(accept_rec));
+
+ while (*accept_line) {
+ accept_rec *new = (accept_rec *) ap_push_array(accept_recs);
+ accept_line = get_entry(p, new, accept_line);
+ }
+
+ return accept_recs;
+}
+
+/* Given the text of the Content-Languages: line from the var map file,
+ * return an array containing the languages of this variant
+ */
+
+static array_header *do_languages_line(pool *p, const char **lang_line)
+{
+ array_header *lang_recs = ap_make_array(p, 2, sizeof(char *));
+
+ if (!lang_line) {
+ return lang_recs;
+ }
+
+ while (**lang_line) {
+ char **new = (char **) ap_push_array(lang_recs);
+ *new = ap_get_token(p, lang_line, 0);
+ ap_str_tolower(*new);
+ if (**lang_line == ',' || **lang_line == ';') {
+ ++(*lang_line);
+ }
+ }
+
+ return lang_recs;
+}
+
+/*****************************************************************
+ *
+ * Handling header lines from clients...
+ */
+
+static negotiation_state *parse_accept_headers(request_rec *r)
+{
+ negotiation_state *new =
+ (negotiation_state *) ap_pcalloc(r->pool, sizeof(negotiation_state));
+ accept_rec *elts;
+ table *hdrs = r->headers_in;
+ int i;
+
+ new->pool = r->pool;
+ new->r = r;
+ new->dir_name = ap_make_dirstr_parent(r->pool, r->filename);
+
+ new->accepts = do_header_line(r->pool, ap_table_get(hdrs, "Accept"));
+
+ /* calculate new->accept_q value */
+ if (new->accepts) {
+ elts = (accept_rec *) new->accepts->elts;
+
+ for (i = 0; i < new->accepts->nelts; ++i) {
+ if (elts[i].quality < 1.0) {
+ new->accept_q = 1;
+ }
+ }
+ }
+
+ new->accept_encodings =
+ do_header_line(r->pool, ap_table_get(hdrs, "Accept-Encoding"));
+ new->accept_langs =
+ do_header_line(r->pool, ap_table_get(hdrs, "Accept-Language"));
+ new->accept_charsets =
+ do_header_line(r->pool, ap_table_get(hdrs, "Accept-Charset"));
+
+ new->avail_vars = ap_make_array(r->pool, 40, sizeof(var_rec));
+
+ return new;
+}
+
+
+static void parse_negotiate_header(request_rec *r, negotiation_state *neg)
+{
+ const char *negotiate = ap_table_get(r->headers_in, "Negotiate");
+ char *tok;
+
+ /* First, default to no TCN, no Alternates, and the original Apache
+ * negotiation algorithm with fiddles for broken browser configs.
+ *
+ * To save network bandwidth, we do not configure to send an
+ * Alternates header to the user agent by default. User
+ * agents that want an Alternates header for agent-driven
+ * negotiation will have to request it by sending an
+ * appropriate Negotiate header.
+ */
+ neg->ua_supports_trans = 0;
+ neg->send_alternates = 0;
+ neg->may_choose = 1;
+ neg->use_rvsa = 0;
+ neg->dont_fiddle_headers = 0;
+
+ if (!negotiate)
+ return;
+
+ if (strcmp(negotiate, "trans") == 0) {
+ /* Lynx 2.7 and 2.8 send 'negotiate: trans' even though they
+ * do not support transparent content negotiation, so for Lynx we
+ * ignore the negotiate header when its contents are exactly "trans".
+ * If future versions of Lynx ever need to say 'negotiate: trans',
+ * they can send the equivalent 'negotiate: trans, trans' instead
+ * to avoid triggering the workaround below.
+ */
+ const char *ua = ap_table_get(r->headers_in, "User-Agent");
+
+ if (ua && (strncmp(ua, "Lynx", 4) == 0))
+ return;
+ }
+
+ neg->may_choose = 0; /* An empty Negotiate would require 300 response */
+
+ while ((tok = ap_get_list_item(neg->pool, &negotiate)) != NULL) {
+
+ if (strcmp(tok, "trans") == 0 ||
+ strcmp(tok, "vlist") == 0 ||
+ strcmp(tok, "guess-small") == 0 ||
+ ap_isdigit(tok[0]) ||
+ strcmp(tok, "*") == 0) {
+
+ /* The user agent supports transparent negotiation */
+ neg->ua_supports_trans = 1;
+
+ /* Send-alternates could be configurable, but note
+ * that it must be 1 if we have 'vlist' in the
+ * negotiate header.
+ */
+ neg->send_alternates = 1;
+
+ if (strcmp(tok, "1.0") == 0) {
+ /* we may use the RVSA/1.0 algorithm, configure for it */
+ neg->may_choose = 1;
+ neg->use_rvsa = 1;
+ neg->dont_fiddle_headers = 1;
+ }
+ else if (tok[0] == '*') {
+ /* we may use any variant selection algorithm, configure
+ * to use the Apache algorithm
+ */
+ neg->may_choose = 1;
+
+ /* We disable header fiddles on the assumption that a
+ * client sending Negotiate knows how to send correct
+ * headers which don't need fiddling.
+ */
+ neg->dont_fiddle_headers = 1;
+ }
+ }
+ }
+
+#ifdef NEG_DEBUG
+ fprintf(stderr, "dont_fiddle_headers=%d use_rvsa=%d ua_supports_trans=%d "
+ "send_alternates=%d, may_choose=%d\n",
+ neg->dont_fiddle_headers, neg->use_rvsa,
+ neg->ua_supports_trans, neg->send_alternates, neg->may_choose);
+#endif
+
+}
+
+/* Sometimes clients will give us no Accept info at all; this routine sets
+ * up the standard default for that case, and also arranges for us to be
+ * willing to run a CGI script if we find one. (In fact, we set up to
+ * dramatically prefer CGI scripts in cases where that's appropriate,
+ * e.g., POST or when URI includes query args or extra path info).
+ */
+static void maybe_add_default_accepts(negotiation_state *neg,
+ int prefer_scripts)
+{
+ accept_rec *new_accept;
+
+ if (!neg->accepts) {
+ neg->accepts = ap_make_array(neg->pool, 4, sizeof(accept_rec));
+
+ new_accept = (accept_rec *) ap_push_array(neg->accepts);
+
+ new_accept->name = "*/*";
+ new_accept->quality = 1.0f;
+ new_accept->level = 0.0f;
+ }
+
+ new_accept = (accept_rec *) ap_push_array(neg->accepts);
+
+ new_accept->name = CGI_MAGIC_TYPE;
+ if (neg->use_rvsa) {
+ new_accept->quality = 0;
+ }
+ else {
+ new_accept->quality = prefer_scripts ? 2.0f : 0.001f;
+ }
+ new_accept->level = 0.0f;
+}
+
+/*****************************************************************
+ *
+ * Parsing type-map files, in Roy's meta/http format augmented with
+ * #-comments.
+ */
+
+/* Reading RFC822-style header lines, ignoring #-comments and
+ * handling continuations.
+ */
+
+enum header_state {
+ header_eof, header_seen, header_sep
+};
+
+static enum header_state get_header_line(char *buffer, int len, FILE *map)
+{
+ char *buf_end = buffer + len;
+ char *cp;
+ int c;
+
+ /* Get a noncommented line */
+
+ do {
+ if (fgets(buffer, MAX_STRING_LEN, map) == NULL) {
+ return header_eof;
+ }
+ } while (buffer[0] == '#');
+
+ /* If blank, just return it --- this ends information on this variant */
+
+ for (cp = buffer; (*cp && ap_isspace(*cp)); ++cp) {
+ continue;
+ }
+
+ if (*cp == '\0') {
+ return header_sep;
+ }
+
+ /* If non-blank, go looking for header lines, but note that we still
+ * have to treat comments specially...
+ */
+
+ cp += strlen(cp);
+
+ while ((c = getc(map)) != EOF) {
+ if (c == '#') {
+ /* Comment line */
+ while ((c = getc(map)) != EOF && c != '\n') {
+ continue;
+ }
+ }
+ else if (ap_isspace(c)) {
+ /* Leading whitespace. POSSIBLE continuation line
+ * Also, possibly blank --- if so, we ungetc() the final newline
+ * so that we will pick up the blank line the next time 'round.
+ */
+
+ while (c != EOF && c != '\n' && ap_isspace(c)) {
+ c = getc(map);
+ }
+
+ ungetc(c, map);
+
+ if (c == '\n') {
+ return header_seen; /* Blank line */
+ }
+
+ /* Continuation */
+
+ while (cp < buf_end - 2 && (c = getc(map)) != EOF && c != '\n') {
+ *cp++ = c;
+ }
+
+ *cp++ = '\n';
+ *cp = '\0';
+ }
+ else {
+
+ /* Line beginning with something other than whitespace */
+
+ ungetc(c, map);
+ return header_seen;
+ }
+ }
+
+ return header_seen;
+}
+
+/* Stripping out RFC822 comments */
+
+static void strip_paren_comments(char *hdr)
+{
+ /* Hmmm... is this correct? In Roy's latest draft, (comments) can nest! */
+ /* Nope, it isn't correct. Fails to handle backslash escape as well. */
+
+ while (*hdr) {
+ if (*hdr == '"') {
+ hdr = strchr(hdr, '"');
+ if (hdr == NULL) {
+ return;
+ }
+ ++hdr;
+ }
+ else if (*hdr == '(') {
+ while (*hdr && *hdr != ')') {
+ *hdr++ = ' ';
+ }
+
+ if (*hdr) {
+ *hdr++ = ' ';
+ }
+ }
+ else {
+ ++hdr;
+ }
+ }
+}
+
+/* Getting to a header body from the header */
+
+static char *lcase_header_name_return_body(char *header, request_rec *r)
+{
+ char *cp = header;
+
+ for ( ; *cp && *cp != ':' ; ++cp) {
+ *cp = ap_tolower(*cp);
+ }
+
+ if (!*cp) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Syntax error in type map --- no ':': %s", r->filename);
+ return NULL;
+ }
+
+ do {
+ ++cp;
+ } while (*cp && ap_isspace(*cp));
+
+ if (!*cp) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Syntax error in type map --- no header body: %s",
+ r->filename);
+ return NULL;
+ }
+
+ return cp;
+}
+
+static int read_type_map(negotiation_state *neg, request_rec *rr)
+{
+ request_rec *r = neg->r;
+ FILE *map;
+ char buffer[MAX_STRING_LEN];
+ enum header_state hstate;
+ struct var_rec mime_info;
+ int has_content;
+
+ /* We are not using multiviews */
+ neg->count_multiviews_variants = 0;
+
+ map = ap_pfopen(neg->pool, rr->filename, "r");
+ if (map == NULL) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
+ "cannot access type map file: %s", rr->filename);
+ return HTTP_FORBIDDEN;
+ }
+
+ clean_var_rec(&mime_info);
+ has_content = 0;
+
+ do {
+ hstate = get_header_line(buffer, MAX_STRING_LEN, map);
+
+ if (hstate == header_seen) {
+ char *body1 = lcase_header_name_return_body(buffer, neg->r);
+ const char *body;
+
+ if (body1 == NULL) {
+ return SERVER_ERROR;
+ }
+
+ strip_paren_comments(body1);
+ body = body1;
+
+ if (!strncmp(buffer, "uri:", 4)) {
+ mime_info.file_name = ap_get_token(neg->pool, &body, 0);
+ }
+ else if (!strncmp(buffer, "content-type:", 13)) {
+ struct accept_rec accept_info;
+
+ get_entry(neg->pool, &accept_info, body);
+ set_mime_fields(&mime_info, &accept_info);
+ has_content = 1;
+ }
+ else if (!strncmp(buffer, "content-length:", 15)) {
+ mime_info.bytes = atof(body);
+ has_content = 1;
+ }
+ else if (!strncmp(buffer, "content-language:", 17)) {
+ mime_info.content_languages = do_languages_line(neg->pool,
+ &body);
+ has_content = 1;
+ }
+ else if (!strncmp(buffer, "content-encoding:", 17)) {
+ mime_info.content_encoding = ap_get_token(neg->pool, &body, 0);
+ has_content = 1;
+ }
+ else if (!strncmp(buffer, "description:", 12)) {
+ char *desc = ap_pstrdup(neg->pool, body);
+ char *cp;
+
+ for (cp = desc; *cp; ++cp) {
+ if (*cp=='\n') *cp=' ';
+ }
+ if (cp>desc) *(cp-1)=0;
+ mime_info.description = desc;
+ }
+ }
+ else {
+ if (*mime_info.file_name && has_content) {
+ void *new_var = ap_push_array(neg->avail_vars);
+
+ memcpy(new_var, (void *) &mime_info, sizeof(var_rec));
+ }
+
+ clean_var_rec(&mime_info);
+ has_content = 0;
+ }
+ } while (hstate != header_eof);
+
+ ap_pfclose(neg->pool, map);
+
+ set_vlist_validator(r, rr);
+
+ return OK;
+}
+
+
+/* Sort function used by read_types_multi. */
+static int variantsortf(var_rec *a, var_rec *b) {
+
+ /* First key is the source quality, sort in descending order. */
+
+ /* XXX: note that we currently implement no method of setting the
+ * source quality for multiviews variants, so we are always comparing
+ * 1.0 to 1.0 for now
+ */
+ if (a->source_quality < b->source_quality)
+ return 1;
+ if (a->source_quality > b->source_quality)
+ return -1;
+
+ /* Second key is the variant name */
+ return strcmp(a->file_name, b->file_name);
+}
+
+/*****************************************************************
+ *
+ * Same as read_type_map, except we use a filtered directory listing
+ * as the map...
+ */
+
+static int read_types_multi(negotiation_state *neg)
+{
+ request_rec *r = neg->r;
+
+ char *filp;
+ int prefix_len;
+ DIR *dirp;
+ struct DIR_TYPE *dir_entry;
+ struct var_rec mime_info;
+ struct accept_rec accept_info;
+ void *new_var;
+
+ clean_var_rec(&mime_info);
+
+ if (!(filp = strrchr(r->filename, '/'))) {
+ return DECLINED; /* Weird... */
+ }
+
+ if (strncmp(r->filename, "proxy:", 6) == 0) {
+ return DECLINED;
+ }
+
+ ++filp;
+ prefix_len = strlen(filp);
+
+ dirp = ap_popendir(neg->pool, neg->dir_name);
+
+ if (dirp == NULL) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
+ "cannot read directory for multi: %s", neg->dir_name);
+ return HTTP_FORBIDDEN;
+ }
+
+ while ((dir_entry = readdir(dirp))) {
+ request_rec *sub_req;
+
+ /* Do we have a match? */
+
+ if (strncmp(dir_entry->d_name, filp, prefix_len)) {
+ continue;
+ }
+ if (dir_entry->d_name[prefix_len] != '.') {
+ continue;
+ }
+
+ /* Yep. See if it's something which we have access to, and
+ * which has a known type and encoding (as opposed to something
+ * which we'll be slapping default_type on later).
+ */
+
+ sub_req = ap_sub_req_lookup_file(dir_entry->d_name, r);
+
+ /* If it has a handler, we'll pretend it's a CGI script,
+ * since that's a good indication of the sort of thing it
+ * might be doing.
+ */
+ if (sub_req->handler && !sub_req->content_type) {
+ sub_req->content_type = CGI_MAGIC_TYPE;
+ }
+
+ if (sub_req->status != HTTP_OK || !sub_req->content_type) {
+ ap_destroy_sub_req(sub_req);
+ continue;
+ }
+
+ /* If it's a map file, we use that instead of the map
+ * we're building...
+ */
+
+ if (((sub_req->content_type) &&
+ !strcmp(sub_req->content_type, MAP_FILE_MAGIC_TYPE)) ||
+ ((sub_req->handler) &&
+ !strcmp(sub_req->handler, "type-map"))) {
+
+ ap_pclosedir(neg->pool, dirp);
+ neg->avail_vars->nelts = 0;
+ if (sub_req->status != HTTP_OK) {
+ return sub_req->status;
+ }
+ return read_type_map(neg, sub_req);
+ }
+
+ /* Have reasonable variant --- gather notes. */
+
+ mime_info.sub_req = sub_req;
+ mime_info.file_name = ap_pstrdup(neg->pool, dir_entry->d_name);
+ if (sub_req->content_encoding) {
+ mime_info.content_encoding = sub_req->content_encoding;
+ }
+ if (sub_req->content_languages) {
+ mime_info.content_languages = sub_req->content_languages;
+ }
+
+ get_entry(neg->pool, &accept_info, sub_req->content_type);
+ set_mime_fields(&mime_info, &accept_info);
+
+ new_var = ap_push_array(neg->avail_vars);
+ memcpy(new_var, (void *) &mime_info, sizeof(var_rec));
+
+ neg->count_multiviews_variants++;
+
+ clean_var_rec(&mime_info);
+ }
+
+ ap_pclosedir(neg->pool, dirp);
+
+ set_vlist_validator(r, r);
+
+ /* Sort the variants into a canonical order. The negotiation
+ * result sometimes depends on the order of the variants. By
+ * sorting the variants into a canonical order, rather than using
+ * the order in which readdir() happens to return them, we ensure
+ * that the negotiation result will be consistent over filesystem
+ * backup/restores and over all mirror sites.
+ */
+
+ qsort((void *) neg->avail_vars->elts, neg->avail_vars->nelts,
+ sizeof(var_rec), (int (*)(const void *, const void *)) variantsortf);
+
+ return OK;
+}
+
+
+/*****************************************************************
+ * And now for the code you've been waiting for... actually
+ * finding a match to the client's requirements.
+ */
+
+/* Matching MIME types ... the star/star and foo/star commenting conventions
+ * are implemented here. (You know what I mean by star/star, but just
+ * try mentioning those three characters in a C comment). Using strcmp()
+ * is legit, because everything has already been smashed to lowercase.
+ *
+ * Note also that if we get an exact match on the media type, we update
+ * level_matched for use in level_cmp below...
+ *
+ * We also give a value for mime_stars, which is used later. It should
+ * be 1 for star/star, 2 for type/star and 3 for type/subtype.
+ */
+
+static int mime_match(accept_rec *accept_r, var_rec *avail)
+{
+ char *accept_type = accept_r->name;
+ char *avail_type = avail->mime_type;
+ int len = strlen(accept_type);
+
+ if (accept_type[0] == '*') { /* Anything matches star/star */
+ if (avail->mime_stars < 1) {
+ avail->mime_stars = 1;
+ }
+ return 1;
+ }
+ else if ((accept_type[len - 1] == '*') &&
+ !strncmp(accept_type, avail_type, len - 2)) {
+ if (avail->mime_stars < 2) {
+ avail->mime_stars = 2;
+ }
+ return 1;
+ }
+ else if (!strcmp(accept_type, avail_type)
+ || (!strcmp(accept_type, "text/html")
+ && (!strcmp(avail_type, INCLUDES_MAGIC_TYPE)
+ || !strcmp(avail_type, INCLUDES_MAGIC_TYPE3)))) {
+ if (accept_r->level >= avail->level) {
+ avail->level_matched = avail->level;
+ avail->mime_stars = 3;
+ return 1;
+ }
+ }
+
+ return OK;
+}
+
+/* This code implements a piece of the tie-breaking algorithm between
+ * variants of equal quality. This piece is the treatment of variants
+ * of the same base media type, but different levels. What we want to
+ * return is the variant at the highest level that the client explicitly
+ * claimed to accept.
+ *
+ * If all the variants available are at a higher level than that, or if
+ * the client didn't say anything specific about this media type at all
+ * and these variants just got in on a wildcard, we prefer the lowest
+ * level, on grounds that that's the one that the client is least likely
+ * to choke on.
+ *
+ * (This is all motivated by treatment of levels in HTML --- we only
+ * want to give level 3 to browsers that explicitly ask for it; browsers
+ * that don't, including HTTP/0.9 browsers that only get the implicit
+ * "Accept: * / *" [space added to avoid confusing cpp --- no, that
+ * syntax doesn't really work] should get HTML2 if available).
+ *
+ * (Note that this code only comes into play when we are choosing among
+ * variants of equal quality, where the draft standard gives us a fair
+ * bit of leeway about what to do. It ain't specified by the standard;
+ * rather, it is a choice made by this server about what to do in cases
+ * where the standard does not specify a unique course of action).
+ */
+
+static int level_cmp(var_rec *var1, var_rec *var2)
+{
+ /* Levels are only comparable between matching media types */
+
+ if (var1->is_pseudo_html && !var2->is_pseudo_html) {
+ return 0;
+ }
+
+ if (!var1->is_pseudo_html && strcmp(var1->mime_type, var2->mime_type)) {
+ return 0;
+ }
+ /* The result of the above if statements is that, if we get to
+ * here, both variants have the same mime_type or both are
+ * pseudo-html.
+ */
+
+ /* Take highest level that matched, if either did match. */
+
+ if (var1->level_matched > var2->level_matched) {
+ return 1;
+ }
+ if (var1->level_matched < var2->level_matched) {
+ return -1;
+ }
+
+ /* Neither matched. Take lowest level, if there's a difference. */
+
+ if (var1->level < var2->level) {
+ return 1;
+ }
+ if (var1->level > var2->level) {
+ return -1;
+ }
+
+ /* Tied */
+
+ return 0;
+}
+
+/* Finding languages. The main entry point is set_language_quality()
+ * which is called for each variant. It sets two elements in the
+ * variant record:
+ * language_quality - the 'q' value of the 'best' matching language
+ * from Accept-Language: header (HTTP/1.1)
+ * lang_index - Pre HTTP/1.1 language priority, using
+ * position of language on the Accept-Language:
+ * header, if present, else LanguagePriority
+ * directive order.
+ *
+ * When we do the variant checking for best variant, we use language
+ * quality first, and if a tie, language_index next (this only applies
+ * when _not_ using the RVSA/1.0 algorithm). If using the RVSA/1.0
+ * algorithm, lang_index is never used.
+ *
+ * set_language_quality() calls find_lang_index() and find_default_index()
+ * to set lang_index.
+ */
+
+static int find_lang_index(array_header *accept_langs, char *lang)
+{
+ accept_rec *accs;
+ int i;
+
+ if (!lang || !accept_langs) {
+ return -1;
+ }
+
+ accs = (accept_rec *) accept_langs->elts;
+
+ for (i = 0; i < accept_langs->nelts; ++i) {
+ if (!strncmp(lang, accs[i].name, strlen(accs[i].name))) {
+ return i;
+ }
+ }
+
+ return -1;
+}
+
+/* This function returns the priority of a given language
+ * according to LanguagePriority. It is used in case of a tie
+ * between several languages.
+ */
+
+static int find_default_index(neg_dir_config *conf, char *lang)
+{
+ array_header *arr;
+ int nelts;
+ char **elts;
+ int i;
+
+ if (!lang) {
+ return -1;
+ }
+
+ arr = conf->language_priority;
+ nelts = arr->nelts;
+ elts = (char **) arr->elts;
+
+ for (i = 0; i < nelts; ++i) {
+ if (!strcasecmp(elts[i], lang)) {
+ return i;
+ }
+ }
+
+ return -1;
+}
+
+/* set_default_lang_quality() sets the quality we apply to variants
+ * which have no language assigned to them. If none of the variants
+ * have a language, we are not negotiating on language, so all are
+ * acceptable, and we set the default q value to 1.0. However if
+ * some of the variants have languages, we set this default to 0.001.
+ * The value of this default will be applied to all variants with
+ * no explicit language -- which will have the effect of making them
+ * acceptable, but only if no variants with an explicit language
+ * are acceptable. The default q value set here is assigned to variants
+ * with no language type in set_language_quality().
+ *
+ * Note that if using the RVSA/1.0 algorithm, we don't use this
+ * fiddle.
+ */
+
+static void set_default_lang_quality(negotiation_state *neg)
+{
+ var_rec *avail_recs = (var_rec *) neg->avail_vars->elts;
+ int j;
+
+ if (!neg->dont_fiddle_headers) {
+ for (j = 0; j < neg->avail_vars->nelts; ++j) {
+ var_rec *variant = &avail_recs[j];
+ if (variant->content_languages &&
+ variant->content_languages->nelts) {
+ neg->default_lang_quality = 0.001f;
+ return;
+ }
+ }
+ }
+
+ neg->default_lang_quality = 1.0f;
+}
+
+/* Set the language_quality value in the variant record. Also
+ * assigns lang_index for back-compat.
+ *
+ * To find the language_quality value, we look for the 'q' value
+ * of the 'best' matching language on the Accept-Language
+ * header. The 'best' match is the language on Accept-Language
+ * header which matches the language of this variant either fully,
+ * or as far as the prefix marker (-). If two or more languages
+ * match, use the longest string from the Accept-Language header
+ * (see HTTP/1.1 [14.4])
+ *
+ * When a variant has multiple languages, we find the 'best'
+ * match for each variant language tag as above, then select the
+ * one with the highest q value. Because both the accept-header
+ * and variant can have multiple languages, we now have a hairy
+ * loop-within-a-loop here.
+ *
+ * If the variant has no language and we have no Accept-Language
+ * items, leave the quality at 1.0 and return.
+ *
+ * If the variant has no language, we use the default as set by
+ * set_default_lang_quality() (1.0 if we are not negotiating on
+ * language, 0.001 if we are).
+ *
+ * Following the setting of the language quality, we drop through to
+ * set the old 'lang_index'. This is set based on either the order
+ * of the languages on the Accept-Language header, or the
+ * order on the LanguagePriority directive. This is only used
+ * in the negotiation if the language qualities tie.
+ */
+
+static void set_language_quality(negotiation_state *neg, var_rec *variant)
+{
+ char *firstlang;
+ int idx;
+
+ if (!variant->content_languages || !variant->content_languages->nelts) {
+ /* This variant has no content-language, so use the default
+ * quality factor for variants with no content-language
+ * (previously set by set_default_lang_quality()).
+ * Leave the factor alone (it remains at 1.0) when we may not fiddle
+ * with the headers.
+ */
+ if (!neg->dont_fiddle_headers) {
+ variant->lang_quality = neg->default_lang_quality;
+ }
+ if (!neg->accept_langs) {
+ return; /* no accept-language header */
+ }
+
+ }
+ else {
+ /* Variant has one (or more) languages. Look for the best
+ * match. We do this by going through each language on the
+ * variant description looking for a match on the
+ * Accept-Language header. The best match is the longest
+ * matching language on the header. The final result is the
+ * best q value from all the languages on the variant
+ * description.
+ */
+
+ if (!neg->accept_langs) {
+ /* no accept-language header makes the variant indefinite */
+ variant->definite = 0;
+ }
+ else { /* There is an accept-language with 0 or more items */
+ accept_rec *accs = (accept_rec *) neg->accept_langs->elts;
+ accept_rec *best = NULL, *star = NULL;
+ accept_rec *bestthistag;
+ char *lang, *p;
+ float fiddle_q = 0.0f;
+ int any_match_on_star = 0;
+ int i, j, alen, longest_lang_range_len;
+
+ for (j = 0; j < variant->content_languages->nelts; ++j) {
+ p = NULL;
+ bestthistag = NULL;
+ longest_lang_range_len = 0;
+ alen = 0;
+
+ /* lang is the variant's language-tag, which is the one
+ * we are allowed to use the prefix of in HTTP/1.1
+ */
+ lang = ((char **) (variant->content_languages->elts))[j];
+
+ /* now find the best (i.e. longest) matching
+ * Accept-Language header language. We put the best match
+ * for this tag in bestthistag. We cannot update the
+ * overall best (based on q value) because the best match
+ * for this tag is the longest language item on the accept
+ * header, not necessarily the highest q.
+ */
+ for (i = 0; i < neg->accept_langs->nelts; ++i) {
+ if (!strcmp(accs[i].name, "*")) {
+ if (!star) {
+ star = &accs[i];
+ }
+ continue;
+ }
+ /* Find language. We match if either the variant
+ * language tag exactly matches the language range
+ * from the accept header, or a prefix of the variant
+ * language tag up to a '-' character matches the
+ * whole of the language range in the Accept-Language
+ * header. Note that HTTP/1.x allows any number of
+ * '-' characters in a tag or range, currently only
+ * tags with zero or one '-' characters are defined
+ * for general use (see rfc1766).
+ *
+ * We only use language range in the Accept-Language
+ * header the best match for the variant language tag
+ * if it is longer than the previous best match.
+ */
+
+ alen = strlen(accs[i].name);
+
+ if ((strlen(lang) >= alen) &&
+ !strncmp(lang, accs[i].name, alen) &&
+ ((lang[alen] == 0) || (lang[alen] == '-')) ) {
+
+ if (alen > longest_lang_range_len) {
+ longest_lang_range_len = alen;
+ bestthistag = &accs[i];
+ }
+ }
+
+ if (!bestthistag && !neg->dont_fiddle_headers) {
+ /* The next bit is a fiddle. Some browsers might
+ * be configured to send more specific language
+ * ranges than desirable. For example, an
+ * Accept-Language of en-US should never match
+ * variants with languages en or en-GB. But US
+ * English speakers might pick en-US as their
+ * language choice. So this fiddle checks if the
+ * language range has a prefix, and if so, it
+ * matches variants which match that prefix with a
+ * priority of 0.001. So a request for en-US would
+ * match variants of types en and en-GB, but at
+ * much lower priority than matches of en-US
+ * directly, or of any other language listed on
+ * the Accept-Language header. Note that this
+ * fiddle does not handle multi-level prefixes.
+ */
+ if ((p = strchr(accs[i].name, '-'))) {
+ int plen = p - accs[i].name;
+
+ if (!strncmp(lang, accs[i].name, plen)) {
+ fiddle_q = 0.001f;
+ }
+ }
+ }
+ }
+ /* Finished looking at Accept-Language headers, the best
+ * (longest) match is in bestthistag, or NULL if no match
+ */
+ if (!best ||
+ (bestthistag && bestthistag->quality > best->quality)) {
+ best = bestthistag;
+ }
+
+ /* See if the tag matches on a * in the Accept-Language
+ * header. If so, record this fact for later use
+ */
+ if (!bestthistag && star) {
+ any_match_on_star = 1;
+ }
+ }
+
+ /* If one of the language tags of the variant matched on *, we
+ * need to see if its q is better than that of any non-* match
+ * on any other tag of the variant. If so the * match takes
+ * precedence and the overall match is not definite.
+ */
+ if ( any_match_on_star &&
+ ((best && star->quality > best->quality) ||
+ (!best)) ) {
+ best = star;
+ variant->definite = 0;
+ }
+
+ variant->lang_quality = best ? best->quality : fiddle_q;
+ }
+ }
+
+ /* Now set the old lang_index field. Since this is old
+ * stuff anyway, don't bother with handling multiple languages
+ * per variant, just use the first one assigned to it
+ */
+ idx = 0;
+ if (variant->content_languages && variant->content_languages->nelts) {
+ firstlang = ((char **) variant->content_languages->elts)[0];
+ }
+ else {
+ firstlang = "";
+ }
+ if (!neg->accept_langs) { /* Client doesn't care */
+ idx = find_default_index((neg_dir_config *) ap_get_module_config(
+ neg->r->per_dir_config, &negotiation_module),
+ firstlang);
+ }
+ else { /* Client has Accept-Language */
+ idx = find_lang_index(neg->accept_langs, firstlang);
+ }
+ variant->lang_index = idx;
+
+ return;
+}
+
+/* Determining the content length --- if the map didn't tell us,
+ * we have to do a stat() and remember for next time.
+ *
+ * Grump. For Apache, even the first stat here may well be
+ * redundant (for multiviews) with a stat() done by the sub_req
+ * machinery. At some point, that ought to be fixed.
+ */
+
+static float find_content_length(negotiation_state *neg, var_rec *variant)
+{
+ struct stat statb;
+
+ if (variant->bytes == 0) {
+ char *fullname = ap_make_full_path(neg->pool, neg->dir_name,
+ variant->file_name);
+
+ if (stat(fullname, &statb) >= 0) {
+ /* Note, precision may be lost */
+ variant->bytes = (float) statb.st_size;
+ }
+ }
+
+ return variant->bytes;
+}
+
+/* For a given variant, find the best matching Accept: header
+ * and assign the Accept: header's quality value to the
+ * mime_type_quality field of the variant, for later use in
+ * determining the best matching variant.
+ */
+
+static void set_accept_quality(negotiation_state *neg, var_rec *variant)
+{
+ int i;
+ accept_rec *accept_recs;
+ float q = 0.0f;
+ int q_definite = 1;
+
+ /* if no Accept: header, leave quality alone (will
+ * remain at the default value of 1)
+ *
+ * XXX: This if is currently never true because of the effect of
+ * maybe_add_default_accepts().
+ */
+ if (!neg->accepts) {
+ if (variant->mime_type && *variant->mime_type)
+ variant->definite = 0;
+ return;
+ }
+
+ accept_recs = (accept_rec *) neg->accepts->elts;
+
+ /*
+ * Go through each of the ranges on the Accept: header,
+ * looking for the 'best' match with this variant's
+ * content-type. We use the best match's quality
+ * value (from the Accept: header) for this variant's
+ * mime_type_quality field.
+ *
+ * The best match is determined like this:
+ * type/type is better than type/ * is better than * / *
+ * if match is type/type, use the level mime param if available
+ */
+ for (i = 0; i < neg->accepts->nelts; ++i) {
+
+ accept_rec *type = &accept_recs[i];
+ int prev_mime_stars;
+
+ prev_mime_stars = variant->mime_stars;
+
+ if (!mime_match(type, variant)) {
+ continue; /* didn't match the content type at all */
+ }
+ else {
+ /* did match - see if there were less or more stars than
+ * in previous match
+ */
+ if (prev_mime_stars == variant->mime_stars) {
+ continue; /* more stars => not as good a match */
+ }
+ }
+
+ /* If we are allowed to mess with the q-values
+ * and have no explicit q= parameters in the accept header,
+ * make wildcards very low, so we have a low chance
+ * of ending up with them if there's something better.
+ */
+
+ if (!neg->dont_fiddle_headers && !neg->accept_q &&
+ variant->mime_stars == 1) {
+ q = 0.01f;
+ }
+ else if (!neg->dont_fiddle_headers && !neg->accept_q &&
+ variant->mime_stars == 2) {
+ q = 0.02f;
+ }
+ else {
+ q = type->quality;
+ }
+
+ q_definite = (variant->mime_stars == 3);
+ }
+ variant->mime_type_quality = q;
+ variant->definite = variant->definite && q_definite;
+
+}
+
+/* For a given variant, find the 'q' value of the charset given
+ * on the Accept-Charset line. If no charsets are listed,
+ * assume value of '1'.
+ */
+static void set_charset_quality(negotiation_state *neg, var_rec *variant)
+{
+ int i;
+ accept_rec *accept_recs;
+ char *charset = variant->content_charset;
+ accept_rec *star = NULL;
+
+ /* if no Accept-Charset: header, leave quality alone (will
+ * remain at the default value of 1)
+ */
+ if (!neg->accept_charsets) {
+ if (charset && *charset)
+ variant->definite = 0;
+ return;
+ }
+
+ accept_recs = (accept_rec *) neg->accept_charsets->elts;
+
+ if (charset == NULL || !*charset) {
+ /* Charset of variant not known */
+
+ /* if not a text / * type, leave quality alone */
+ if (!(!strncmp(variant->mime_type, "text/", 5)
+ || !strcmp(variant->mime_type, INCLUDES_MAGIC_TYPE)
+ || !strcmp(variant->mime_type, INCLUDES_MAGIC_TYPE3)
+ ))
+ return;
+
+ /* Don't go guessing if we are in strict header mode,
+ * e.g. when running the rvsa, as any guess won't be reflected
+ * in the variant list or content-location headers.
+ */
+ if (neg->dont_fiddle_headers)
+ return;
+
+ charset = "iso-8859-1"; /* The default charset for HTTP text types */
+ }
+
+ /*
+ * Go through each of the items on the Accept-Charset header,
+ * looking for a match with this variant's charset. If none
+ * match, charset is unacceptable, so set quality to 0.
+ */
+ for (i = 0; i < neg->accept_charsets->nelts; ++i) {
+
+ accept_rec *type = &accept_recs[i];
+
+ if (!strcmp(type->name, charset)) {
+ variant->charset_quality = type->quality;
+ return;
+ }
+ else if (strcmp(type->name, "*") == 0) {
+ star = type;
+ }
+ }
+ /* No explicit match */
+ if (star) {
+ variant->charset_quality = star->quality;
+ variant->definite = 0;
+ return;
+ }
+ /* If this variant is in charset iso-8859-1, the default is 1.0 */
+ if (strcmp(charset, "iso-8859-1") == 0) {
+ variant->charset_quality = 1.0f;
+ }
+ else {
+ variant->charset_quality = 0.0f;
+ }
+}
+
+
+/* is_identity_encoding is included for back-compat, but does anyone
+ * use 7bit, 8bin or binary in their var files??
+ */
+
+static int is_identity_encoding(const char *enc)
+{
+ return (!enc || !enc[0] || !strcmp(enc, "7bit") || !strcmp(enc, "8bit")
+ || !strcmp(enc, "binary"));
+}
+
+/*
+ * set_encoding_quality determines whether the encoding for a particular
+ * variant is acceptable for the user-agent.
+ *
+ * The rules for encoding are that if the user-agent does not supply
+ * any Accept-Encoding header, then all encodings are allowed but a
+ * variant with no encoding should be preferred.
+ * If there is an empty Accept-Encoding header, then no encodings are
+ * acceptable. If there is a non-empty Accept-Encoding header, then
+ * any of the listed encodings are acceptable, as well as no encoding
+ * unless the "identity" encoding is specifically excluded.
+ */
+static void set_encoding_quality(negotiation_state *neg, var_rec *variant)
+{
+ accept_rec *accept_recs;
+ const char *enc = variant->content_encoding;
+ accept_rec *star = NULL;
+ float value_if_not_found = 0.0f;
+ int i;
+
+ if (!neg->accept_encodings) {
+ /* We had no Accept-Encoding header, assume that all
+ * encodings are acceptable with a low quality,
+ * but we prefer no encoding if available.
+ */
+ if (!enc || is_identity_encoding(enc))
+ variant->encoding_quality = 1.0f;
+ else
+ variant->encoding_quality = 0.5f;
+
+ return;
+ }
+
+ if (!enc || is_identity_encoding(enc)) {
+ enc = "identity";
+ value_if_not_found = 0.0001f;
+ }
+
+ accept_recs = (accept_rec *) neg->accept_encodings->elts;
+
+ /* Go through each of the encodings on the Accept-Encoding: header,
+ * looking for a match with our encoding. x- prefixes are ignored.
+ */
+ if (enc[0] == 'x' && enc[1] == '-') {
+ enc += 2;
+ }
+ for (i = 0; i < neg->accept_encodings->nelts; ++i) {
+
+ char *name = accept_recs[i].name;
+
+ if (name[0] == 'x' && name[1] == '-') {
+ name += 2;
+ }
+
+ if (!strcmp(name, enc)) {
+ variant->encoding_quality = accept_recs[i].quality;
+ return;
+ }
+
+ if (strcmp(name, "*") == 0) {
+ star = &accept_recs[i];
+ }
+
+ }
+ /* No explicit match */
+ if (star) {
+ variant->encoding_quality = star->quality;
+ return;
+ }
+
+ /* Encoding not found on Accept-Encoding: header, so it is
+ * _not_ acceptable unless it is the identity (no encoding)
+ */
+ variant->encoding_quality = value_if_not_found;
+}
+
+/*************************************************************
+ * Possible results of the variant selection algorithm
+ */
+enum algorithm_results {
+ alg_choice = 1, /* choose variant */
+ alg_list /* list variants */
+};
+
+/* Below is the 'best_match' function. It returns an int, which has
+ * one of the two values alg_choice or alg_list, which give the result
+ * of the variant selection algorithm. alg_list means that no best
+ * variant was found by the algorithm, alg_choice means that a best
+ * variant was found and should be returned. The list/choice
+ * terminology comes from TCN (rfc2295), but is used in a more generic
+ * way here. The best variant is returned in *pbest. best_match has
+ * two possible algorithms for determining the best variant: the
+ * RVSA/1.0 algorithm (from RFC2296), and the standard Apache
+ * algorithm. These are split out into separate functions
+ * (is_variant_better_rvsa() and is_variant_better()). Selection of
+ * one is through the neg->use_rvsa flag.
+ *
+ * The call to best_match also creates full information, including
+ * language, charset, etc quality for _every_ variant. This is needed
+ * for generating a correct Vary header, and can be used for the
+ * Alternates header, the human-readable list responses and 406 errors.
+ */
+
+/* Firstly, the RVSA/1.0 (HTTP Remote Variant Selection Algorithm
+ * v1.0) from rfc2296. This is the algorithm that goes together with
+ * transparent content negotiation (TCN).
+ */
+static int is_variant_better_rvsa(negotiation_state *neg, var_rec *variant,
+ var_rec *best, float *p_bestq)
+{
+ float bestq = *p_bestq, q;
+
+ /* TCN does not cover negotiation on content-encoding. For now,
+ * we ignore the encoding unless it was explicitly excluded.
+ */
+ if (variant->encoding_quality == 0.0f)
+ return 0;
+
+ q = variant->mime_type_quality *
+ variant->source_quality *
+ variant->charset_quality *
+ variant->lang_quality;
+
+ /* RFC 2296 calls for the result to be rounded to 5 decimal places,
+ * but we don't do that because it serves no useful purpose other
+ * than to ensure that a remote algorithm operates on the same
+ * precision as ours. That is silly, since what we obviously want
+ * is for the algorithm to operate on the best available precision
+ * regardless of who runs it. Since the above calculation may
+ * result in significant variance at 1e-12, rounding would be bogus.
+ */
+
+#ifdef NEG_DEBUG
+ fprintf(stderr, "Variant: file=%s type=%s lang=%s sourceq=%1.3f "
+ "mimeq=%1.3f langq=%1.3f charq=%1.3f encq=%1.3f "
+ "q=%1.5f definite=%d\n",
+ (variant->file_name ? variant->file_name : ""),
+ (variant->mime_type ? variant->mime_type : ""),
+ (variant->content_languages
+ ? ap_array_pstrcat(neg->pool, variant->content_languages, ',')
+ : ""),
+ variant->source_quality,
+ variant->mime_type_quality,
+ variant->lang_quality,
+ variant->charset_quality,
+ variant->encoding_quality,
+ q,
+ variant->definite);
+#endif
+
+ if (q <= 0.0f) {
+ return 0;
+ }
+ if (q > bestq) {
+ *p_bestq = q;
+ return 1;
+ }
+ if (q == bestq) {
+ /* If the best variant's encoding is of lesser quality than
+ * this variant, then we prefer this variant
+ */
+ if (variant->encoding_quality > best->encoding_quality) {
+ *p_bestq = q;
+ return 1;
+ }
+ }
+ return 0;
+}
+
+/* Negotiation algorithm as used by previous versions of Apache
+ * (just about).
+ */
+
+static int is_variant_better(negotiation_state *neg, var_rec *variant,
+ var_rec *best, float *p_bestq)
+{
+ float bestq = *p_bestq, q;
+ int levcmp;
+
+ /* For non-transparent negotiation, server can choose how
+ * to handle the negotiation. We'll use the following in
+ * order: content-type, language, content-type level, charset,
+ * content encoding, content length.
+ *
+ * For each check, we have three possible outcomes:
+ * This variant is worse than current best: return 0
+ * This variant is better than the current best:
+ * assign this variant's q to *p_bestq, and return 1
+ * This variant is just as desirable as the current best:
+ * drop through to the next test.
+ *
+ * This code is written in this long-winded way to allow future
+ * customisation, either by the addition of additional
+ * checks, or to allow the order of the checks to be determined
+ * by configuration options (e.g. we might prefer to check
+ * language quality _before_ content type).
+ */
+
+ /* First though, eliminate this variant if it is not
+ * acceptable by type, charset, encoding or language.
+ */
+
+#ifdef NEG_DEBUG
+ fprintf(stderr, "Variant: file=%s type=%s lang=%s sourceq=%1.3f "
+ "mimeq=%1.3f langq=%1.3f langidx=%d charq=%1.3f encq=%1.3f \n",
+ (variant->file_name ? variant->file_name : ""),
+ (variant->mime_type ? variant->mime_type : ""),
+ (variant->content_languages
+ ? ap_array_pstrcat(neg->pool, variant->content_languages, ',')
+ : ""),
+ variant->source_quality,
+ variant->mime_type_quality,
+ variant->lang_quality,
+ variant->lang_index,
+ variant->charset_quality,
+ variant->encoding_quality);
+#endif
+
+ if (variant->encoding_quality == 0.0f ||
+ variant->lang_quality == 0.0f ||
+ variant->source_quality == 0.0f ||
+ variant->charset_quality == 0.0f ||
+ variant->mime_type_quality == 0.0f) {
+ return 0; /* don't consider unacceptables */
+ }
+
+ q = variant->mime_type_quality * variant->source_quality;
+ if (q == 0.0 || q < bestq) {
+ return 0;
+ }
+ if (q > bestq || !best) {
+ *p_bestq = q;
+ return 1;
+ }
+
+ /* language */
+ if (variant->lang_quality < best->lang_quality) {
+ return 0;
+ }
+ if (variant->lang_quality > best->lang_quality) {
+ *p_bestq = q;
+ return 1;
+ }
+
+ /* if language qualities were equal, try the LanguagePriority stuff */
+ if (best->lang_index != -1 &&
+ (variant->lang_index == -1 || variant->lang_index > best->lang_index)) {
+ return 0;
+ }
+ if (variant->lang_index != -1 &&
+ (best->lang_index == -1 || variant->lang_index < best->lang_index)) {
+ *p_bestq = q;
+ return 1;
+ }
+
+ /* content-type level (sometimes used with text/html, though we
+ * support it on other types too)
+ */
+ levcmp = level_cmp(variant, best);
+ if (levcmp == -1) {
+ return 0;
+ }
+ if (levcmp == 1) {
+ *p_bestq = q;
+ return 1;
+ }
+
+ /* charset */
+ if (variant->charset_quality < best->charset_quality) {
+ return 0;
+ }
+ /* If the best variant's charset is ISO-8859-1 and this variant has
+ * the same charset quality, then we prefer this variant
+ */
+
+ if (variant->charset_quality > best->charset_quality ||
+ ((variant->content_charset != NULL &&
+ *variant->content_charset != '\0' &&
+ strcmp(variant->content_charset, "iso-8859-1") != 0) &&
+ (best->content_charset == NULL ||
+ *best->content_charset == '\0' ||
+ strcmp(best->content_charset, "iso-8859-1") == 0))) {
+ *p_bestq = q;
+ return 1;
+ }
+
+ /* Prefer the highest value for encoding_quality.
+ */
+ if (variant->encoding_quality < best->encoding_quality) {
+ return 0;
+ }
+ if (variant->encoding_quality > best->encoding_quality) {
+ *p_bestq = q;
+ return 1;
+ }
+
+ /* content length if all else equal */
+ if (find_content_length(neg, variant) >= find_content_length(neg, best)) {
+ return 0;
+ }
+
+ /* ok, to get here means every thing turned out equal, except
+ * we have a shorter content length, so use this variant
+ */
+ *p_bestq = q;
+ return 1;
+}
+
+static int best_match(negotiation_state *neg, var_rec **pbest)
+{
+ int j;
+ var_rec *best = NULL;
+ float bestq = 0.0f;
+ enum algorithm_results algorithm_result;
+
+ var_rec *avail_recs = (var_rec *) neg->avail_vars->elts;
+
+ set_default_lang_quality(neg);
+
+ /*
+ * Find the 'best' variant
+ */
+
+ for (j = 0; j < neg->avail_vars->nelts; ++j) {
+ var_rec *variant = &avail_recs[j];
+
+ /* Find all the relevant 'quality' values from the
+ * Accept... headers, and store in the variant. This also
+ * prepares for sending an Alternates header etc so we need to
+ * do it even if we do not actually plan to find a best
+ * variant.
+ */
+ set_accept_quality(neg, variant);
+ set_language_quality(neg, variant);
+ set_encoding_quality(neg, variant);
+ set_charset_quality(neg, variant);
+
+ /* Only do variant selection if we may actually choose a
+ * variant for the client
+ */
+ if (neg->may_choose) {
+
+ /* Now find out if this variant is better than the current
+ * best, either using the RVSA/1.0 algorithm, or Apache's
+ * internal server-driven algorithm. Presumably other
+ * server-driven algorithms are possible, and could be
+ * implemented here.
+ */
+
+ if (neg->use_rvsa) {
+ if (is_variant_better_rvsa(neg, variant, best, &bestq)) {
+ best = variant;
+ }
+ }
+ else {
+ if (is_variant_better(neg, variant, best, &bestq)) {
+ best = variant;
+ }
+ }
+ }
+ }
+
+ /* We now either have a best variant, or no best variant */
+
+ if (neg->use_rvsa) {
+ /* calculate result for RVSA/1.0 algorithm:
+ * only a choice response if the best variant has q>0
+ * and is definite
+ */
+ algorithm_result = (best && best->definite) && (bestq > 0) ?
+ alg_choice : alg_list;
+ }
+ else {
+ /* calculate result for Apache negotiation algorithm */
+ algorithm_result = bestq > 0 ? alg_choice : alg_list;
+ }
+
+ /* Returning a choice response with a non-neighboring variant is a
+ * protocol security error in TCN (see rfc2295). We do *not*
+ * verify here that the variant and URI are neighbors, even though
+ * we may return alg_choice. We depend on the environment (the
+ * caller) to only declare the resource transparently negotiable if
+ * all variants are neighbors.
+ */
+ *pbest = best;
+ return algorithm_result;
+}
+
+/* Sets response headers for a negotiated response.
+ * neg->is_transparent determines whether a transparently negotiated
+ * response or a plain `server driven negotiation' response is
+ * created. Applicable headers are Alternates, Vary, and TCN.
+ *
+ * The Vary header we create is sometimes longer than is required for
+ * the correct caching of negotiated results by HTTP/1.1 caches. For
+ * example if we have 3 variants x.html, x.ps.en and x.ps.nl, and if
+ * the Accept: header assigns a 0 quality to .ps, then the results of
+ * the two server-side negotiation algorithms we currently implement
+ * will never depend on Accept-Language so we could return `Vary:
+ * negotiate, accept' instead of the longer 'Vary: negotiate, accept,
+ * accept-language' which the code below will return. A routine for
+ * computing the exact minimal Vary header would be a huge pain to code
+ * and maintain though, especially because we need to take all possible
+ * twiddles in the server-side negotiation algorithms into account.
+ */
+static void set_neg_headers(request_rec *r, negotiation_state *neg,
+ int alg_result)
+{
+ table *hdrs;
+ var_rec *avail_recs = (var_rec *) neg->avail_vars->elts;
+ const char *sample_type = NULL;
+ const char *sample_language = NULL;
+ const char *sample_encoding = NULL;
+ const char *sample_charset = NULL;
+ char *lang;
+ char *qstr;
+ char *lenstr;
+ long len;
+ array_header *arr;
+ int max_vlist_array = (neg->avail_vars->nelts * 21);
+ int first_variant = 1;
+ int vary_by_type = 0;
+ int vary_by_language = 0;
+ int vary_by_charset = 0;
+ int vary_by_encoding = 0;
+ int j;
+
+ /* In order to avoid O(n^2) memory copies in building Alternates,
+ * we preallocate a table with the maximum substrings possible,
+ * fill it with the variant list, and then concatenate the entire array.
+ * Note that if you change the number of substrings pushed, you also
+ * need to change the calculation of max_vlist_array above.
+ */
+ if (neg->send_alternates && neg->avail_vars->nelts)
+ arr = ap_make_array(r->pool, max_vlist_array, sizeof(char *));
+ else
+ arr = NULL;
+
+ /* Put headers into err_headers_out, since send_http_header()
+ * outputs both headers_out and err_headers_out.
+ */
+ hdrs = r->err_headers_out;
+
+ for (j = 0; j < neg->avail_vars->nelts; ++j) {
+ var_rec *variant = &avail_recs[j];
+
+ if (variant->content_languages && variant->content_languages->nelts) {
+ lang = ap_array_pstrcat(r->pool, variant->content_languages, ',');
+ }
+ else {
+ lang = NULL;
+ }
+
+ /* Calculate Vary by looking for any difference between variants */
+
+ if (first_variant) {
+ sample_type = variant->mime_type;
+ sample_charset = variant->content_charset;
+ sample_language = lang;
+ sample_encoding = variant->content_encoding;
+ }
+ else {
+ if (!vary_by_type &&
+ strcmp(sample_type ? sample_type : "",
+ variant->mime_type ? variant->mime_type : "")) {
+ vary_by_type = 1;
+ }
+ if (!vary_by_charset &&
+ strcmp(sample_charset ? sample_charset : "",
+ variant->content_charset ?
+ variant->content_charset : "")) {
+ vary_by_charset = 1;
+ }
+ if (!vary_by_language &&
+ strcmp(sample_language ? sample_language : "",
+ lang ? lang : "")) {
+ vary_by_language = 1;
+ }
+ if (!vary_by_encoding &&
+ strcmp(sample_encoding ? sample_encoding : "",
+ variant->content_encoding ?
+ variant->content_encoding : "")) {
+ vary_by_encoding = 1;
+ }
+ }
+ first_variant = 0;
+
+ if (!neg->send_alternates)
+ continue;
+
+ /* Generate the string components for this Alternates entry */
+
+ *((const char **) ap_push_array(arr)) = "{\"";
+ *((const char **) ap_push_array(arr)) = variant->file_name;
+ *((const char **) ap_push_array(arr)) = "\" ";
+
+ qstr = (char *) ap_palloc(r->pool, 6);
+ ap_snprintf(qstr, 6, "%1.3f", variant->source_quality);
+
+ /* Strip trailing zeros (saves those valuable network bytes) */
+ if (qstr[4] == '0') {
+ qstr[4] = '\0';
+ if (qstr[3] == '0') {
+ qstr[3] = '\0';
+ if (qstr[2] == '0') {
+ qstr[1] = '\0';
+ }
+ }
+ }
+ *((const char **) ap_push_array(arr)) = qstr;
+
+ if (variant->mime_type && *variant->mime_type) {
+ *((const char **) ap_push_array(arr)) = " {type ";
+ *((const char **) ap_push_array(arr)) = variant->mime_type;
+ *((const char **) ap_push_array(arr)) = "}";
+ }
+ if (variant->content_charset && *variant->content_charset) {
+ *((const char **) ap_push_array(arr)) = " {charset ";
+ *((const char **) ap_push_array(arr)) = variant->content_charset;
+ *((const char **) ap_push_array(arr)) = "}";
+ }
+ if (lang) {
+ *((const char **) ap_push_array(arr)) = " {language ";
+ *((const char **) ap_push_array(arr)) = lang;
+ *((const char **) ap_push_array(arr)) = "}";
+ }
+ if (variant->content_encoding && *variant->content_encoding) {
+ /* Strictly speaking, this is non-standard, but so is TCN */
+
+ *((const char **) ap_push_array(arr)) = " {encoding ";
+ *((const char **) ap_push_array(arr)) = variant->content_encoding;
+ *((const char **) ap_push_array(arr)) = "}";
+ }
+
+ /* Note that the Alternates specification (in rfc2295) does
+ * not require that we include {length x}, so we could omit it
+ * if determining the length is too expensive. We currently
+ * always include it though. 22 bytes is enough for 2^64.
+ *
+ * If the variant is a CGI script, find_content_length would
+ * return the length of the script, not the output it
+ * produces, so we check for the presence of a handler and if
+ * there is one we don't add a length.
+ *
+ * XXX: TODO: This check does not detect a CGI script if we
+ * get the variant from a type map. This needs to be fixed
+ * (without breaking things if the type map specifies a
+ * content-length, which currently leads to the correct result).
+ */
+ if (!(variant->sub_req && variant->sub_req->handler)
+ && (len = find_content_length(neg, variant)) != 0) {
+
+ lenstr = (char *) ap_palloc(r->pool, 22);
+ ap_snprintf(lenstr, 22, "%ld", len);
+ *((const char **) ap_push_array(arr)) = " {length ";
+ *((const char **) ap_push_array(arr)) = lenstr;
+ *((const char **) ap_push_array(arr)) = "}";
+ }
+
+ *((const char **) ap_push_array(arr)) = "}";
+ *((const char **) ap_push_array(arr)) = ", "; /* trimmed below */
+ }
+
+ if (neg->send_alternates && neg->avail_vars->nelts) {
+ arr->nelts--; /* remove last comma */
+ ap_table_mergen(hdrs, "Alternates",
+ ap_array_pstrcat(r->pool, arr, '\0'));
+ }
+
+ if (neg->is_transparent || vary_by_type || vary_by_language ||
+ vary_by_language || vary_by_charset || vary_by_encoding) {
+
+ ap_table_mergen(hdrs, "Vary", 2 + ap_pstrcat(r->pool,
+ neg->is_transparent ? ", negotiate" : "",
+ vary_by_type ? ", accept" : "",
+ vary_by_language ? ", accept-language" : "",
+ vary_by_charset ? ", accept-charset" : "",
+ vary_by_encoding ? ", accept-encoding" : "", NULL));
+ }
+
+ if (neg->is_transparent) { /* Create TCN response header */
+ ap_table_setn(hdrs, "TCN",
+ alg_result == alg_list ? "list" : "choice");
+ }
+}
+
+/**********************************************************************
+ *
+ * Return an HTML list of variants. This is output as part of the
+ * choice response or 406 status body.
+ */
+
+static char *make_variant_list(request_rec *r, negotiation_state *neg)
+{
+ array_header *arr;
+ int i;
+ int max_vlist_array = (neg->avail_vars->nelts * 15) + 2;
+
+ /* In order to avoid O(n^2) memory copies in building the list,
+ * we preallocate a table with the maximum substrings possible,
+ * fill it with the variant list, and then concatenate the entire array.
+ */
+ arr = ap_make_array(r->pool, max_vlist_array, sizeof(char *));
+
+ *((const char **) ap_push_array(arr)) = "Available variants:\n\n";
+
+ for (i = 0; i < neg->avail_vars->nelts; ++i) {
+ var_rec *variant = &((var_rec *) neg->avail_vars->elts)[i];
+ char *filename = variant->file_name ? variant->file_name : "";
+ array_header *languages = variant->content_languages;
+ char *description = variant->description ? variant->description : "";
+
+ /* The format isn't very neat, and it would be nice to make
+ * the tags human readable (eg replace 'language en' with 'English').
+ * Note that if you change the number of substrings pushed, you also
+ * need to change the calculation of max_vlist_array above.
+ */
+ *((const char **) ap_push_array(arr)) = "- ";
+ *((const char **) ap_push_array(arr)) = filename;
+ *((const char **) ap_push_array(arr)) = " ";
+ *((const char **) ap_push_array(arr)) = description;
+
+ if (variant->mime_type && *variant->mime_type) {
+ *((const char **) ap_push_array(arr)) = ", type ";
+ *((const char **) ap_push_array(arr)) = variant->mime_type;
+ }
+ if (languages && languages->nelts) {
+ *((const char **) ap_push_array(arr)) = ", language ";
+ *((const char **) ap_push_array(arr)) = ap_array_pstrcat(r->pool,
+ languages, ',');
+ }
+ if (variant->content_charset && *variant->content_charset) {
+ *((const char **) ap_push_array(arr)) = ", charset ";
+ *((const char **) ap_push_array(arr)) = variant->content_charset;
+ }
+ if (variant->content_encoding) {
+ *((const char **) ap_push_array(arr)) = ", encoding ";
+ *((const char **) ap_push_array(arr)) = variant->content_encoding;
+ }
+ *((const char **) ap_push_array(arr)) = "\n";
+ }
+ *((const char **) ap_push_array(arr)) = "
\n";
+
+ return ap_array_pstrcat(r->pool, arr, '\0');
+}
+
+static void store_variant_list(request_rec *r, negotiation_state *neg)
+{
+ if (r->main == NULL) {
+ ap_table_setn(r->notes, "variant-list", make_variant_list(r, neg));
+ }
+ else {
+ ap_table_setn(r->main->notes, "variant-list",
+ make_variant_list(r->main, neg));
+ }
+}
+
+/* Called if we got a "Choice" response from the variant selection algorithm.
+ * It checks the result of the chosen variant to see if it
+ * is itself negotiated (if so, return error VARIANT_ALSO_VARIES).
+ * Otherwise, add the appropriate headers to the current response.
+ */
+
+static int setup_choice_response(request_rec *r, negotiation_state *neg,
+ var_rec *variant)
+{
+ request_rec *sub_req;
+ const char *sub_vary;
+
+ if (!variant->sub_req) {
+ int status;
+
+ sub_req = ap_sub_req_lookup_file(variant->file_name, r);
+ status = sub_req->status;
+
+ if (status != HTTP_OK &&
+ !ap_table_get(sub_req->err_headers_out, "TCN")) {
+ ap_destroy_sub_req(sub_req);
+ return status;
+ }
+ variant->sub_req = sub_req;
+ }
+ else {
+ sub_req = variant->sub_req;
+ }
+
+ /* The variant selection algorithm told us to return a "Choice"
+ * response. This is the normal variant response, with
+ * some extra headers. First, ensure that the chosen
+ * variant did or will not itself engage in transparent negotiation.
+ * If not, set the appropriate headers, and fall through to
+ * the normal variant handling
+ */
+
+ /* This catches the error that a transparent type map selects a
+ * transparent multiviews resource as the best variant.
+ *
+ * XXX: We do not signal an error if a transparent type map
+ * selects a _non_transparent multiviews resource as the best
+ * variant, because we can generate a legal negotiation response
+ * in this case. In this case, the vlist_validator of the
+ * nontransparent subrequest will be lost however. This could
+ * lead to cases in which a change in the set of variants or the
+ * negotiation algorithm of the nontransparent resource is never
+ * propagated up to a HTTP/1.1 cache which interprets Vary. To be
+ * completely on the safe side we should return VARIANT_ALSO_VARIES
+ * for this type of recursive negotiation too.
+ */
+ if (neg->is_transparent &&
+ ap_table_get(sub_req->err_headers_out, "TCN")) {
+ return VARIANT_ALSO_VARIES;
+ }
+
+ /* This catches the error that a transparent type map recursively
+ * selects, as the best variant, another type map which itself
+ * causes transparent negotiation to be done.
+ *
+ * XXX: Actually, we catch this error by catching all cases of
+ * type map recursion. There are some borderline recursive type
+ * map arrangements which would not produce transparent
+ * negotiation protocol errors or lack of cache propagation
+ * problems, but such arrangements are very hard to detect at this
+ * point in the control flow, so we do not bother to single them
+ * out.
+ *
+ * Recursive type maps imply a recursive arrangement of negotiated
+ * resources which is visible to outside clients, and this is not
+ * supported by the transparent negotiation caching protocols, so
+ * if we are to have generic support for recursive type maps, we
+ * have to create some configuration setting which makes all type
+ * maps non-transparent when recursion is enabled. Also, if we
+ * want recursive type map support which ensures propagation of
+ * type map changes into HTTP/1.1 caches that handle Vary, we
+ * would have to extend the current mechanism for generating
+ * variant list validators.
+ */
+ if (sub_req->handler && strcmp(sub_req->handler, "type-map") == 0) {
+ return VARIANT_ALSO_VARIES;
+ }
+
+ /* This adds an appropriate Variant-Vary header if the subrequest
+ * is a multiviews resource.
+ *
+ * XXX: TODO: Note that this does _not_ handle any Vary header
+ * returned by a CGI if sub_req is a CGI script, because we don't
+ * see that Vary header yet at this point in the control flow.
+ * This won't cause any cache consistency problems _unless_ the
+ * CGI script also returns a Cache-Control header marking the
+ * response as cachable. This needs to be fixed, also there are
+ * problems if a CGI returns an Etag header which also need to be
+ * fixed.
+ */
+ if ((sub_vary = ap_table_get(sub_req->err_headers_out, "Vary")) != NULL) {
+ ap_table_setn(r->err_headers_out, "Variant-Vary", sub_vary);
+
+ /* Move the subreq Vary header into the main request to
+ * prevent having two Vary headers in the response, which
+ * would be legal but strange.
+ */
+ ap_table_setn(r->err_headers_out, "Vary", sub_vary);
+ ap_table_unset(sub_req->err_headers_out, "Vary");
+ }
+
+ ap_table_setn(r->err_headers_out, "Content-Location",
+ ap_pstrdup(r->pool, variant->file_name));
+
+ set_neg_headers(r, neg, alg_choice); /* add Alternates and Vary */
+
+ /* Still to do by caller: add Expires */
+
+ return 0;
+}
+
+/****************************************************************
+ *
+ * Executive...
+ */
+
+static int do_negotiation(request_rec *r, negotiation_state *neg,
+ var_rec **bestp, int prefer_scripts)
+{
+ var_rec *avail_recs = (var_rec *) neg->avail_vars->elts;
+ int alg_result; /* result of variant selection algorithm */
+ int res;
+ int j;
+
+ /* Decide if resource is transparently negotiable */
+
+ /* GET or HEAD? (HEAD has same method number as GET) */
+ if (r->method_number == M_GET) {
+
+ /* maybe this should be configurable, see also the comment
+ * about recursive type maps in setup_choice_response()
+ */
+ neg->is_transparent = 1;
+
+ /* We can't be transparent if we are a map file in the middle
+ * of the request URI.
+ */
+ if (r->path_info && *r->path_info)
+ neg->is_transparent = 0;
+
+ for (j = 0; j < neg->avail_vars->nelts; ++j) {
+ var_rec *variant = &avail_recs[j];
+
+ /* We can't be transparent, because of internal
+ * assumptions in best_match(), if there is a
+ * non-neighboring variant. We can have a non-neighboring
+ * variant when processing a type map.
+ */
+ if (strchr(variant->file_name, '/'))
+ neg->is_transparent = 0;
+ }
+ }
+
+ if (neg->is_transparent) {
+ parse_negotiate_header(r, neg);
+ }
+ else { /* configure negotiation on non-transparent resource */
+ neg->may_choose = 1;
+ }
+
+ maybe_add_default_accepts(neg, prefer_scripts);
+
+ alg_result = best_match(neg, bestp);
+
+ /* alg_result is one of
+ * alg_choice: a best variant is chosen
+ * alg_list: no best variant is chosen
+ */
+
+ if (alg_result == alg_list) {
+ /* send a list response or NOT_ACCEPTABLE error response */
+
+ neg->send_alternates = 1; /* always include Alternates header */
+ set_neg_headers(r, neg, alg_result);
+ store_variant_list(r, neg);
+
+ if (neg->is_transparent && neg->ua_supports_trans) {
+ /* XXX todo: expires? cachability? */
+
+ /* Some HTTP/1.0 clients are known to choke when they get
+ * a 300 (multiple choices) response without a Location
+ * header. However the 300 code response we are are about
+ * to generate will only reach 1.0 clients which support
+ * transparent negotiation, and they should be OK. The
+ * response should never reach older 1.0 clients, even if
+ * we have CacheNegotiatedDocs enabled, because no 1.0
+ * proxy cache (we know of) will cache and return 300
+ * responses (they certainly won't if they conform to the
+ * HTTP/1.0 specification).
+ */
+ return MULTIPLE_CHOICES;
+ }
+
+ if (!*bestp) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "no acceptable variant: %s", r->filename);
+ return NOT_ACCEPTABLE;
+ }
+ }
+
+ /* Variant selection chose a variant */
+
+ /* XXX todo: merge the two cases in the if statement below */
+ if (neg->is_transparent) {
+
+ if ((res = setup_choice_response(r, neg, *bestp)) != 0) {
+ return res; /* return if error */
+ }
+ }
+ else {
+ set_neg_headers(r, neg, alg_result);
+ }
+
+ /* Make sure caching works - Vary should handle HTTP/1.1, but for
+ * HTTP/1.0, we can't allow caching at all.
+ */
+
+ /* XXX: Note that we only set r->no_cache to 1, which causes
+ * Expires: to be added, when responding to a HTTP/1.0
+ * client. If we return the response to a 1.1 client, we do not
+ * add Expires , because doing so would degrade 1.1 cache
+ * performance by preventing re-use of the response without prior
+ * revalidation. On the other hand, if the 1.1 client is a proxy
+ * which was itself contacted by a 1.0 client, or a proxy cache
+ * which can be contacted later by 1.0 clients, then we currently
+ * rely on this 1.1 proxy to add the Expires: when it
+ * forwards the response.
+ *
+ * XXX: TODO: Find out if the 1.1 spec requires proxies and
+ * tunnels to add Expires: when forwarding the response to
+ * 1.0 clients. I (kh) recall it is rather vague on this point.
+ * Testing actual 1.1 proxy implementations would also be nice. If
+ * Expires: is not added by proxies then we need to always
+ * include Expires: ourselves to ensure correct caching, but
+ * this would degrade HTTP/1.1 cache efficiency unless we also add
+ * Cache-Control: max-age=N, which we currently don't.
+ *
+ * Roy: No, we are not going to screw over HTTP future just to
+ * ensure that people who can't be bothered to upgrade their
+ * clients will always receive perfect server-side negotiation.
+ * Hell, those clients are sending bogus accept headers anyway.
+ *
+ * Manual setting of cache-control/expires always overrides this
+ * automated kluge, on purpose.
+ */
+
+ if ((!do_cache_negotiated_docs(r->server)
+ && (r->proto_num < HTTP_VERSION(1,1)))
+ && neg->count_multiviews_variants != 1) {
+ r->no_cache = 1;
+ }
+
+ return OK;
+}
+
+static int handle_map_file(request_rec *r)
+{
+ negotiation_state *neg = parse_accept_headers(r);
+ var_rec *best;
+ int res;
+
+ char *udir;
+
+ if ((res = read_type_map(neg, r))) {
+ return res;
+ }
+
+ res = do_negotiation(r, neg, &best, 0);
+ if (res != 0) return res;
+
+ if (r->path_info && *r->path_info) {
+ r->uri[ap_find_path_info(r->uri, r->path_info)] = '\0';
+ }
+ udir = ap_make_dirstr_parent(r->pool, r->uri);
+ udir = ap_escape_uri(r->pool, udir);
+ ap_internal_redirect(ap_pstrcat(r->pool, udir, best->file_name,
+ r->path_info, NULL), r);
+ return OK;
+}
+
+static int handle_multi(request_rec *r)
+{
+ negotiation_state *neg;
+ var_rec *best, *avail_recs;
+ request_rec *sub_req;
+ int res;
+ int j;
+
+ if (r->finfo.st_mode != 0 || !(ap_allow_options(r) & OPT_MULTI)) {
+ return DECLINED;
+ }
+
+ neg = parse_accept_headers(r);
+
+ if ((res = read_types_multi(neg))) {
+ return_from_multi:
+ /* free all allocated memory from subrequests */
+ avail_recs = (var_rec *) neg->avail_vars->elts;
+ for (j = 0; j < neg->avail_vars->nelts; ++j) {
+ var_rec *variant = &avail_recs[j];
+ if (variant->sub_req) {
+ ap_destroy_sub_req(variant->sub_req);
+ }
+ }
+ return res;
+ }
+ if (neg->avail_vars->nelts == 0) {
+ return DECLINED;
+ }
+
+ res = do_negotiation(r, neg, &best,
+ (r->method_number != M_GET) || r->args ||
+ (r->path_info && *r->path_info));
+ if (res != 0)
+ goto return_from_multi;
+
+ if (!(sub_req = best->sub_req)) {
+ /* We got this out of a map file, so we don't actually have
+ * a sub_req structure yet. Get one now.
+ */
+
+ sub_req = ap_sub_req_lookup_file(best->file_name, r);
+ if (sub_req->status != HTTP_OK) {
+ res = sub_req->status;
+ ap_destroy_sub_req(sub_req);
+ goto return_from_multi;
+ }
+ }
+
+ /* BLECH --- don't multi-resolve non-ordinary files */
+
+ if (!S_ISREG(sub_req->finfo.st_mode)) {
+ res = NOT_FOUND;
+ goto return_from_multi;
+ }
+
+ /* Otherwise, use it. */
+
+ /* now do a "fast redirect" ... promote the sub_req into the main req */
+ /* We need to tell POOL_DEBUG that we're guaranteeing that sub_req->pool
+ * will exist as long as r->pool. Otherwise we run into troubles because
+ * some values in this request will be allocated in r->pool, and others in
+ * sub_req->pool.
+ */
+ ap_pool_join(r->pool, sub_req->pool);
+ r->mtime = 0; /* reset etag info for subrequest */
+ r->filename = sub_req->filename;
+ r->handler = sub_req->handler;
+ r->content_type = sub_req->content_type;
+ r->content_encoding = sub_req->content_encoding;
+ r->content_languages = sub_req->content_languages;
+ r->content_language = sub_req->content_language;
+ r->finfo = sub_req->finfo;
+ r->per_dir_config = sub_req->per_dir_config;
+ /* copy output headers from subrequest, but leave negotiation headers */
+ r->notes = ap_overlay_tables(r->pool, sub_req->notes, r->notes);
+ r->headers_out = ap_overlay_tables(r->pool, sub_req->headers_out,
+ r->headers_out);
+ r->err_headers_out = ap_overlay_tables(r->pool, sub_req->err_headers_out,
+ r->err_headers_out);
+ r->subprocess_env = ap_overlay_tables(r->pool, sub_req->subprocess_env,
+ r->subprocess_env);
+ avail_recs = (var_rec *) neg->avail_vars->elts;
+ for (j = 0; j < neg->avail_vars->nelts; ++j) {
+ var_rec *variant = &avail_recs[j];
+ if (variant != best && variant->sub_req) {
+ ap_destroy_sub_req(variant->sub_req);
+ }
+ }
+ return OK;
+}
+
+/**********************************************************************
+ * There is a problem with content-encoding, as some clients send and
+ * expect an x- token (e.g. x-gzip) while others expect the plain token
+ * (i.e. gzip). To try and deal with this as best as possible we do
+ * the following: if the client sent an Accept-Encoding header and it
+ * contains a plain token corresponding to the content encoding of the
+ * response, then set content encoding using the plain token. Else if
+ * the A-E header contains the x- token use the x- token in the C-E
+ * header. Else don't do anything.
+ *
+ * Note that if no A-E header was sent, or it does not contain a token
+ * compatible with the final content encoding, then the token in the
+ * C-E header will be whatever was specified in the AddEncoding
+ * directive.
+ */
+static int fix_encoding(request_rec *r)
+{
+ const char *enc = r->content_encoding;
+ char *x_enc = NULL;
+ array_header *accept_encodings;
+ accept_rec *accept_recs;
+ int i;
+
+ if (!enc || !*enc) {
+ return DECLINED;
+ }
+
+ if (enc[0] == 'x' && enc[1] == '-') {
+ enc += 2;
+ }
+
+ if ((accept_encodings = do_header_line(r->pool,
+ ap_table_get(r->headers_in, "Accept-Encoding"))) == NULL) {
+ return DECLINED;
+ }
+
+ accept_recs = (accept_rec *) accept_encodings->elts;
+
+ for (i = 0; i < accept_encodings->nelts; ++i) {
+ char *name = accept_recs[i].name;
+
+ if (!strcmp(name, enc)) {
+ r->content_encoding = name;
+ return OK;
+ }
+
+ if (name[0] == 'x' && name[1] == '-' && !strcmp(name+2, enc)) {
+ x_enc = name;
+ }
+ }
+
+ if (x_enc) {
+ r->content_encoding = x_enc;
+ return OK;
+ }
+
+ return DECLINED;
+}
+
+static const handler_rec negotiation_handlers[] =
+{
+ {MAP_FILE_MAGIC_TYPE, handle_map_file},
+ {"type-map", handle_map_file},
+ {NULL}
+};
+
+module MODULE_VAR_EXPORT negotiation_module =
+{
+ STANDARD_MODULE_STUFF,
+ NULL, /* initializer */
+ create_neg_dir_config, /* dir config creator */
+ merge_neg_dir_configs, /* dir merger --- default is to override */
+ NULL, /* server config */
+ NULL, /* merge server config */
+ negotiation_cmds, /* command table */
+ negotiation_handlers, /* handlers */
+ NULL, /* filename translation */
+ NULL, /* check_user_id */
+ NULL, /* check auth */
+ NULL, /* check access */
+ handle_multi, /* type_checker */
+ fix_encoding, /* fixups */
+ NULL, /* logger */
+ NULL, /* header parser */
+ NULL, /* child_init */
+ NULL, /* child_exit */
+ NULL /* post read-request */
+};
diff --git a/modules/mappers/mod_rewrite.c b/modules/mappers/mod_rewrite.c
new file mode 100644
index 00000000000..c44de0dafab
--- /dev/null
+++ b/modules/mappers/mod_rewrite.c
@@ -0,0 +1,4263 @@
+/* ====================================================================
+ * Copyright (c) 1996-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+
+/* _ _ _
+** _ __ ___ ___ __| | _ __ _____ ___ __(_) |_ ___
+** | '_ ` _ \ / _ \ / _` | | '__/ _ \ \ /\ / / '__| | __/ _ \
+** | | | | | | (_) | (_| | | | | __/\ V V /| | | | || __/
+** |_| |_| |_|\___/ \__,_|___|_| \___| \_/\_/ |_| |_|\__\___|
+** |_____|
+**
+** URL Rewriting Module
+**
+** This module uses a rule-based rewriting engine (based on a
+** regular-expression parser) to rewrite requested URLs on the fly.
+**
+** It supports an unlimited number of additional rule conditions (which can
+** operate on a lot of variables, even on HTTP headers) for granular
+** matching and even external database lookups (either via plain text
+** tables, DBM hash files or even external processes) for advanced URL
+** substitution.
+**
+** It operates on the full URLs (including the PATH_INFO part) both in
+** per-server context (httpd.conf) and per-dir context (.htaccess) and even
+** can generate QUERY_STRING parts on result. The rewriting result finally
+** can lead to internal subprocessing, external request redirection or even
+** to internal proxy throughput.
+**
+** This module was originally written in April 1996 and
+** gifted exclusively to the The Apache Group in July 1997 by
+**
+** Ralf S. Engelschall
+** rse@engelschall.com
+** www.engelschall.com
+*/
+
+
+#include "mod_rewrite.h"
+
+#ifndef NO_WRITEV
+#include
+#include
+#endif
+
+/*
+** +-------------------------------------------------------+
+** | |
+** | static module configuration
+** | |
+** +-------------------------------------------------------+
+*/
+
+
+/*
+** Our interface to the Apache server kernel:
+**
+** o Runtime logic of a request is as following:
+** while(request or subrequest)
+** foreach(stage #0...#9)
+** foreach(module) (**)
+** try to run hook
+**
+** o the order of modules at (**) is the inverted order as
+** given in the "Configuration" file, i.e. the last module
+** specified is the first one called for each hook!
+** The core module is always the last!
+**
+** o there are two different types of result checking and
+** continue processing:
+** for hook #0,#1,#4,#5,#6,#8:
+** hook run loop stops on first modules which gives
+** back a result != DECLINED, i.e. it usually returns OK
+** which says "OK, module has handled this _stage_" and for #1
+** this have not to mean "Ok, the filename is now valid".
+** for hook #2,#3,#7,#9:
+** all hooks are run, independend of result
+**
+** o at the last stage, the core module always
+** - says "BAD_REQUEST" if r->filename does not begin with "/"
+** - prefix URL with document_root or replaced server_root
+** with document_root and sets r->filename
+** - always return a "OK" independed if the file really exists
+** or not!
+*/
+
+ /* The section for the Configure script:
+ * MODULE-DEFINITION-START
+ * Name: rewrite_module
+ * ConfigStart
+ . ./helpers/find-dbm-lib
+ if [ "x$found_dbm" = "x1" ]; then
+ echo " enabling DBM support for mod_rewrite"
+ else
+ echo " disabling DBM support for mod_rewrite"
+ echo " (perhaps you need to add -ldbm, -lndbm or -lgdbm to EXTRA_LIBS)"
+ CFLAGS="$CFLAGS -DNO_DBM_REWRITEMAP"
+ fi
+ * ConfigEnd
+ * MODULE-DEFINITION-END
+ */
+
+ /* the table of commands we provide */
+static const command_rec command_table[] = {
+ { "RewriteEngine", cmd_rewriteengine, NULL, OR_FILEINFO, FLAG,
+ "On or Off to enable or disable (default) the whole rewriting engine" },
+ { "RewriteOptions", cmd_rewriteoptions, NULL, OR_FILEINFO, ITERATE,
+ "List of option strings to set" },
+ { "RewriteBase", cmd_rewritebase, NULL, OR_FILEINFO, TAKE1,
+ "the base URL of the per-directory context" },
+ { "RewriteCond", cmd_rewritecond, NULL, OR_FILEINFO, RAW_ARGS,
+ "an input string and a to be applied regexp-pattern" },
+ { "RewriteRule", cmd_rewriterule, NULL, OR_FILEINFO, RAW_ARGS,
+ "an URL-applied regexp-pattern and a substitution URL" },
+ { "RewriteMap", cmd_rewritemap, NULL, RSRC_CONF, TAKE2,
+ "a mapname and a filename" },
+ { "RewriteLock", cmd_rewritelock, NULL, RSRC_CONF, TAKE1,
+ "the filename of a lockfile used for inter-process synchronization"},
+ { "RewriteLog", cmd_rewritelog, NULL, RSRC_CONF, TAKE1,
+ "the filename of the rewriting logfile" },
+ { "RewriteLogLevel", cmd_rewriteloglevel, NULL, RSRC_CONF, TAKE1,
+ "the level of the rewriting logfile verbosity "
+ "(0=none, 1=std, .., 9=max)" },
+ { NULL }
+};
+
+ /* the table of content handlers we provide */
+static const handler_rec handler_table[] = {
+ { "redirect-handler", handler_redirect },
+ { NULL }
+};
+
+ /* the main config structure */
+module MODULE_VAR_EXPORT rewrite_module = {
+ STANDARD_MODULE_STUFF,
+ init_module, /* module initializer */
+ config_perdir_create, /* create per-dir config structures */
+ config_perdir_merge, /* merge per-dir config structures */
+ config_server_create, /* create per-server config structures */
+ config_server_merge, /* merge per-server config structures */
+ command_table, /* table of config file commands */
+ handler_table, /* [#8] MIME-typed-dispatched handlers */
+ hook_uri2file, /* [#1] URI to filename translation */
+ NULL, /* [#4] validate user id from request */
+ NULL, /* [#5] check if the user is ok _here_ */
+ NULL, /* [#3] check access by host address */
+ hook_mimetype, /* [#6] determine MIME type */
+ hook_fixup, /* [#7] pre-run fixups */
+ NULL, /* [#9] log a transaction */
+ NULL, /* [#2] header parser */
+ init_child, /* child_init */
+ NULL, /* child_exit */
+ NULL /* [#0] post read-request */
+};
+
+ /* the cache */
+static cache *cachep;
+
+ /* whether proxy module is available or not */
+static int proxy_available;
+
+static char *lockname;
+static int lockfd = -1;
+
+/*
+** +-------------------------------------------------------+
+** | |
+** | configuration directive handling
+** | |
+** +-------------------------------------------------------+
+*/
+
+/*
+**
+** per-server configuration structure handling
+**
+*/
+
+static void *config_server_create(pool *p, server_rec *s)
+{
+ rewrite_server_conf *a;
+
+ a = (rewrite_server_conf *)ap_pcalloc(p, sizeof(rewrite_server_conf));
+
+ a->state = ENGINE_DISABLED;
+ a->options = OPTION_NONE;
+ a->rewritelogfile = NULL;
+ a->rewritelogfp = -1;
+ a->rewriteloglevel = 0;
+ a->rewritemaps = ap_make_array(p, 2, sizeof(rewritemap_entry));
+ a->rewriteconds = ap_make_array(p, 2, sizeof(rewritecond_entry));
+ a->rewriterules = ap_make_array(p, 2, sizeof(rewriterule_entry));
+ a->server = s;
+
+ return (void *)a;
+}
+
+static void *config_server_merge(pool *p, void *basev, void *overridesv)
+{
+ rewrite_server_conf *a, *base, *overrides;
+
+ a = (rewrite_server_conf *)ap_pcalloc(p, sizeof(rewrite_server_conf));
+ base = (rewrite_server_conf *)basev;
+ overrides = (rewrite_server_conf *)overridesv;
+
+ a->state = overrides->state;
+ a->options = overrides->options;
+ a->server = overrides->server;
+
+ if (a->options & OPTION_INHERIT) {
+ /*
+ * local directives override
+ * and anything else is inherited
+ */
+ a->rewriteloglevel = overrides->rewriteloglevel != 0
+ ? overrides->rewriteloglevel
+ : base->rewriteloglevel;
+ a->rewritelogfile = overrides->rewritelogfile != NULL
+ ? overrides->rewritelogfile
+ : base->rewritelogfile;
+ a->rewritelogfp = overrides->rewritelogfp != -1
+ ? overrides->rewritelogfp
+ : base->rewritelogfp;
+ a->rewritemaps = ap_append_arrays(p, overrides->rewritemaps,
+ base->rewritemaps);
+ a->rewriteconds = ap_append_arrays(p, overrides->rewriteconds,
+ base->rewriteconds);
+ a->rewriterules = ap_append_arrays(p, overrides->rewriterules,
+ base->rewriterules);
+ }
+ else {
+ /*
+ * local directives override
+ * and anything else gets defaults
+ */
+ a->rewriteloglevel = overrides->rewriteloglevel;
+ a->rewritelogfile = overrides->rewritelogfile;
+ a->rewritelogfp = overrides->rewritelogfp;
+ a->rewritemaps = overrides->rewritemaps;
+ a->rewriteconds = overrides->rewriteconds;
+ a->rewriterules = overrides->rewriterules;
+ }
+
+ return (void *)a;
+}
+
+
+/*
+**
+** per-directory configuration structure handling
+**
+*/
+
+static void *config_perdir_create(pool *p, char *path)
+{
+ rewrite_perdir_conf *a;
+
+ a = (rewrite_perdir_conf *)ap_pcalloc(p, sizeof(rewrite_perdir_conf));
+
+ a->state = ENGINE_DISABLED;
+ a->options = OPTION_NONE;
+ a->baseurl = NULL;
+ a->rewriteconds = ap_make_array(p, 2, sizeof(rewritecond_entry));
+ a->rewriterules = ap_make_array(p, 2, sizeof(rewriterule_entry));
+
+ if (path == NULL) {
+ a->directory = NULL;
+ }
+ else {
+ /* make sure it has a trailing slash */
+ if (path[strlen(path)-1] == '/') {
+ a->directory = ap_pstrdup(p, path);
+ }
+ else {
+ a->directory = ap_pstrcat(p, path, "/", NULL);
+ }
+ }
+
+ return (void *)a;
+}
+
+static void *config_perdir_merge(pool *p, void *basev, void *overridesv)
+{
+ rewrite_perdir_conf *a, *base, *overrides;
+
+ a = (rewrite_perdir_conf *)ap_pcalloc(p,
+ sizeof(rewrite_perdir_conf));
+ base = (rewrite_perdir_conf *)basev;
+ overrides = (rewrite_perdir_conf *)overridesv;
+
+ a->state = overrides->state;
+ a->options = overrides->options;
+ a->directory = overrides->directory;
+ a->baseurl = overrides->baseurl;
+
+ if (a->options & OPTION_INHERIT) {
+ a->rewriteconds = ap_append_arrays(p, overrides->rewriteconds,
+ base->rewriteconds);
+ a->rewriterules = ap_append_arrays(p, overrides->rewriterules,
+ base->rewriterules);
+ }
+ else {
+ a->rewriteconds = overrides->rewriteconds;
+ a->rewriterules = overrides->rewriterules;
+ }
+
+ return (void *)a;
+}
+
+
+/*
+**
+** the configuration commands
+**
+*/
+
+static const char *cmd_rewriteengine(cmd_parms *cmd,
+ rewrite_perdir_conf *dconf, int flag)
+{
+ rewrite_server_conf *sconf;
+
+ sconf =
+ (rewrite_server_conf *)ap_get_module_config(cmd->server->module_config,
+ &rewrite_module);
+
+ if (cmd->path == NULL) { /* is server command */
+ sconf->state = (flag ? ENGINE_ENABLED : ENGINE_DISABLED);
+ }
+ else /* is per-directory command */ {
+ dconf->state = (flag ? ENGINE_ENABLED : ENGINE_DISABLED);
+ }
+
+ return NULL;
+}
+
+static const char *cmd_rewriteoptions(cmd_parms *cmd,
+ rewrite_perdir_conf *dconf, char *option)
+{
+ rewrite_server_conf *sconf;
+ const char *err;
+
+ sconf = (rewrite_server_conf *)
+ ap_get_module_config(cmd->server->module_config, &rewrite_module);
+
+ if (cmd->path == NULL) { /* is server command */
+ err = cmd_rewriteoptions_setoption(cmd->pool,
+ &(sconf->options), option);
+ }
+ else { /* is per-directory command */
+ err = cmd_rewriteoptions_setoption(cmd->pool,
+ &(dconf->options), option);
+ }
+
+ return err;
+}
+
+static const char *cmd_rewriteoptions_setoption(pool *p, int *options,
+ char *name)
+{
+ if (strcasecmp(name, "inherit") == 0) {
+ *options |= OPTION_INHERIT;
+ }
+ else {
+ return ap_pstrcat(p, "RewriteOptions: unknown option '",
+ name, "'\n", NULL);
+ }
+ return NULL;
+}
+
+static const char *cmd_rewritelog(cmd_parms *cmd, void *dconf, char *a1)
+{
+ rewrite_server_conf *sconf;
+
+ sconf = (rewrite_server_conf *)
+ ap_get_module_config(cmd->server->module_config, &rewrite_module);
+
+ sconf->rewritelogfile = a1;
+
+ return NULL;
+}
+
+static const char *cmd_rewriteloglevel(cmd_parms *cmd, void *dconf, char *a1)
+{
+ rewrite_server_conf *sconf;
+
+ sconf = (rewrite_server_conf *)
+ ap_get_module_config(cmd->server->module_config, &rewrite_module);
+
+ sconf->rewriteloglevel = atoi(a1);
+
+ return NULL;
+}
+
+static const char *cmd_rewritemap(cmd_parms *cmd, void *dconf, char *a1,
+ char *a2)
+{
+ rewrite_server_conf *sconf;
+ rewritemap_entry *new;
+ struct stat st;
+
+ sconf = (rewrite_server_conf *)
+ ap_get_module_config(cmd->server->module_config, &rewrite_module);
+
+ new = ap_push_array(sconf->rewritemaps);
+
+ new->name = a1;
+ new->func = NULL;
+ if (strncmp(a2, "txt:", 4) == 0) {
+ new->type = MAPTYPE_TXT;
+ new->datafile = a2+4;
+ new->checkfile = a2+4;
+ }
+ else if (strncmp(a2, "rnd:", 4) == 0) {
+ new->type = MAPTYPE_RND;
+ new->datafile = a2+4;
+ new->checkfile = a2+4;
+ }
+ else if (strncmp(a2, "dbm:", 4) == 0) {
+#ifndef NO_DBM_REWRITEMAP
+ new->type = MAPTYPE_DBM;
+ new->datafile = a2+4;
+ new->checkfile = ap_pstrcat(cmd->pool, a2+4, NDBM_FILE_SUFFIX, NULL);
+#else
+ return ap_pstrdup(cmd->pool, "RewriteMap: cannot use NDBM mapfile, "
+ "because no NDBM support is compiled in");
+#endif
+ }
+ else if (strncmp(a2, "prg:", 4) == 0) {
+ new->type = MAPTYPE_PRG;
+ new->datafile = a2+4;
+ new->checkfile = a2+4;
+ }
+ else if (strncmp(a2, "int:", 4) == 0) {
+ new->type = MAPTYPE_INT;
+ new->datafile = NULL;
+ new->checkfile = NULL;
+ if (strcmp(a2+4, "tolower") == 0) {
+ new->func = rewrite_mapfunc_tolower;
+ }
+ else if (strcmp(a2+4, "toupper") == 0) {
+ new->func = rewrite_mapfunc_toupper;
+ }
+ else if (strcmp(a2+4, "escape") == 0) {
+ new->func = rewrite_mapfunc_escape;
+ }
+ else if (strcmp(a2+4, "unescape") == 0) {
+ new->func = rewrite_mapfunc_unescape;
+ }
+ else if (sconf->state == ENGINE_ENABLED) {
+ return ap_pstrcat(cmd->pool, "RewriteMap: internal map not found:",
+ a2+4, NULL);
+ }
+ }
+ else {
+ new->type = MAPTYPE_TXT;
+ new->datafile = a2;
+ new->checkfile = a2;
+ }
+ new->fpin = -1;
+ new->fpout = -1;
+
+ if (new->checkfile && (sconf->state == ENGINE_ENABLED)
+ && (stat(new->checkfile, &st) == -1)) {
+ return ap_pstrcat(cmd->pool,
+ "RewriteMap: map file or program not found:",
+ new->checkfile, NULL);
+ }
+
+ return NULL;
+}
+
+static const char *cmd_rewritelock(cmd_parms *cmd, void *dconf, char *a1)
+{
+ const char *error;
+
+ if ((error = ap_check_cmd_context(cmd, GLOBAL_ONLY)) != NULL)
+ return error;
+
+ lockname = a1;
+
+ return NULL;
+}
+
+static const char *cmd_rewritebase(cmd_parms *cmd, rewrite_perdir_conf *dconf,
+ char *a1)
+{
+ if (cmd->path == NULL || dconf == NULL) {
+ return "RewriteBase: only valid in per-directory config files";
+ }
+ if (a1[0] == '\0') {
+ return "RewriteBase: empty URL not allowed";
+ }
+ if (a1[0] != '/') {
+ return "RewriteBase: argument is not a valid URL";
+ }
+
+ dconf->baseurl = a1;
+
+ return NULL;
+}
+
+static const char *cmd_rewritecond(cmd_parms *cmd, rewrite_perdir_conf *dconf,
+ char *str)
+{
+ rewrite_server_conf *sconf;
+ rewritecond_entry *new;
+ regex_t *regexp;
+ char *a1;
+ char *a2;
+ char *a3;
+ char *cp;
+ const char *err;
+ int rc;
+
+ sconf = (rewrite_server_conf *)
+ ap_get_module_config(cmd->server->module_config, &rewrite_module);
+
+ /* make a new entry in the internal temporary rewrite rule list */
+ if (cmd->path == NULL) { /* is server command */
+ new = ap_push_array(sconf->rewriteconds);
+ }
+ else { /* is per-directory command */
+ new = ap_push_array(dconf->rewriteconds);
+ }
+
+ /* parse the argument line ourself */
+ if (parseargline(str, &a1, &a2, &a3)) {
+ return ap_pstrcat(cmd->pool, "RewriteCond: bad argument line '", str,
+ "'\n", NULL);
+ }
+
+ /* arg1: the input string */
+ new->input = ap_pstrdup(cmd->pool, a1);
+
+ /* arg3: optional flags field
+ (this have to be first parsed, because we need to
+ know if the regex should be compiled with ICASE!) */
+ new->flags = CONDFLAG_NONE;
+ if (a3 != NULL) {
+ if ((err = cmd_rewritecond_parseflagfield(cmd->pool, new,
+ a3)) != NULL) {
+ return err;
+ }
+ }
+
+ /* arg2: the pattern
+ try to compile the regexp to test if is ok */
+ cp = a2;
+ if (cp[0] == '!') {
+ new->flags |= CONDFLAG_NOTMATCH;
+ cp++;
+ }
+
+ /* now be careful: Under the POSIX regex library
+ we can compile the pattern for case-insensitive matching,
+ under the old V8 library we have to do it self via a hack */
+ if (new->flags & CONDFLAG_NOCASE) {
+ rc = ((regexp = ap_pregcomp(cmd->pool, cp, REG_EXTENDED|REG_ICASE))
+ == NULL);
+ }
+ else {
+ rc = ((regexp = ap_pregcomp(cmd->pool, cp, REG_EXTENDED)) == NULL);
+ }
+ if (rc) {
+ return ap_pstrcat(cmd->pool,
+ "RewriteCond: cannot compile regular expression '",
+ a2, "'\n", NULL);
+ }
+
+ new->pattern = ap_pstrdup(cmd->pool, cp);
+ new->regexp = regexp;
+
+ return NULL;
+}
+
+static const char *cmd_rewritecond_parseflagfield(pool *p,
+ rewritecond_entry *cfg,
+ char *str)
+{
+ char *cp;
+ char *cp1;
+ char *cp2;
+ char *cp3;
+ char *key;
+ char *val;
+ const char *err;
+
+ if (str[0] != '[' || str[strlen(str)-1] != ']') {
+ return "RewriteCond: bad flag delimiters";
+ }
+
+ cp = str+1;
+ str[strlen(str)-1] = ','; /* for simpler parsing */
+ for ( ; *cp != '\0'; ) {
+ /* skip whitespaces */
+ for ( ; (*cp == ' ' || *cp == '\t') && *cp != '\0'; cp++)
+ ;
+ if (*cp == '\0') {
+ break;
+ }
+ cp1 = cp;
+ if ((cp2 = strchr(cp, ',')) != NULL) {
+ cp = cp2+1;
+ for ( ; (*(cp2-1) == ' ' || *(cp2-1) == '\t'); cp2--)
+ ;
+ *cp2 = '\0';
+ if ((cp3 = strchr(cp1, '=')) != NULL) {
+ *cp3 = '\0';
+ key = cp1;
+ val = cp3+1;
+ }
+ else {
+ key = cp1;
+ val = "";
+ }
+ if ((err = cmd_rewritecond_setflag(p, cfg, key, val)) != NULL) {
+ return err;
+ }
+ }
+ else {
+ break;
+ }
+ }
+
+ return NULL;
+}
+
+static const char *cmd_rewritecond_setflag(pool *p, rewritecond_entry *cfg,
+ char *key, char *val)
+{
+ if ( strcasecmp(key, "nocase") == 0
+ || strcasecmp(key, "NC") == 0 ) {
+ cfg->flags |= CONDFLAG_NOCASE;
+ }
+ else if ( strcasecmp(key, "ornext") == 0
+ || strcasecmp(key, "OR") == 0 ) {
+ cfg->flags |= CONDFLAG_ORNEXT;
+ }
+ else {
+ return ap_pstrcat(p, "RewriteCond: unknown flag '", key, "'\n", NULL);
+ }
+ return NULL;
+}
+
+static const char *cmd_rewriterule(cmd_parms *cmd, rewrite_perdir_conf *dconf,
+ char *str)
+{
+ rewrite_server_conf *sconf;
+ rewriterule_entry *new;
+ regex_t *regexp;
+ char *a1;
+ char *a2;
+ char *a3;
+ char *cp;
+ const char *err;
+ int mode;
+
+ sconf = (rewrite_server_conf *)
+ ap_get_module_config(cmd->server->module_config, &rewrite_module);
+
+ /* make a new entry in the internal rewrite rule list */
+ if (cmd->path == NULL) { /* is server command */
+ new = ap_push_array(sconf->rewriterules);
+ }
+ else { /* is per-directory command */
+ new = ap_push_array(dconf->rewriterules);
+ }
+
+ /* parse the argument line ourself */
+ if (parseargline(str, &a1, &a2, &a3)) {
+ return ap_pstrcat(cmd->pool, "RewriteRule: bad argument line '", str,
+ "'\n", NULL);
+ }
+
+ /* arg3: optional flags field */
+ new->forced_mimetype = NULL;
+ new->forced_responsecode = HTTP_MOVED_TEMPORARILY;
+ new->flags = RULEFLAG_NONE;
+ new->env[0] = NULL;
+ new->skip = 0;
+ if (a3 != NULL) {
+ if ((err = cmd_rewriterule_parseflagfield(cmd->pool, new,
+ a3)) != NULL) {
+ return err;
+ }
+ }
+
+ /* arg1: the pattern
+ * try to compile the regexp to test if is ok
+ */
+ cp = a1;
+ if (cp[0] == '!') {
+ new->flags |= RULEFLAG_NOTMATCH;
+ cp++;
+ }
+ mode = REG_EXTENDED;
+ if (new->flags & RULEFLAG_NOCASE) {
+ mode |= REG_ICASE;
+ }
+ if ((regexp = ap_pregcomp(cmd->pool, cp, mode)) == NULL) {
+ return ap_pstrcat(cmd->pool,
+ "RewriteRule: cannot compile regular expression '",
+ a1, "'\n", NULL);
+ }
+ new->pattern = ap_pstrdup(cmd->pool, cp);
+ new->regexp = regexp;
+
+ /* arg2: the output string
+ * replace the $ by \ which is needed by the currently
+ * used Regular Expression library
+ */
+ new->output = ap_pstrdup(cmd->pool, a2);
+
+ /* now, if the server or per-dir config holds an
+ * array of RewriteCond entries, we take it for us
+ * and clear the array
+ */
+ if (cmd->path == NULL) { /* is server command */
+ new->rewriteconds = sconf->rewriteconds;
+ sconf->rewriteconds = ap_make_array(cmd->pool, 2,
+ sizeof(rewritecond_entry));
+ }
+ else { /* is per-directory command */
+ new->rewriteconds = dconf->rewriteconds;
+ dconf->rewriteconds = ap_make_array(cmd->pool, 2,
+ sizeof(rewritecond_entry));
+ }
+
+ return NULL;
+}
+
+static const char *cmd_rewriterule_parseflagfield(pool *p,
+ rewriterule_entry *cfg,
+ char *str)
+{
+ char *cp;
+ char *cp1;
+ char *cp2;
+ char *cp3;
+ char *key;
+ char *val;
+ const char *err;
+
+ if (str[0] != '[' || str[strlen(str)-1] != ']') {
+ return "RewriteRule: bad flag delimiters";
+ }
+
+ cp = str+1;
+ str[strlen(str)-1] = ','; /* for simpler parsing */
+ for ( ; *cp != '\0'; ) {
+ /* skip whitespaces */
+ for ( ; (*cp == ' ' || *cp == '\t') && *cp != '\0'; cp++)
+ ;
+ if (*cp == '\0') {
+ break;
+ }
+ cp1 = cp;
+ if ((cp2 = strchr(cp, ',')) != NULL) {
+ cp = cp2+1;
+ for ( ; (*(cp2-1) == ' ' || *(cp2-1) == '\t'); cp2--)
+ ;
+ *cp2 = '\0';
+ if ((cp3 = strchr(cp1, '=')) != NULL) {
+ *cp3 = '\0';
+ key = cp1;
+ val = cp3+1;
+ }
+ else {
+ key = cp1;
+ val = "";
+ }
+ if ((err = cmd_rewriterule_setflag(p, cfg, key, val)) != NULL) {
+ return err;
+ }
+ }
+ else {
+ break;
+ }
+ }
+
+ return NULL;
+}
+
+static const char *cmd_rewriterule_setflag(pool *p, rewriterule_entry *cfg,
+ char *key, char *val)
+{
+ int status = 0;
+ int i;
+
+ if ( strcasecmp(key, "redirect") == 0
+ || strcasecmp(key, "R") == 0 ) {
+ cfg->flags |= RULEFLAG_FORCEREDIRECT;
+ if (strlen(val) > 0) {
+ if (strcasecmp(val, "permanent") == 0) {
+ status = HTTP_MOVED_PERMANENTLY;
+ }
+ else if (strcasecmp(val, "temp") == 0) {
+ status = HTTP_MOVED_TEMPORARILY;
+ }
+ else if (strcasecmp(val, "seeother") == 0) {
+ status = HTTP_SEE_OTHER;
+ }
+ else if (ap_isdigit(*val)) {
+ status = atoi(val);
+ }
+ if (!ap_is_HTTP_REDIRECT(status)) {
+ return "RewriteRule: invalid HTTP response code "
+ "for flag 'R'";
+ }
+ cfg->forced_responsecode = status;
+ }
+ }
+ else if ( strcasecmp(key, "last") == 0
+ || strcasecmp(key, "L") == 0 ) {
+ cfg->flags |= RULEFLAG_LASTRULE;
+ }
+ else if ( strcasecmp(key, "next") == 0
+ || strcasecmp(key, "N") == 0 ) {
+ cfg->flags |= RULEFLAG_NEWROUND;
+ }
+ else if ( strcasecmp(key, "chain") == 0
+ || strcasecmp(key, "C") == 0 ) {
+ cfg->flags |= RULEFLAG_CHAIN;
+ }
+ else if ( strcasecmp(key, "type") == 0
+ || strcasecmp(key, "T") == 0 ) {
+ cfg->forced_mimetype = ap_pstrdup(p, val);
+ ap_str_tolower(cfg->forced_mimetype);
+ }
+ else if ( strcasecmp(key, "env") == 0
+ || strcasecmp(key, "E") == 0 ) {
+ for (i = 0; (cfg->env[i] != NULL) && (i < MAX_ENV_FLAGS); i++)
+ ;
+ if (i < MAX_ENV_FLAGS) {
+ cfg->env[i] = ap_pstrdup(p, val);
+ cfg->env[i+1] = NULL;
+ }
+ else {
+ return "RewriteRule: too many environment flags 'E'";
+ }
+ }
+ else if ( strcasecmp(key, "nosubreq") == 0
+ || strcasecmp(key, "NS") == 0 ) {
+ cfg->flags |= RULEFLAG_IGNOREONSUBREQ;
+ }
+ else if ( strcasecmp(key, "proxy") == 0
+ || strcasecmp(key, "P") == 0 ) {
+ cfg->flags |= RULEFLAG_PROXY;
+ }
+ else if ( strcasecmp(key, "passthrough") == 0
+ || strcasecmp(key, "PT") == 0 ) {
+ cfg->flags |= RULEFLAG_PASSTHROUGH;
+ }
+ else if ( strcasecmp(key, "skip") == 0
+ || strcasecmp(key, "S") == 0 ) {
+ cfg->skip = atoi(val);
+ }
+ else if ( strcasecmp(key, "forbidden") == 0
+ || strcasecmp(key, "F") == 0 ) {
+ cfg->flags |= RULEFLAG_FORBIDDEN;
+ }
+ else if ( strcasecmp(key, "gone") == 0
+ || strcasecmp(key, "G") == 0 ) {
+ cfg->flags |= RULEFLAG_GONE;
+ }
+ else if ( strcasecmp(key, "qsappend") == 0
+ || strcasecmp(key, "QSA") == 0 ) {
+ cfg->flags |= RULEFLAG_QSAPPEND;
+ }
+ else if ( strcasecmp(key, "nocase") == 0
+ || strcasecmp(key, "NC") == 0 ) {
+ cfg->flags |= RULEFLAG_NOCASE;
+ }
+ else {
+ return ap_pstrcat(p, "RewriteRule: unknown flag '", key, "'\n", NULL);
+ }
+ return NULL;
+}
+
+
+/*
+**
+** Global Module Initialization
+** [called from read_config() after all
+** config commands were already called]
+**
+*/
+
+static void init_module(server_rec *s, pool *p)
+{
+ /* check if proxy module is available */
+ proxy_available = (ap_find_linked_module("mod_proxy.c") != NULL);
+
+ /* create the rewriting lockfile in the parent */
+ rewritelock_create(s, p);
+ ap_register_cleanup(p, (void *)s, rewritelock_remove, ap_null_cleanup);
+
+ /* step through the servers and
+ * - open each rewriting logfile
+ * - open the RewriteMap prg:xxx programs
+ */
+ for (; s; s = s->next) {
+ open_rewritelog(s, p);
+ run_rewritemap_programs(s, p);
+ }
+}
+
+
+/*
+**
+** Per-Child Module Initialization
+** [called after a child process is spawned]
+**
+*/
+
+static void init_child(server_rec *s, pool *p)
+{
+ /* open the rewriting lockfile */
+ rewritelock_open(s, p);
+
+ /* create the lookup cache */
+ cachep = init_cache(p);
+}
+
+
+/*
+** +-------------------------------------------------------+
+** | |
+** | runtime hooks
+** | |
+** +-------------------------------------------------------+
+*/
+
+/*
+**
+** URI-to-filename hook
+**
+** [used for the rewriting engine triggered by
+** the per-server 'RewriteRule' directives]
+**
+*/
+
+static int hook_uri2file(request_rec *r)
+{
+ void *sconf;
+ rewrite_server_conf *conf;
+ const char *var;
+ const char *thisserver;
+ char *thisport;
+ const char *thisurl;
+ char buf[512];
+ char docroot[512];
+ char *cp, *cp2;
+ const char *ccp;
+ struct stat finfo;
+ unsigned int port;
+ int n;
+ int l;
+
+ /*
+ * retrieve the config structures
+ */
+ sconf = r->server->module_config;
+ conf = (rewrite_server_conf *)ap_get_module_config(sconf,
+ &rewrite_module);
+
+ /*
+ * only do something under runtime if the engine is really enabled,
+ * else return immediately!
+ */
+ if (conf->state == ENGINE_DISABLED) {
+ return DECLINED;
+ }
+
+ /*
+ * check for the ugly API case of a virtual host section where no
+ * mod_rewrite directives exists. In this situation we became no chance
+ * by the API to setup our default per-server config so we have to
+ * on-the-fly assume we have the default config. But because the default
+ * config has a disabled rewriting engine we are lucky because can
+ * just stop operating now.
+ */
+ if (conf->server != r->server) {
+ return DECLINED;
+ }
+
+ /*
+ * add the SCRIPT_URL variable to the env. this is a bit complicated
+ * due to the fact that apache uses subrequests and internal redirects
+ */
+
+ if (r->main == NULL) {
+ var = ap_pstrcat(r->pool, "REDIRECT_", ENVVAR_SCRIPT_URL, NULL);
+ var = ap_table_get(r->subprocess_env, var);
+ if (var == NULL) {
+ ap_table_setn(r->subprocess_env, ENVVAR_SCRIPT_URL, r->uri);
+ }
+ else {
+ ap_table_setn(r->subprocess_env, ENVVAR_SCRIPT_URL, var);
+ }
+ }
+ else {
+ var = ap_table_get(r->main->subprocess_env, ENVVAR_SCRIPT_URL);
+ ap_table_setn(r->subprocess_env, ENVVAR_SCRIPT_URL, var);
+ }
+
+ /*
+ * create the SCRIPT_URI variable for the env
+ */
+
+ /* add the canonical URI of this URL */
+ thisserver = ap_get_server_name(r);
+ port = ap_get_server_port(r);
+ if (ap_is_default_port(port, r)) {
+ thisport = "";
+ }
+ else {
+ ap_snprintf(buf, sizeof(buf), ":%u", port);
+ thisport = buf;
+ }
+ thisurl = ap_table_get(r->subprocess_env, ENVVAR_SCRIPT_URL);
+
+ /* set the variable */
+ var = ap_pstrcat(r->pool, ap_http_method(r), "://", thisserver, thisport,
+ thisurl, NULL);
+ ap_table_setn(r->subprocess_env, ENVVAR_SCRIPT_URI, var);
+
+ /* if filename was not initially set,
+ * we start with the requested URI
+ */
+ if (r->filename == NULL) {
+ r->filename = ap_pstrdup(r->pool, r->uri);
+ rewritelog(r, 2, "init rewrite engine with requested uri %s",
+ r->filename);
+ }
+
+ /*
+ * now apply the rules ...
+ */
+ if (apply_rewrite_list(r, conf->rewriterules, NULL)) {
+
+ if (strlen(r->filename) > 6 &&
+ strncmp(r->filename, "proxy:", 6) == 0) {
+ /* it should be go on as an internal proxy request */
+
+ /* check if the proxy module is enabled, so
+ * we can actually use it!
+ */
+ if (!proxy_available) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "attempt to make remote request from mod_rewrite "
+ "without proxy enabled: %s", r->filename);
+ return FORBIDDEN;
+ }
+
+ /* make sure the QUERY_STRING and
+ * PATH_INFO parts get incorporated
+ */
+ if (r->path_info != NULL) {
+ r->filename = ap_pstrcat(r->pool, r->filename,
+ r->path_info, NULL);
+ }
+ if (r->args != NULL &&
+ r->uri == r->unparsed_uri) {
+ /* see proxy_http:proxy_http_canon() */
+ r->filename = ap_pstrcat(r->pool, r->filename,
+ "?", r->args, NULL);
+ }
+
+ /* now make sure the request gets handled by the proxy handler */
+ r->proxyreq = 1;
+ r->handler = "proxy-server";
+
+ rewritelog(r, 1, "go-ahead with proxy request %s [OK]",
+ r->filename);
+ return OK;
+ }
+ else if ( (strlen(r->filename) > 7 &&
+ strncasecmp(r->filename, "http://", 7) == 0)
+ || (strlen(r->filename) > 8 &&
+ strncasecmp(r->filename, "https://", 8) == 0)
+ || (strlen(r->filename) > 9 &&
+ strncasecmp(r->filename, "gopher://", 9) == 0)
+ || (strlen(r->filename) > 6 &&
+ strncasecmp(r->filename, "ftp://", 6) == 0) ) {
+ /* it was finally rewritten to a remote URL */
+
+ /* skip 'scheme:' */
+ for (cp = r->filename; *cp != ':' && *cp != '\0'; cp++)
+ ;
+ /* skip '://' */
+ cp += 3;
+ /* skip host part */
+ for ( ; *cp != '/' && *cp != '\0'; cp++)
+ ;
+ if (*cp != '\0') {
+ rewritelog(r, 1, "escaping %s for redirect", r->filename);
+ cp2 = ap_escape_uri(r->pool, cp);
+ *cp = '\0';
+ r->filename = ap_pstrcat(r->pool, r->filename, cp2, NULL);
+ }
+
+ /* append the QUERY_STRING part */
+ if (r->args != NULL) {
+ r->filename = ap_pstrcat(r->pool, r->filename,
+ "?", r->args, NULL);
+ }
+
+ /* determine HTTP redirect response code */
+ if (ap_is_HTTP_REDIRECT(r->status)) {
+ n = r->status;
+ r->status = HTTP_OK; /* make Apache kernel happy */
+ }
+ else {
+ n = REDIRECT;
+ }
+
+ /* now do the redirection */
+ ap_table_setn(r->headers_out, "Location", r->filename);
+ rewritelog(r, 1, "redirect to %s [REDIRECT/%d]", r->filename, n);
+ return n;
+ }
+ else if (strlen(r->filename) > 10 &&
+ strncmp(r->filename, "forbidden:", 10) == 0) {
+ /* This URLs is forced to be forbidden for the requester */
+ return FORBIDDEN;
+ }
+ else if (strlen(r->filename) > 5 &&
+ strncmp(r->filename, "gone:", 5) == 0) {
+ /* This URLs is forced to be gone */
+ return HTTP_GONE;
+ }
+ else if (strlen(r->filename) > 12 &&
+ strncmp(r->filename, "passthrough:", 12) == 0) {
+ /*
+ * Hack because of underpowered API: passing the current
+ * rewritten filename through to other URL-to-filename handlers
+ * just as it were the requested URL. This is to enable
+ * post-processing by mod_alias, etc. which always act on
+ * r->uri! The difference here is: We do not try to
+ * add the document root
+ */
+ r->uri = ap_pstrdup(r->pool, r->filename+12);
+ return DECLINED;
+ }
+ else {
+ /* it was finally rewritten to a local path */
+
+ /* expand "/~user" prefix */
+#ifndef WIN32
+ r->filename = expand_tildepaths(r, r->filename);
+#endif
+ rewritelog(r, 2, "local path result: %s", r->filename);
+
+ /* the filename has to start with a slash! */
+ if (r->filename[0] != '/') {
+ return BAD_REQUEST;
+ }
+
+ /* if there is no valid prefix, we have
+ * to emulate the translator from the core and
+ * prefix the filename with document_root
+ *
+ * NOTICE:
+ * We cannot leave out the prefix_stat because
+ * - when we always prefix with document_root
+ * then no absolute path can be created, e.g. via
+ * emulating a ScriptAlias directive, etc.
+ * - when we always NOT prefix with document_root
+ * then the files under document_root have to
+ * be references directly and document_root
+ * gets never used and will be a dummy parameter -
+ * this is also bad
+ *
+ * BUT:
+ * Under real Unix systems this is no problem,
+ * because we only do stat() on the first directory
+ * and this gets cached by the kernel for along time!
+ */
+ n = prefix_stat(r->filename, &finfo);
+ if (n == 0) {
+ if ((ccp = ap_document_root(r)) != NULL) {
+ l = ap_cpystrn(docroot, ccp, sizeof(docroot)) - docroot;
+
+ /* always NOT have a trailing slash */
+ if (docroot[l-1] == '/') {
+ docroot[l-1] = '\0';
+ }
+ if (r->server->path
+ && !strncmp(r->filename, r->server->path,
+ r->server->pathlen)) {
+ r->filename = ap_pstrcat(r->pool, docroot,
+ (r->filename +
+ r->server->pathlen), NULL);
+ }
+ else {
+ r->filename = ap_pstrcat(r->pool, docroot,
+ r->filename, NULL);
+ }
+ rewritelog(r, 2, "prefixed with document_root to %s",
+ r->filename);
+ }
+ }
+
+ rewritelog(r, 1, "go-ahead with %s [OK]", r->filename);
+ return OK;
+ }
+ }
+ else {
+ rewritelog(r, 1, "pass through %s", r->filename);
+ return DECLINED;
+ }
+}
+
+
+/*
+**
+** MIME-type hook
+**
+** [used to support the forced-MIME-type feature]
+**
+*/
+
+static int hook_mimetype(request_rec *r)
+{
+ const char *t;
+
+ /* now check if we have to force a MIME-type */
+ t = ap_table_get(r->notes, REWRITE_FORCED_MIMETYPE_NOTEVAR);
+ if (t == NULL) {
+ return DECLINED;
+ }
+ else {
+ rewritelog(r, 1, "force filename %s to have MIME-type '%s'",
+ r->filename, t);
+ r->content_type = t;
+ return OK;
+ }
+}
+
+
+/*
+**
+** Fixup hook
+**
+** [used for the rewriting engine triggered by
+** the per-directory 'RewriteRule' directives]
+**
+*/
+
+static int hook_fixup(request_rec *r)
+{
+ rewrite_perdir_conf *dconf;
+ char *cp;
+ char *cp2;
+ const char *ccp;
+ char *prefix;
+ int l;
+ int n;
+ char *ofilename;
+
+ dconf = (rewrite_perdir_conf *)ap_get_module_config(r->per_dir_config,
+ &rewrite_module);
+
+ /* if there is no per-dir config we return immediately */
+ if (dconf == NULL) {
+ return DECLINED;
+ }
+
+ /* we shouldn't do anything in subrequests */
+ if (r->main != NULL) {
+ return DECLINED;
+ }
+
+ /* if there are no real (i.e. no RewriteRule directives!)
+ per-dir config of us, we return also immediately */
+ if (dconf->directory == NULL) {
+ return DECLINED;
+ }
+
+ /*
+ * only do something under runtime if the engine is really enabled,
+ * for this directory, else return immediately!
+ */
+ if (!(ap_allow_options(r) & (OPT_SYM_LINKS | OPT_SYM_OWNER))) {
+ /* FollowSymLinks is mandatory! */
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "Options FollowSymLinks or SymLinksIfOwnerMatch is off "
+ "which implies that RewriteRule directive is forbidden: "
+ "%s", r->filename);
+ return FORBIDDEN;
+ }
+ else {
+ /* FollowSymLinks is given, but the user can
+ * still turn off the rewriting engine
+ */
+ if (dconf->state == ENGINE_DISABLED) {
+ return DECLINED;
+ }
+ }
+
+ /*
+ * remember the current filename before rewriting for later check
+ * to prevent deadlooping because of internal redirects
+ * on final URL/filename which can be equal to the inital one.
+ */
+ ofilename = r->filename;
+
+ /*
+ * now apply the rules ...
+ */
+ if (apply_rewrite_list(r, dconf->rewriterules, dconf->directory)) {
+
+ if (strlen(r->filename) > 6 &&
+ strncmp(r->filename, "proxy:", 6) == 0) {
+ /* it should go on as an internal proxy request */
+
+ /* make sure the QUERY_STRING and
+ * PATH_INFO parts get incorporated
+ * (r->path_info was already appended by the
+ * rewriting engine because of the per-dir context!)
+ */
+ if (r->args != NULL
+ && r->uri == r->unparsed_uri) {
+ /* see proxy_http:proxy_http_canon() */
+ r->filename = ap_pstrcat(r->pool, r->filename,
+ "?", r->args, NULL);
+ }
+
+ /* now make sure the request gets handled by the proxy handler */
+ r->proxyreq = 1;
+ r->handler = "proxy-server";
+
+ rewritelog(r, 1, "[per-dir %s] go-ahead with proxy request "
+ "%s [OK]", dconf->directory, r->filename);
+ return OK;
+ }
+ else if ( (strlen(r->filename) > 7 &&
+ strncmp(r->filename, "http://", 7) == 0)
+ || (strlen(r->filename) > 8 &&
+ strncmp(r->filename, "https://", 8) == 0)
+ || (strlen(r->filename) > 9 &&
+ strncmp(r->filename, "gopher://", 9) == 0)
+ || (strlen(r->filename) > 6 &&
+ strncmp(r->filename, "ftp://", 6) == 0) ) {
+ /* it was finally rewritten to a remote URL */
+
+ /* because we are in a per-dir context
+ * first try to replace the directory with its base-URL
+ * if there is a base-URL available
+ */
+ if (dconf->baseurl != NULL) {
+ /* skip 'scheme:' */
+ for (cp = r->filename; *cp != ':' && *cp != '\0'; cp++)
+ ;
+ /* skip '://' */
+ cp += 3;
+ if ((cp = strchr(cp, '/')) != NULL) {
+ rewritelog(r, 2,
+ "[per-dir %s] trying to replace "
+ "prefix %s with %s",
+ dconf->directory, dconf->directory,
+ dconf->baseurl);
+ cp2 = subst_prefix_path(r, cp, dconf->directory,
+ dconf->baseurl);
+ if (strcmp(cp2, cp) != 0) {
+ *cp = '\0';
+ r->filename = ap_pstrcat(r->pool, r->filename,
+ cp2, NULL);
+ }
+ }
+ }
+
+ /* now prepare the redirect... */
+
+ /* skip 'scheme:' */
+ for (cp = r->filename; *cp != ':' && *cp != '\0'; cp++)
+ ;
+ /* skip '://' */
+ cp += 3;
+ /* skip host part */
+ for ( ; *cp != '/' && *cp != '\0'; cp++)
+ ;
+ if (*cp != '\0') {
+ rewritelog(r, 1, "[per-dir %s] escaping %s for redirect",
+ dconf->directory, r->filename);
+ cp2 = ap_escape_uri(r->pool, cp);
+ *cp = '\0';
+ r->filename = ap_pstrcat(r->pool, r->filename, cp2, NULL);
+ }
+
+ /* append the QUERY_STRING part */
+ if (r->args != NULL) {
+ r->filename = ap_pstrcat(r->pool, r->filename,
+ "?", r->args, NULL);
+ }
+
+ /* determine HTTP redirect response code */
+ if (ap_is_HTTP_REDIRECT(r->status)) {
+ n = r->status;
+ r->status = HTTP_OK; /* make Apache kernel happy */
+ }
+ else {
+ n = REDIRECT;
+ }
+
+ /* now do the redirection */
+ ap_table_setn(r->headers_out, "Location", r->filename);
+ rewritelog(r, 1, "[per-dir %s] redirect to %s [REDIRECT/%d]",
+ dconf->directory, r->filename, n);
+ return n;
+ }
+ else if (strlen(r->filename) > 10 &&
+ strncmp(r->filename, "forbidden:", 10) == 0) {
+ /* This URL is forced to be forbidden for the requester */
+ return FORBIDDEN;
+ }
+ else if (strlen(r->filename) > 5 &&
+ strncmp(r->filename, "gone:", 5) == 0) {
+ /* This URL is forced to be gone */
+ return HTTP_GONE;
+ }
+ else {
+ /* it was finally rewritten to a local path */
+
+ /* if someone used the PASSTHROUGH flag in per-dir
+ * context we just ignore it. It is only useful
+ * in per-server context
+ */
+ if (strlen(r->filename) > 12 &&
+ strncmp(r->filename, "passthrough:", 12) == 0) {
+ r->filename = ap_pstrdup(r->pool, r->filename+12);
+ }
+
+ /* the filename has to start with a slash! */
+ if (r->filename[0] != '/') {
+ return BAD_REQUEST;
+ }
+
+ /* Check for deadlooping:
+ * At this point we KNOW that at least one rewriting
+ * rule was applied, but when the resulting URL is
+ * the same as the initial URL, we are not allowed to
+ * use the following internal redirection stuff because
+ * this would lead to a deadloop.
+ */
+ if (strcmp(r->filename, ofilename) == 0) {
+ rewritelog(r, 1, "[per-dir %s] initial URL equal rewritten "
+ "URL: %s [IGNORING REWRITE]",
+ dconf->directory, r->filename);
+ return OK;
+ }
+
+ /* if there is a valid base-URL then substitute
+ * the per-dir prefix with this base-URL if the
+ * current filename still is inside this per-dir
+ * context. If not then treat the result as a
+ * plain URL
+ */
+ if (dconf->baseurl != NULL) {
+ rewritelog(r, 2,
+ "[per-dir %s] trying to replace prefix %s with %s",
+ dconf->directory, dconf->directory, dconf->baseurl);
+ r->filename = subst_prefix_path(r, r->filename,
+ dconf->directory,
+ dconf->baseurl);
+ }
+ else {
+ /* if no explicit base-URL exists we assume
+ * that the directory prefix is also a valid URL
+ * for this webserver and only try to remove the
+ * document_root if it is prefix
+ */
+ if ((ccp = ap_document_root(r)) != NULL) {
+ prefix = ap_pstrdup(r->pool, ccp);
+ /* always NOT have a trailing slash */
+ l = strlen(prefix);
+ if (prefix[l-1] == '/') {
+ prefix[l-1] = '\0';
+ l--;
+ }
+ if (strncmp(r->filename, prefix, l) == 0) {
+ rewritelog(r, 2,
+ "[per-dir %s] strip document_root "
+ "prefix: %s -> %s",
+ dconf->directory, r->filename,
+ r->filename+l);
+ r->filename = ap_pstrdup(r->pool, r->filename+l);
+ }
+ }
+ }
+
+ /* now initiate the internal redirect */
+ rewritelog(r, 1, "[per-dir %s] internal redirect with %s "
+ "[INTERNAL REDIRECT]", dconf->directory, r->filename);
+ r->filename = ap_pstrcat(r->pool, "redirect:", r->filename, NULL);
+ r->handler = "redirect-handler";
+ return OK;
+ }
+ }
+ else {
+ rewritelog(r, 1, "[per-dir %s] pass through %s",
+ dconf->directory, r->filename);
+ return DECLINED;
+ }
+}
+
+
+/*
+**
+** Content-Handlers
+**
+** [used for redirect support]
+**
+*/
+
+static int handler_redirect(request_rec *r)
+{
+ /* just make sure that we are really meant! */
+ if (strncmp(r->filename, "redirect:", 9) != 0) {
+ return DECLINED;
+ }
+
+ /* now do the internal redirect */
+ ap_internal_redirect(ap_pstrcat(r->pool, r->filename+9,
+ r->args ? "?" : NULL, r->args, NULL), r);
+
+ /* and return gracefully */
+ return OK;
+}
+
+
+/*
+** +-------------------------------------------------------+
+** | |
+** | the rewriting engine
+** | |
+** +-------------------------------------------------------+
+*/
+
+/*
+ * Apply a complete rule set,
+ * i.e. a list of rewrite rules
+ */
+static int apply_rewrite_list(request_rec *r, array_header *rewriterules,
+ char *perdir)
+{
+ rewriterule_entry *entries;
+ rewriterule_entry *p;
+ int i;
+ int changed;
+ int rc;
+ int s;
+
+ /*
+ * Iterate over all existing rules
+ */
+ entries = (rewriterule_entry *)rewriterules->elts;
+ changed = 0;
+ loop:
+ for (i = 0; i < rewriterules->nelts; i++) {
+ p = &entries[i];
+
+ /*
+ * Ignore this rule on subrequests if we are explicitly
+ * asked to do so or this is a proxy-throughput or a
+ * forced redirect rule.
+ */
+ if (r->main != NULL &&
+ (p->flags & RULEFLAG_IGNOREONSUBREQ ||
+ p->flags & RULEFLAG_PROXY ||
+ p->flags & RULEFLAG_FORCEREDIRECT )) {
+ continue;
+ }
+
+ /*
+ * Apply the current rule.
+ */
+ rc = apply_rewrite_rule(r, p, perdir);
+ if (rc) {
+ /*
+ * Indicate a change if this was not a match-only rule.
+ */
+ if (rc != 2) {
+ changed = 1;
+ }
+
+ /*
+ * Pass-Through Feature (`RewriteRule .. .. [PT]'):
+ * Because the Apache 1.x API is very limited we
+ * need this hack to pass the rewritten URL to other
+ * modules like mod_alias, mod_userdir, etc.
+ */
+ if (p->flags & RULEFLAG_PASSTHROUGH) {
+ rewritelog(r, 2, "forcing '%s' to get passed through "
+ "to next API URI-to-filename handler", r->filename);
+ r->filename = ap_pstrcat(r->pool, "passthrough:",
+ r->filename, NULL);
+ changed = 1;
+ break;
+ }
+
+ /*
+ * Rule has the "forbidden" flag set which means that
+ * we stop processing and indicate this to the caller.
+ */
+ if (p->flags & RULEFLAG_FORBIDDEN) {
+ rewritelog(r, 2, "forcing '%s' to be forbidden", r->filename);
+ r->filename = ap_pstrcat(r->pool, "forbidden:",
+ r->filename, NULL);
+ changed = 1;
+ break;
+ }
+
+ /*
+ * Rule has the "gone" flag set which means that
+ * we stop processing and indicate this to the caller.
+ */
+ if (p->flags & RULEFLAG_GONE) {
+ rewritelog(r, 2, "forcing '%s' to be gone", r->filename);
+ r->filename = ap_pstrcat(r->pool, "gone:", r->filename, NULL);
+ changed = 1;
+ break;
+ }
+
+ /*
+ * Stop processing also on proxy pass-through and
+ * last-rule and new-round flags.
+ */
+ if (p->flags & RULEFLAG_PROXY) {
+ break;
+ }
+ if (p->flags & RULEFLAG_LASTRULE) {
+ break;
+ }
+
+ /*
+ * On "new-round" flag we just start from the top of
+ * the rewriting ruleset again.
+ */
+ if (p->flags & RULEFLAG_NEWROUND) {
+ goto loop;
+ }
+
+ /*
+ * If we are forced to skip N next rules, do it now.
+ */
+ if (p->skip > 0) {
+ s = p->skip;
+ while ( i < rewriterules->nelts
+ && s > 0) {
+ i++;
+ p = &entries[i];
+ s--;
+ }
+ }
+ }
+ else {
+ /*
+ * If current rule is chained with next rule(s),
+ * skip all this next rule(s)
+ */
+ while ( i < rewriterules->nelts
+ && p->flags & RULEFLAG_CHAIN) {
+ i++;
+ p = &entries[i];
+ }
+ }
+ }
+ return changed;
+}
+
+/*
+ * Apply a single(!) rewrite rule
+ */
+static int apply_rewrite_rule(request_rec *r, rewriterule_entry *p,
+ char *perdir)
+{
+ char *uri;
+ char *output;
+ const char *vary;
+ char newuri[MAX_STRING_LEN];
+ char env[MAX_STRING_LEN];
+ regex_t *regexp;
+ regmatch_t regmatch[MAX_NMATCH];
+ backrefinfo *briRR = NULL;
+ backrefinfo *briRC = NULL;
+ int prefixstrip;
+ int failed;
+ array_header *rewriteconds;
+ rewritecond_entry *conds;
+ rewritecond_entry *c;
+ int i;
+ int rc;
+
+ /*
+ * Initialisation
+ */
+ uri = r->filename;
+ regexp = p->regexp;
+ output = p->output;
+
+ /*
+ * Add (perhaps splitted away) PATH_INFO postfix to URL to
+ * make sure we really match against the complete URL.
+ */
+ if (perdir != NULL && r->path_info != NULL && r->path_info[0] != '\0') {
+ rewritelog(r, 3, "[per-dir %s] add path-info postfix: %s -> %s%s",
+ perdir, uri, uri, r->path_info);
+ uri = ap_pstrcat(r->pool, uri, r->path_info, NULL);
+ }
+
+ /*
+ * On per-directory context (.htaccess) strip the location
+ * prefix from the URL to make sure patterns apply only to
+ * the local part. Additionally indicate this special
+ * threatment in the logfile.
+ */
+ prefixstrip = 0;
+ if (perdir != NULL) {
+ if ( strlen(uri) >= strlen(perdir)
+ && strncmp(uri, perdir, strlen(perdir)) == 0) {
+ rewritelog(r, 3, "[per-dir %s] strip per-dir prefix: %s -> %s",
+ perdir, uri, uri+strlen(perdir));
+ uri = uri+strlen(perdir);
+ prefixstrip = 1;
+ }
+ }
+
+ /*
+ * Try to match the URI against the RewriteRule pattern
+ * and exit immeddiately if it didn't apply.
+ */
+ if (perdir == NULL) {
+ rewritelog(r, 3, "applying pattern '%s' to uri '%s'",
+ p->pattern, uri);
+ }
+ else {
+ rewritelog(r, 3, "[per-dir %s] applying pattern '%s' to uri '%s'",
+ perdir, p->pattern, uri);
+ }
+ rc = (ap_regexec(regexp, uri, regexp->re_nsub+1, regmatch, 0) == 0);
+ if (! (( rc && !(p->flags & RULEFLAG_NOTMATCH)) ||
+ (!rc && (p->flags & RULEFLAG_NOTMATCH)) ) ) {
+ return 0;
+ }
+
+ /*
+ * Else create the RewriteRule `regsubinfo' structure which
+ * holds the substitution information.
+ */
+ briRR = (backrefinfo *)ap_palloc(r->pool, sizeof(backrefinfo));
+ if (!rc && (p->flags & RULEFLAG_NOTMATCH)) {
+ /* empty info on negative patterns */
+ briRR->source = "";
+ briRR->nsub = 0;
+ }
+ else {
+ briRR->source = ap_pstrdup(r->pool, uri);
+ briRR->nsub = regexp->re_nsub;
+ memcpy((void *)(briRR->regmatch), (void *)(regmatch),
+ sizeof(regmatch));
+ }
+
+ /*
+ * Initiallally create the RewriteCond backrefinfo with
+ * empty backrefinfo, i.e. not subst parts
+ * (this one is adjusted inside apply_rewrite_cond() later!!)
+ */
+ briRC = (backrefinfo *)ap_pcalloc(r->pool, sizeof(backrefinfo));
+ briRC->source = "";
+ briRC->nsub = 0;
+
+ /*
+ * Ok, we already know the pattern has matched, but we now
+ * additionally have to check for all existing preconditions
+ * (RewriteCond) which have to be also true. We do this at
+ * this very late stage to avoid unnessesary checks which
+ * would slow down the rewriting engine!!
+ */
+ rewriteconds = p->rewriteconds;
+ conds = (rewritecond_entry *)rewriteconds->elts;
+ failed = 0;
+ for (i = 0; i < rewriteconds->nelts; i++) {
+ c = &conds[i];
+ rc = apply_rewrite_cond(r, c, perdir, briRR, briRC);
+ if (c->flags & CONDFLAG_ORNEXT) {
+ /*
+ * The "OR" case
+ */
+ if (rc == 0) {
+ /* One condition is false, but another can be
+ * still true, so we have to continue...
+ */
+ ap_table_unset(r->notes, VARY_KEY_THIS);
+ continue;
+ }
+ else {
+ /* One true condition is enough in "or" case, so
+ * skip the other conditions which are "ornext"
+ * chained
+ */
+ while ( i < rewriteconds->nelts
+ && c->flags & CONDFLAG_ORNEXT) {
+ i++;
+ c = &conds[i];
+ }
+ continue;
+ }
+ }
+ else {
+ /*
+ * The "AND" case, i.e. no "or" flag,
+ * so a single failure means total failure.
+ */
+ if (rc == 0) {
+ failed = 1;
+ break;
+ }
+ }
+ vary = ap_table_get(r->notes, VARY_KEY_THIS);
+ if (vary != NULL) {
+ ap_table_merge(r->notes, VARY_KEY, vary);
+ ap_table_unset(r->notes, VARY_KEY_THIS);
+ }
+ }
+ /* if any condition fails the complete rule fails */
+ if (failed) {
+ ap_table_unset(r->notes, VARY_KEY);
+ ap_table_unset(r->notes, VARY_KEY_THIS);
+ return 0;
+ }
+
+ /*
+ * Regardless of what we do next, we've found a match. Check to see
+ * if any of the request header fields were involved, and add them
+ * to the Vary field of the response.
+ */
+ if ((vary = ap_table_get(r->notes, VARY_KEY)) != NULL) {
+ ap_table_merge(r->headers_out, "Vary", vary);
+ ap_table_unset(r->notes, VARY_KEY);
+ }
+
+ /*
+ * If this is a pure matching rule (`RewriteRule -')
+ * we stop processing and return immediately. The only thing
+ * we have not to forget are the environment variables
+ * (`RewriteRule - [E=...]')
+ */
+ if (strcmp(output, "-") == 0) {
+ for (i = 0; p->env[i] != NULL; i++) {
+ /* 1. take the string */
+ ap_cpystrn(env, p->env[i], sizeof(env));
+ /* 2. expand $N (i.e. backrefs to RewriteRule pattern) */
+ expand_backref_inbuffer(r->pool, env, sizeof(env), briRR, '$');
+ /* 3. expand %N (i.e. backrefs to latest RewriteCond pattern) */
+ expand_backref_inbuffer(r->pool, env, sizeof(env), briRC, '%');
+ /* 4. expand %{...} (i.e. variables) */
+ expand_variables_inbuffer(r, env, sizeof(env));
+ /* 5. expand ${...} (RewriteMap lookups) */
+ expand_map_lookups(r, env, sizeof(env));
+ /* and add the variable to Apache's structures */
+ add_env_variable(r, env);
+ }
+ if (p->forced_mimetype != NULL) {
+ if (perdir == NULL) {
+ /* In the per-server context we can force the MIME-type
+ * the correct way by notifying our MIME-type hook handler
+ * to do the job when the MIME-type API stage is reached.
+ */
+ rewritelog(r, 2, "remember %s to have MIME-type '%s'",
+ r->filename, p->forced_mimetype);
+ ap_table_setn(r->notes, REWRITE_FORCED_MIMETYPE_NOTEVAR,
+ p->forced_mimetype);
+ }
+ else {
+ /* In per-directory context we operate in the Fixup API hook
+ * which is after the MIME-type hook, so our MIME-type handler
+ * has no chance to set r->content_type. And because we are
+ * in the situation where no substitution takes place no
+ * sub-request will happen (which could solve the
+ * restriction). As a workaround we do it ourself now
+ * immediately although this is not strictly API-conforming.
+ * But it's the only chance we have...
+ */
+ rewritelog(r, 1, "[per-dir %s] force %s to have MIME-type "
+ "'%s'", perdir, r->filename, p->forced_mimetype);
+ r->content_type = p->forced_mimetype;
+ }
+ }
+ return 2;
+ }
+
+ /*
+ * Ok, now we finally know all patterns have matched and
+ * that there is something to replace, so we create the
+ * substitution URL string in `newuri'.
+ */
+ /* 1. take the output string */
+ ap_cpystrn(newuri, output, sizeof(newuri));
+ /* 2. expand $N (i.e. backrefs to RewriteRule pattern) */
+ expand_backref_inbuffer(r->pool, newuri, sizeof(newuri), briRR, '$');
+ /* 3. expand %N (i.e. backrefs to latest RewriteCond pattern) */
+ expand_backref_inbuffer(r->pool, newuri, sizeof(newuri), briRC, '%');
+ /* 4. expand %{...} (i.e. variables) */
+ expand_variables_inbuffer(r, newuri, sizeof(newuri));
+ /* 5. expand ${...} (RewriteMap lookups) */
+ expand_map_lookups(r, newuri, sizeof(newuri));
+ /* and log the result... */
+ if (perdir == NULL) {
+ rewritelog(r, 2, "rewrite %s -> %s", uri, newuri);
+ }
+ else {
+ rewritelog(r, 2, "[per-dir %s] rewrite %s -> %s", perdir, uri, newuri);
+ }
+
+ /*
+ * Additionally do expansion for the environment variable
+ * strings (`RewriteRule .. .. [E=]').
+ */
+ for (i = 0; p->env[i] != NULL; i++) {
+ /* 1. take the string */
+ ap_cpystrn(env, p->env[i], sizeof(env));
+ /* 2. expand $N (i.e. backrefs to RewriteRule pattern) */
+ expand_backref_inbuffer(r->pool, env, sizeof(env), briRR, '$');
+ /* 3. expand %N (i.e. backrefs to latest RewriteCond pattern) */
+ expand_backref_inbuffer(r->pool, env, sizeof(env), briRC, '%');
+ /* 4. expand %{...} (i.e. variables) */
+ expand_variables_inbuffer(r, env, sizeof(env));
+ /* 5. expand ${...} (RewriteMap lookups) */
+ expand_map_lookups(r, env, sizeof(env));
+ /* and add the variable to Apache's structures */
+ add_env_variable(r, env);
+ }
+
+ /*
+ * Now replace API's knowledge of the current URI:
+ * Replace r->filename with the new URI string and split out
+ * an on-the-fly generated QUERY_STRING part into r->args
+ */
+ r->filename = ap_pstrdup(r->pool, newuri);
+ splitout_queryargs(r, p->flags & RULEFLAG_QSAPPEND);
+
+ /*
+ * Again add the previously stripped per-directory location
+ * prefix if the new URI is not a new one for this
+ * location, i.e. if it's not starting with either a slash
+ * or a fully qualified URL scheme.
+ */
+ i = strlen(r->filename);
+ if ( prefixstrip
+ && !( r->filename[0] == '/'
+ || ( (i > 7 && strncasecmp(r->filename, "http://", 7) == 0)
+ || (i > 8 && strncasecmp(r->filename, "https://", 8) == 0)
+ || (i > 9 && strncasecmp(r->filename, "gopher://", 9) == 0)
+ || (i > 6 && strncasecmp(r->filename, "ftp://", 6) == 0)))) {
+ rewritelog(r, 3, "[per-dir %s] add per-dir prefix: %s -> %s%s",
+ perdir, r->filename, perdir, r->filename);
+ r->filename = ap_pstrcat(r->pool, perdir, r->filename, NULL);
+ }
+
+ /*
+ * If this rule is forced for proxy throughput
+ * (`RewriteRule ... ... [P]') then emulate mod_proxy's
+ * URL-to-filename handler to be sure mod_proxy is triggered
+ * for this URL later in the Apache API. But make sure it is
+ * a fully-qualified URL. (If not it is qualified with
+ * ourself).
+ */
+ if (p->flags & RULEFLAG_PROXY) {
+ fully_qualify_uri(r);
+ if (perdir == NULL) {
+ rewritelog(r, 2, "forcing proxy-throughput with %s", r->filename);
+ }
+ else {
+ rewritelog(r, 2, "[per-dir %s] forcing proxy-throughput with %s",
+ perdir, r->filename);
+ }
+ r->filename = ap_pstrcat(r->pool, "proxy:", r->filename, NULL);
+ return 1;
+ }
+
+ /*
+ * If this rule is explicitly forced for HTTP redirection
+ * (`RewriteRule .. .. [R]') then force an external HTTP
+ * redirect. But make sure it is a fully-qualified URL. (If
+ * not it is qualified with ourself).
+ */
+ if (p->flags & RULEFLAG_FORCEREDIRECT) {
+ fully_qualify_uri(r);
+ if (perdir == NULL) {
+ rewritelog(r, 2,
+ "explicitly forcing redirect with %s", r->filename);
+ }
+ else {
+ rewritelog(r, 2,
+ "[per-dir %s] explicitly forcing redirect with %s",
+ perdir, r->filename);
+ }
+ r->status = p->forced_responsecode;
+ return 1;
+ }
+
+ /*
+ * Special Rewriting Feature: Self-Reduction
+ * We reduce the URL by stripping a possible
+ * http[s]://[:] prefix, i.e. a prefix which
+ * corresponds to ourself. This is to simplify rewrite maps
+ * and to avoid recursion, etc. When this prefix is not a
+ * coincidence then the user has to use [R] explicitly (see
+ * above).
+ */
+ reduce_uri(r);
+
+ /*
+ * If this rule is still implicitly forced for HTTP
+ * redirection (`RewriteRule .. ://...') then
+ * directly force an external HTTP redirect.
+ */
+ i = strlen(r->filename);
+ if ( (i > 7 && strncasecmp(r->filename, "http://", 7) == 0)
+ || (i > 8 && strncasecmp(r->filename, "https://", 8) == 0)
+ || (i > 9 && strncasecmp(r->filename, "gopher://", 9) == 0)
+ || (i > 6 && strncasecmp(r->filename, "ftp://", 6) == 0)) {
+ if (perdir == NULL) {
+ rewritelog(r, 2,
+ "implicitly forcing redirect (rc=%d) with %s",
+ p->forced_responsecode, r->filename);
+ }
+ else {
+ rewritelog(r, 2, "[per-dir %s] implicitly forcing redirect "
+ "(rc=%d) with %s", perdir, p->forced_responsecode,
+ r->filename);
+ }
+ r->status = p->forced_responsecode;
+ return 1;
+ }
+
+ /*
+ * Now we are sure it is not a fully qualified URL. But
+ * there is still one special case left: A local rewrite in
+ * per-directory context, i.e. a substitution URL which does
+ * not start with a slash. Here we add again the initially
+ * stripped per-directory prefix.
+ */
+ if (prefixstrip && r->filename[0] != '/') {
+ rewritelog(r, 3, "[per-dir %s] add per-dir prefix: %s -> %s%s",
+ perdir, r->filename, perdir, r->filename);
+ r->filename = ap_pstrcat(r->pool, perdir, r->filename, NULL);
+ }
+
+ /*
+ * Finally we had to remember if a MIME-type should be
+ * forced for this URL (`RewriteRule .. .. [T=]')
+ * Later in the API processing phase this is forced by our
+ * MIME API-hook function. This time its no problem even for
+ * the per-directory context (where the MIME-type hook was
+ * already processed) because a sub-request happens ;-)
+ */
+ if (p->forced_mimetype != NULL) {
+ ap_table_setn(r->notes, REWRITE_FORCED_MIMETYPE_NOTEVAR,
+ p->forced_mimetype);
+ if (perdir == NULL) {
+ rewritelog(r, 2, "remember %s to have MIME-type '%s'",
+ r->filename, p->forced_mimetype);
+ }
+ else {
+ rewritelog(r, 2,
+ "[per-dir %s] remember %s to have MIME-type '%s'",
+ perdir, r->filename, p->forced_mimetype);
+ }
+ }
+
+ /*
+ * Puuhhhhhhhh... WHAT COMPLICATED STUFF ;_)
+ * But now we're done for this particular rule.
+ */
+ return 1;
+}
+
+static int apply_rewrite_cond(request_rec *r, rewritecond_entry *p,
+ char *perdir, backrefinfo *briRR,
+ backrefinfo *briRC)
+{
+ char input[MAX_STRING_LEN];
+ struct stat sb;
+ request_rec *rsub;
+ regmatch_t regmatch[MAX_NMATCH];
+ int rc;
+
+ /*
+ * Construct the string we match against
+ */
+
+ /* 1. take the string */
+ ap_cpystrn(input, p->input, sizeof(input));
+ /* 2. expand $N (i.e. backrefs to RewriteRule pattern) */
+ expand_backref_inbuffer(r->pool, input, sizeof(input), briRR, '$');
+ /* 3. expand %N (i.e. backrefs to latest RewriteCond pattern) */
+ expand_backref_inbuffer(r->pool, input, sizeof(input), briRC, '%');
+ /* 4. expand %{...} (i.e. variables) */
+ expand_variables_inbuffer(r, input, sizeof(input));
+ /* 5. expand ${...} (RewriteMap lookups) */
+ expand_map_lookups(r, input, sizeof(input));
+
+ /*
+ * Apply the patterns
+ */
+
+ rc = 0;
+ if (strcmp(p->pattern, "-f") == 0) {
+ if (stat(input, &sb) == 0) {
+ if (S_ISREG(sb.st_mode)) {
+ rc = 1;
+ }
+ }
+ }
+ else if (strcmp(p->pattern, "-s") == 0) {
+ if (stat(input, &sb) == 0) {
+ if (S_ISREG(sb.st_mode) && sb.st_size > 0) {
+ rc = 1;
+ }
+ }
+ }
+ else if (strcmp(p->pattern, "-l") == 0) {
+#if !defined(OS2) && !defined(WIN32)
+ if (lstat(input, &sb) == 0) {
+ if (S_ISLNK(sb.st_mode)) {
+ rc = 1;
+ }
+ }
+#endif
+ }
+ else if (strcmp(p->pattern, "-d") == 0) {
+ if (stat(input, &sb) == 0) {
+ if (S_ISDIR(sb.st_mode)) {
+ rc = 1;
+ }
+ }
+ }
+ else if (strcmp(p->pattern, "-U") == 0) {
+ /* avoid infinite subrequest recursion */
+ if (strlen(input) > 0 /* nonempty path, and */
+ && ( r->main == NULL /* - either not in a subrequest */
+ || ( r->main->uri != NULL /* - or in a subrequest... */
+ && r->uri != NULL /* ...and URIs aren't NULL... */
+ /* ...and sub/main URIs differ */
+ && strcmp(r->main->uri, r->uri) != 0) ) ) {
+
+ /* run a URI-based subrequest */
+ rsub = ap_sub_req_lookup_uri(input, r);
+
+ /* URI exists for any result up to 3xx, redirects allowed */
+ if (rsub->status < 400)
+ rc = 1;
+
+ /* log it */
+ rewritelog(r, 5, "RewriteCond URI (-U) check: "
+ "path=%s -> status=%d", input, rsub->status);
+
+ /* cleanup by destroying the subrequest */
+ ap_destroy_sub_req(rsub);
+ }
+ }
+ else if (strcmp(p->pattern, "-F") == 0) {
+ /* avoid infinite subrequest recursion */
+ if (strlen(input) > 0 /* nonempty path, and */
+ && ( r->main == NULL /* - either not in a subrequest */
+ || ( r->main->uri != NULL /* - or in a subrequest... */
+ && r->uri != NULL /* ...and URIs aren't NULL... */
+ /* ...and sub/main URIs differ */
+ && strcmp(r->main->uri, r->uri) != 0) ) ) {
+
+ /* process a file-based subrequest:
+ * this differs from -U in that no path translation is done.
+ */
+ rsub = ap_sub_req_lookup_file(input, r);
+
+ /* file exists for any result up to 2xx, no redirects */
+ if (rsub->status < 300 &&
+ /* double-check that file exists since default result is 200 */
+ stat(rsub->filename, &sb) == 0) {
+ rc = 1;
+ }
+
+ /* log it */
+ rewritelog(r, 5, "RewriteCond file (-F) check: path=%s "
+ "-> file=%s status=%d", input, rsub->filename,
+ rsub->status);
+
+ /* cleanup by destroying the subrequest */
+ ap_destroy_sub_req(rsub);
+ }
+ }
+ else if (strlen(p->pattern) > 1 && *(p->pattern) == '>') {
+ rc = (compare_lexicography(input, p->pattern+1) == 1 ? 1 : 0);
+ }
+ else if (strlen(p->pattern) > 1 && *(p->pattern) == '<') {
+ rc = (compare_lexicography(input, p->pattern+1) == -1 ? 1 : 0);
+ }
+ else if (strlen(p->pattern) > 1 && *(p->pattern) == '=') {
+ if (strcmp(p->pattern+1, "\"\"") == 0) {
+ rc = (*input == '\0');
+ }
+ else {
+ rc = (strcmp(input, p->pattern+1) == 0 ? 1 : 0);
+ }
+ }
+ else {
+ /* it is really a regexp pattern, so apply it */
+ rc = (ap_regexec(p->regexp, input,
+ p->regexp->re_nsub+1, regmatch,0) == 0);
+
+ /* if it isn't a negated pattern and really matched
+ we update the passed-through regex subst info structure */
+ if (rc && !(p->flags & CONDFLAG_NOTMATCH)) {
+ briRC->source = ap_pstrdup(r->pool, input);
+ briRC->nsub = p->regexp->re_nsub;
+ memcpy((void *)(briRC->regmatch), (void *)(regmatch),
+ sizeof(regmatch));
+ }
+ }
+
+ /* if this is a non-matching regexp, just negate the result */
+ if (p->flags & CONDFLAG_NOTMATCH) {
+ rc = !rc;
+ }
+
+ rewritelog(r, 4, "RewriteCond: input='%s' pattern='%s%s' => %s",
+ input, (p->flags & CONDFLAG_NOTMATCH ? "!" : ""),
+ p->pattern, rc ? "matched" : "not-matched");
+
+ /* end just return the result */
+ return rc;
+}
+
+
+/*
+** +-------------------------------------------------------+
+** | |
+** | URL transformation functions
+** | |
+** +-------------------------------------------------------+
+*/
+
+/*
+**
+** split out a QUERY_STRING part from
+** the current URI string
+**
+*/
+
+static void splitout_queryargs(request_rec *r, int qsappend)
+{
+ char *q;
+ char *olduri;
+
+ q = strchr(r->filename, '?');
+ if (q != NULL) {
+ olduri = ap_pstrdup(r->pool, r->filename);
+ *q++ = '\0';
+ if (qsappend) {
+ r->args = ap_pstrcat(r->pool, q, "&", r->args, NULL);
+ }
+ else {
+ r->args = ap_pstrdup(r->pool, q);
+ }
+ if (strlen(r->args) == 0) {
+ r->args = NULL;
+ rewritelog(r, 3, "split uri=%s -> uri=%s, args=", olduri,
+ r->filename);
+ }
+ else {
+ if (r->args[strlen(r->args)-1] == '&') {
+ r->args[strlen(r->args)-1] = '\0';
+ }
+ rewritelog(r, 3, "split uri=%s -> uri=%s, args=%s", olduri,
+ r->filename, r->args);
+ }
+ }
+ return;
+}
+
+
+/*
+**
+** strip 'http[s]://ourhost/' from URI
+**
+*/
+
+static void reduce_uri(request_rec *r)
+{
+ char *cp;
+ unsigned short port;
+ char *portp;
+ char *hostp;
+ char *url;
+ char c;
+ char host[LONG_STRING_LEN];
+ char buf[MAX_STRING_LEN];
+ char *olduri;
+ int l;
+
+ cp = ap_http_method(r);
+ l = strlen(cp);
+ if ( strlen(r->filename) > l+3
+ && strncasecmp(r->filename, cp, l) == 0
+ && r->filename[l] == ':'
+ && r->filename[l+1] == '/'
+ && r->filename[l+2] == '/' ) {
+ /* there was really a rewrite to a remote path */
+
+ olduri = ap_pstrdup(r->pool, r->filename); /* save for logging */
+
+ /* cut the hostname and port out of the URI */
+ ap_cpystrn(buf, r->filename+(l+3), sizeof(buf));
+ hostp = buf;
+ for (cp = hostp; *cp != '\0' && *cp != '/' && *cp != ':'; cp++)
+ ;
+ if (*cp == ':') {
+ /* set host */
+ *cp++ = '\0';
+ ap_cpystrn(host, hostp, sizeof(host));
+ /* set port */
+ portp = cp;
+ for (; *cp != '\0' && *cp != '/'; cp++)
+ ;
+ c = *cp;
+ *cp = '\0';
+ port = atoi(portp);
+ *cp = c;
+ /* set remaining url */
+ url = cp;
+ }
+ else if (*cp == '/') {
+ /* set host */
+ *cp = '\0';
+ ap_cpystrn(host, hostp, sizeof(host));
+ *cp = '/';
+ /* set port */
+ port = ap_default_port(r);
+ /* set remaining url */
+ url = cp;
+ }
+ else {
+ /* set host */
+ ap_cpystrn(host, hostp, sizeof(host));
+ /* set port */
+ port = ap_default_port(r);
+ /* set remaining url */
+ url = "/";
+ }
+
+ /* now check whether we could reduce it to a local path... */
+ if (ap_matches_request_vhost(r, host, port)) {
+ /* this is our host, so only the URL remains */
+ r->filename = ap_pstrdup(r->pool, url);
+ rewritelog(r, 3, "reduce %s -> %s", olduri, r->filename);
+ }
+ }
+ return;
+}
+
+
+/*
+**
+** add 'http[s]://ourhost[:ourport]/' to URI
+** if URI is still not fully qualified
+**
+*/
+
+static void fully_qualify_uri(request_rec *r)
+{
+ int i;
+ char buf[32];
+ const char *thisserver;
+ char *thisport;
+ int port;
+
+ i = strlen(r->filename);
+ if (!( (i > 7 && strncasecmp(r->filename, "http://", 7) == 0)
+ || (i > 8 && strncasecmp(r->filename, "https://", 8) == 0)
+ || (i > 9 && strncasecmp(r->filename, "gopher://", 9) == 0)
+ || (i > 6 && strncasecmp(r->filename, "ftp://", 6) == 0))) {
+
+ thisserver = ap_get_server_name(r);
+ port = ap_get_server_port(r);
+ if (ap_is_default_port(port,r)) {
+ thisport = "";
+ }
+ else {
+ ap_snprintf(buf, sizeof(buf), ":%u", port);
+ thisport = buf;
+ }
+
+ if (r->filename[0] == '/') {
+ r->filename = ap_psprintf(r->pool, "%s://%s%s%s",
+ ap_http_method(r), thisserver,
+ thisport, r->filename);
+ }
+ else {
+ r->filename = ap_psprintf(r->pool, "%s://%s%s/%s",
+ ap_http_method(r), thisserver,
+ thisport, r->filename);
+ }
+ }
+ return;
+}
+
+
+/*
+**
+** Expand the %0-%9 or $0-$9 regex backreferences
+**
+*/
+
+static void expand_backref_inbuffer(pool *p, char *buf, int nbuf,
+ backrefinfo *bri, char c)
+{
+ int i;
+
+ if (bri->nsub < 1) {
+ return;
+ }
+
+ if (c != '$') {
+ /* safe existing $N backrefs and replace N with $N backrefs */
+ for (i = 0; buf[i] != '\0' && i < nbuf; i++) {
+ if (buf[i] == '$' && (buf[i+1] >= '0' && buf[i+1] <= '9')) {
+ buf[i++] = '\001';
+ }
+ else if (buf[i] == c && (buf[i+1] >= '0' && buf[i+1] <= '9')) {
+ buf[i++] = '$';
+ }
+ }
+ }
+
+ /* now apply the pregsub() function */
+ ap_cpystrn(buf, ap_pregsub(p, buf, bri->source,
+ bri->nsub+1, bri->regmatch), nbuf);
+
+ if (c != '$') {
+ /* restore the original $N backrefs */
+ for (i = 0; buf[i] != '\0' && i < nbuf; i++) {
+ if (buf[i] == '\001' && (buf[i+1] >= '0' && buf[i+1] <= '9')) {
+ buf[i++] = '$';
+ }
+ }
+ }
+}
+
+
+/*
+**
+** Expand tilde-paths (/~user) through
+** Unix /etc/passwd database information
+**
+*/
+#ifndef WIN32
+static char *expand_tildepaths(request_rec *r, char *uri)
+{
+ char user[LONG_STRING_LEN];
+ struct passwd *pw;
+ char *newuri;
+ int i, j;
+
+ newuri = uri;
+ if (uri != NULL && strlen(uri) > 2 && uri[0] == '/' && uri[1] == '~') {
+ /* cut out the username */
+ for (j = 0, i = 2; j < sizeof(user)-1
+ && uri[i] != '\0'
+ && uri[i] != '/' ; ) {
+ user[j++] = uri[i++];
+ }
+ user[j] = '\0';
+
+ /* lookup username in systems passwd file */
+ if ((pw = getpwnam(user)) != NULL) {
+ /* ok, user was found, so expand the ~user string */
+ if (uri[i] != '\0') {
+ /* ~user/anything... has to be expanded */
+ if (pw->pw_dir[strlen(pw->pw_dir)-1] == '/') {
+ pw->pw_dir[strlen(pw->pw_dir)-1] = '\0';
+ }
+ newuri = ap_pstrcat(r->pool, pw->pw_dir, uri+i, NULL);
+ }
+ else {
+ /* only ~user has to be expanded */
+ newuri = ap_pstrdup(r->pool, pw->pw_dir);
+ }
+ }
+ }
+ return newuri;
+}
+#endif
+
+/*
+**
+** mapfile expansion support
+** i.e. expansion of MAP lookup directives
+** ${:} in RewriteRule rhs
+**
+*/
+
+#define limit_length(n) (n > LONG_STRING_LEN-1 ? LONG_STRING_LEN-1 : n)
+
+static void expand_map_lookups(request_rec *r, char *uri, int uri_len)
+{
+ char newuri[MAX_STRING_LEN];
+ char *cpI;
+ char *cpIE;
+ char *cpO;
+ char *cpT;
+ char *cpT2;
+ char mapname[LONG_STRING_LEN];
+ char mapkey[LONG_STRING_LEN];
+ char defaultvalue[LONG_STRING_LEN];
+ int n;
+
+ cpI = uri;
+ cpIE = cpI+strlen(cpI);
+ cpO = newuri;
+ while (cpI < cpIE) {
+ if (cpI+6 < cpIE && strncmp(cpI, "${", 2) == 0) {
+ /* missing delimiter -> take it as plain text */
+ if ( strchr(cpI+2, ':') == NULL
+ || strchr(cpI+2, '}') == NULL) {
+ memcpy(cpO, cpI, 2);
+ cpO += 2;
+ cpI += 2;
+ continue;
+ }
+ cpI += 2;
+
+ cpT = strchr(cpI, ':');
+ n = cpT-cpI;
+ memcpy(mapname, cpI, limit_length(n));
+ mapname[limit_length(n)] = '\0';
+ cpI += n+1;
+
+ cpT2 = strchr(cpI, '|');
+ cpT = strchr(cpI, '}');
+ if (cpT2 != NULL && cpT2 < cpT) {
+ n = cpT2-cpI;
+ memcpy(mapkey, cpI, limit_length(n));
+ mapkey[limit_length(n)] = '\0';
+ cpI += n+1;
+
+ n = cpT-cpI;
+ memcpy(defaultvalue, cpI, limit_length(n));
+ defaultvalue[limit_length(n)] = '\0';
+ cpI += n+1;
+ }
+ else {
+ n = cpT-cpI;
+ memcpy(mapkey, cpI, limit_length(n));
+ mapkey[limit_length(n)] = '\0';
+ cpI += n+1;
+
+ defaultvalue[0] = '\0';
+ }
+
+ cpT = lookup_map(r, mapname, mapkey);
+ if (cpT != NULL) {
+ n = strlen(cpT);
+ if (cpO + n >= newuri + sizeof(newuri)) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR,
+ r, "insufficient space in "
+ "expand_map_lookups, aborting");
+ return;
+ }
+ memcpy(cpO, cpT, n);
+ cpO += n;
+ }
+ else {
+ n = strlen(defaultvalue);
+ if (cpO + n >= newuri + sizeof(newuri)) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR,
+ r, "insufficient space in "
+ "expand_map_lookups, aborting");
+ return;
+ }
+ memcpy(cpO, defaultvalue, n);
+ cpO += n;
+ }
+ }
+ else {
+ cpT = strstr(cpI, "${");
+ if (cpT == NULL)
+ cpT = cpI+strlen(cpI);
+ n = cpT-cpI;
+ if (cpO + n >= newuri + sizeof(newuri)) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR,
+ r, "insufficient space in "
+ "expand_map_lookups, aborting");
+ return;
+ }
+ memcpy(cpO, cpI, n);
+ cpO += n;
+ cpI += n;
+ }
+ }
+ *cpO = '\0';
+ ap_cpystrn(uri, newuri, uri_len);
+ return;
+}
+
+#undef limit_length
+
+
+
+/*
+** +-------------------------------------------------------+
+** | |
+** | DBM hashfile support
+** | |
+** +-------------------------------------------------------+
+*/
+
+
+static char *lookup_map(request_rec *r, char *name, char *key)
+{
+ void *sconf;
+ rewrite_server_conf *conf;
+ array_header *rewritemaps;
+ rewritemap_entry *entries;
+ rewritemap_entry *s;
+ char *value;
+ struct stat st;
+ int i;
+
+ /* get map configuration */
+ sconf = r->server->module_config;
+ conf = (rewrite_server_conf *)ap_get_module_config(sconf,
+ &rewrite_module);
+ rewritemaps = conf->rewritemaps;
+
+ entries = (rewritemap_entry *)rewritemaps->elts;
+ for (i = 0; i < rewritemaps->nelts; i++) {
+ s = &entries[i];
+ if (strcmp(s->name, name) == 0) {
+ if (s->type == MAPTYPE_TXT) {
+ if (stat(s->checkfile, &st) == -1) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
+ "mod_rewrite: can't access text RewriteMap "
+ "file %s", s->checkfile);
+ rewritelog(r, 1, "can't open RewriteMap file, "
+ "see error log");
+ return NULL;
+ }
+ value = get_cache_string(cachep, s->name, CACHEMODE_TS,
+ st.st_mtime, key);
+ if (value == NULL) {
+ rewritelog(r, 6, "cache lookup FAILED, forcing new "
+ "map lookup");
+ if ((value =
+ lookup_map_txtfile(r, s->datafile, key)) != NULL) {
+ rewritelog(r, 5, "map lookup OK: map=%s key=%s[txt] "
+ "-> val=%s", s->name, key, value);
+ set_cache_string(cachep, s->name, CACHEMODE_TS,
+ st.st_mtime, key, value);
+ return value;
+ }
+ else {
+ rewritelog(r, 5, "map lookup FAILED: map=%s[txt] "
+ "key=%s", s->name, key);
+ set_cache_string(cachep, s->name, CACHEMODE_TS,
+ st.st_mtime, key, "");
+ return NULL;
+ }
+ }
+ else {
+ rewritelog(r, 5, "cache lookup OK: map=%s[txt] key=%s "
+ "-> val=%s", s->name, key, value);
+ return value[0] != '\0' ? value : NULL;
+ }
+ }
+ else if (s->type == MAPTYPE_DBM) {
+#ifndef NO_DBM_REWRITEMAP
+ if (stat(s->checkfile, &st) == -1) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
+ "mod_rewrite: can't access DBM RewriteMap "
+ "file %s", s->checkfile);
+ rewritelog(r, 1, "can't open DBM RewriteMap file, "
+ "see error log");
+ return NULL;
+ }
+ value = get_cache_string(cachep, s->name, CACHEMODE_TS,
+ st.st_mtime, key);
+ if (value == NULL) {
+ rewritelog(r, 6,
+ "cache lookup FAILED, forcing new map lookup");
+ if ((value =
+ lookup_map_dbmfile(r, s->datafile, key)) != NULL) {
+ rewritelog(r, 5, "map lookup OK: map=%s[dbm] key=%s "
+ "-> val=%s", s->name, key, value);
+ set_cache_string(cachep, s->name, CACHEMODE_TS,
+ st.st_mtime, key, value);
+ return value;
+ }
+ else {
+ rewritelog(r, 5, "map lookup FAILED: map=%s[dbm] "
+ "key=%s", s->name, key);
+ set_cache_string(cachep, s->name, CACHEMODE_TS,
+ st.st_mtime, key, "");
+ return NULL;
+ }
+ }
+ else {
+ rewritelog(r, 5, "cache lookup OK: map=%s[dbm] key=%s "
+ "-> val=%s", s->name, key, value);
+ return value[0] != '\0' ? value : NULL;
+ }
+#else
+ return NULL;
+#endif
+ }
+ else if (s->type == MAPTYPE_PRG) {
+ if ((value =
+ lookup_map_program(r, s->fpin, s->fpout, key)) != NULL) {
+ rewritelog(r, 5, "map lookup OK: map=%s key=%s -> val=%s",
+ s->name, key, value);
+ return value;
+ }
+ else {
+ rewritelog(r, 5, "map lookup FAILED: map=%s key=%s",
+ s->name, key);
+ }
+ }
+ else if (s->type == MAPTYPE_INT) {
+ if ((value = lookup_map_internal(r, s->func, key)) != NULL) {
+ rewritelog(r, 5, "map lookup OK: map=%s key=%s -> val=%s",
+ s->name, key, value);
+ return value;
+ }
+ else {
+ rewritelog(r, 5, "map lookup FAILED: map=%s key=%s",
+ s->name, key);
+ }
+ }
+ else if (s->type == MAPTYPE_RND) {
+ if (stat(s->checkfile, &st) == -1) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
+ "mod_rewrite: can't access text RewriteMap "
+ "file %s", s->checkfile);
+ rewritelog(r, 1, "can't open RewriteMap file, "
+ "see error log");
+ return NULL;
+ }
+ value = get_cache_string(cachep, s->name, CACHEMODE_TS,
+ st.st_mtime, key);
+ if (value == NULL) {
+ rewritelog(r, 6, "cache lookup FAILED, forcing new "
+ "map lookup");
+ if ((value =
+ lookup_map_txtfile(r, s->datafile, key)) != NULL) {
+ rewritelog(r, 5, "map lookup OK: map=%s key=%s[txt] "
+ "-> val=%s", s->name, key, value);
+ set_cache_string(cachep, s->name, CACHEMODE_TS,
+ st.st_mtime, key, value);
+ }
+ else {
+ rewritelog(r, 5, "map lookup FAILED: map=%s[txt] "
+ "key=%s", s->name, key);
+ set_cache_string(cachep, s->name, CACHEMODE_TS,
+ st.st_mtime, key, "");
+ return NULL;
+ }
+ }
+ else {
+ rewritelog(r, 5, "cache lookup OK: map=%s[txt] key=%s "
+ "-> val=%s", s->name, key, value);
+ }
+ if (value[0] != '\0') {
+ value = select_random_value_part(r, value);
+ rewritelog(r, 5, "randomly choosen the subvalue `%s'", value);
+ }
+ else {
+ value = NULL;
+ }
+ return value;
+ }
+ }
+ }
+ return NULL;
+}
+
+static char *lookup_map_txtfile(request_rec *r, char *file, char *key)
+{
+ FILE *fp = NULL;
+ char line[1024];
+ char *value = NULL;
+ char *cpT;
+ size_t skip;
+ char *curkey;
+ char *curval;
+
+ if ((fp = ap_pfopen(r->pool, file, "r")) == NULL) {
+ return NULL;
+ }
+
+ while (fgets(line, sizeof(line), fp) != NULL) {
+ if (line[0] == '#')
+ continue; /* ignore comments */
+ cpT = line;
+ curkey = cpT;
+ skip = strcspn(cpT," \t\r\n");
+ if (skip == 0)
+ continue; /* ignore lines that start with a space, tab, CR, or LF */
+ cpT += skip;
+ *cpT = '\0';
+ if (strcmp(curkey, key) != 0)
+ continue; /* key does not match... */
+
+ /* found a matching key; now extract and return the value */
+ ++cpT;
+ skip = strspn(cpT, " \t\r\n");
+ cpT += skip;
+ curval = cpT;
+ skip = strcspn(cpT, " \t\r\n");
+ if (skip == 0)
+ continue; /* no value... */
+ cpT += skip;
+ *cpT = '\0';
+ value = ap_pstrdup(r->pool, curval);
+ break;
+ }
+ ap_pfclose(r->pool, fp);
+ return value;
+}
+
+#ifndef NO_DBM_REWRITEMAP
+static char *lookup_map_dbmfile(request_rec *r, char *file, char *key)
+{
+ DBM *dbmfp = NULL;
+ datum dbmkey;
+ datum dbmval;
+ char *value = NULL;
+ char buf[MAX_STRING_LEN];
+
+ dbmkey.dptr = key;
+ dbmkey.dsize = strlen(key);
+ if ((dbmfp = dbm_open(file, O_RDONLY, 0666)) != NULL) {
+ dbmval = dbm_fetch(dbmfp, dbmkey);
+ if (dbmval.dptr != NULL) {
+ memcpy(buf, dbmval.dptr,
+ dbmval.dsize < sizeof(buf)-1 ?
+ dbmval.dsize : sizeof(buf)-1 );
+ buf[dbmval.dsize] = '\0';
+ value = ap_pstrdup(r->pool, buf);
+ }
+ dbm_close(dbmfp);
+ }
+ return value;
+}
+#endif
+
+static char *lookup_map_program(request_rec *r, int fpin, int fpout, char *key)
+{
+ char buf[LONG_STRING_LEN];
+ char c;
+ int i;
+#ifndef NO_WRITEV
+ struct iovec iov[2];
+#endif
+
+ /* when `RewriteEngine off' was used in the per-server
+ * context then the rewritemap-programs were not spawned.
+ * In this case using such a map (usually in per-dir context)
+ * is useless because it is not available.
+ */
+ if (fpin == -1 || fpout == -1) {
+ return NULL;
+ }
+
+ /* take the lock */
+ rewritelock_alloc(r);
+
+ /* write out the request key */
+#ifdef NO_WRITEV
+ write(fpin, key, strlen(key));
+ write(fpin, "\n", 1);
+#else
+ iov[0].iov_base = key;
+ iov[0].iov_len = strlen(key);
+ iov[1].iov_base = "\n";
+ iov[1].iov_len = 1;
+ writev(fpin, iov, 2);
+#endif
+
+ /* read in the response value */
+ i = 0;
+ while (read(fpout, &c, 1) == 1 && (i < LONG_STRING_LEN-1)) {
+ if (c == '\n') {
+ break;
+ }
+ buf[i++] = c;
+ }
+ buf[i] = '\0';
+
+ /* give the lock back */
+ rewritelock_free(r);
+
+ if (strcasecmp(buf, "NULL") == 0) {
+ return NULL;
+ }
+ else {
+ return ap_pstrdup(r->pool, buf);
+ }
+}
+
+static char *lookup_map_internal(request_rec *r,
+ char *(*func)(request_rec *, char *),
+ char *key)
+{
+ /* currently we just let the function convert
+ the key to a corresponding value */
+ return func(r, key);
+}
+
+static char *rewrite_mapfunc_toupper(request_rec *r, char *key)
+{
+ char *value, *cp;
+
+ for (cp = value = ap_pstrdup(r->pool, key); cp != NULL && *cp != '\0';
+ cp++) {
+ *cp = ap_toupper(*cp);
+ }
+ return value;
+}
+
+static char *rewrite_mapfunc_tolower(request_rec *r, char *key)
+{
+ char *value, *cp;
+
+ for (cp = value = ap_pstrdup(r->pool, key); cp != NULL && *cp != '\0';
+ cp++) {
+ *cp = ap_tolower(*cp);
+ }
+ return value;
+}
+
+static char *rewrite_mapfunc_escape(request_rec *r, char *key)
+{
+ char *value;
+
+ value = ap_escape_uri(r->pool, key);
+ return value;
+}
+
+static char *rewrite_mapfunc_unescape(request_rec *r, char *key)
+{
+ char *value;
+
+ value = ap_pstrdup(r->pool, key);
+ ap_unescape_url(value);
+ return value;
+}
+
+static int rewrite_rand_init_done = 0;
+
+static void rewrite_rand_init(void)
+{
+ if (!rewrite_rand_init_done) {
+ srand((unsigned)(getpid()));
+ rewrite_rand_init_done = 1;
+ }
+ return;
+}
+
+static int rewrite_rand(int l, int h)
+{
+ int i;
+ char buf[50];
+
+ rewrite_rand_init();
+ ap_snprintf(buf, sizeof(buf), "%.0f",
+ (((double)(rand()%RAND_MAX)/RAND_MAX)*(h-l)));
+ i = atoi(buf)+1;
+ if (i < l) i = l;
+ if (i > h) i = h;
+ return i;
+}
+
+static char *select_random_value_part(request_rec *r, char *value)
+{
+ char *buf;
+ int n, i, k;
+
+ /* count number of distinct values */
+ for (n = 1, i = 0; value[i] != '\0'; i++) {
+ if (value[i] == '|') {
+ n++;
+ }
+ }
+
+ /* when only one value we have no option to choose */
+ if (n == 1) {
+ return value;
+ }
+
+ /* else randomly select one */
+ k = rewrite_rand(1, n);
+
+ /* and grep it out */
+ for (n = 1, i = 0; value[i] != '\0'; i++) {
+ if (n == k) {
+ break;
+ }
+ if (value[i] == '|') {
+ n++;
+ }
+ }
+ buf = ap_pstrdup(r->pool, &value[i]);
+ for (i = 0; buf[i] != '\0' && buf[i] != '|'; i++)
+ ;
+ buf[i] = '\0';
+ return buf;
+}
+
+
+/*
+** +-------------------------------------------------------+
+** | |
+** | rewriting logfile support
+** | |
+** +-------------------------------------------------------+
+*/
+
+
+static void open_rewritelog(server_rec *s, pool *p)
+{
+ rewrite_server_conf *conf;
+ char *fname;
+ piped_log *pl;
+ int rewritelog_flags = ( O_WRONLY|O_APPEND|O_CREAT );
+#ifdef WIN32
+ mode_t rewritelog_mode = ( _S_IREAD|_S_IWRITE );
+#else
+ mode_t rewritelog_mode = ( S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH );
+#endif
+
+ conf = ap_get_module_config(s->module_config, &rewrite_module);
+
+ if (conf->rewritelogfile == NULL) {
+ return;
+ }
+ if (*(conf->rewritelogfile) == '\0') {
+ return;
+ }
+ if (conf->rewritelogfp > 0) {
+ return; /* virtual log shared w/ main server */
+ }
+
+ fname = ap_server_root_relative(p, conf->rewritelogfile);
+
+ if (*conf->rewritelogfile == '|') {
+ if ((pl = ap_open_piped_log(p, conf->rewritelogfile+1)) == NULL) {
+ ap_log_error(APLOG_MARK, APLOG_ERR, s,
+ "mod_rewrite: could not open reliable pipe "
+ "to RewriteLog filter %s", conf->rewritelogfile+1);
+ exit(1);
+ }
+ conf->rewritelogfp = ap_piped_log_write_fd(pl);
+ }
+ else if (*conf->rewritelogfile != '\0') {
+ if ((conf->rewritelogfp = ap_popenf(p, fname, rewritelog_flags,
+ rewritelog_mode)) < 0) {
+ ap_log_error(APLOG_MARK, APLOG_ERR, s,
+
+ "mod_rewrite: could not open RewriteLog "
+ "file %s", fname);
+ exit(1);
+ }
+ }
+ return;
+}
+
+static void rewritelog(request_rec *r, int level, const char *text, ...)
+{
+ rewrite_server_conf *conf;
+ conn_rec *conn;
+ char *str1;
+ char str2[512];
+ char str3[1024];
+ char type[20];
+ char redir[20];
+ va_list ap;
+ int i;
+ request_rec *req;
+ char *ruser;
+ const char *rhost;
+
+ va_start(ap, text);
+ conf = ap_get_module_config(r->server->module_config, &rewrite_module);
+ conn = r->connection;
+
+ if (conf->rewritelogfp < 0) {
+ return;
+ }
+ if (conf->rewritelogfile == NULL) {
+ return;
+ }
+ if (*(conf->rewritelogfile) == '\0') {
+ return;
+ }
+
+ if (level > conf->rewriteloglevel) {
+ return;
+ }
+
+ if (conn->user == NULL) {
+ ruser = "-";
+ }
+ else if (strlen(conn->user) != 0) {
+ ruser = conn->user;
+ }
+ else {
+ ruser = "\"\"";
+ }
+
+ rhost = ap_get_remote_host(conn, r->server->module_config,
+ REMOTE_NOLOOKUP);
+ if (rhost == NULL) {
+ rhost = "UNKNOWN-HOST";
+ }
+
+ str1 = ap_pstrcat(r->pool, rhost, " ",
+ (conn->remote_logname != NULL ?
+ conn->remote_logname : "-"), " ",
+ ruser, NULL);
+ ap_vsnprintf(str2, sizeof(str2), text, ap);
+
+ if (r->main == NULL) {
+ strcpy(type, "initial");
+ }
+ else {
+ strcpy(type, "subreq");
+ }
+
+ for (i = 0, req = r; req->prev != NULL; req = req->prev) {
+ i++;
+ }
+ if (i == 0) {
+ redir[0] = '\0';
+ }
+ else {
+ ap_snprintf(redir, sizeof(redir), "/redir#%d", i);
+ }
+
+ ap_snprintf(str3, sizeof(str3),
+ "%s %s [%s/sid#%lx][rid#%lx/%s%s] (%d) %s\n", str1,
+ current_logtime(r), ap_get_server_name(r),
+ (unsigned long)(r->server), (unsigned long)r,
+ type, redir, level, str2);
+
+ fd_lock(r, conf->rewritelogfp);
+ write(conf->rewritelogfp, str3, strlen(str3));
+ fd_unlock(r, conf->rewritelogfp);
+
+ va_end(ap);
+ return;
+}
+
+static char *current_logtime(request_rec *r)
+{
+ int timz;
+ struct tm *t;
+ char tstr[80];
+ char sign;
+
+ t = ap_get_gmtoff(&timz);
+ sign = (timz < 0 ? '-' : '+');
+ if (timz < 0) {
+ timz = -timz;
+ }
+
+ strftime(tstr, 80, "[%d/%b/%Y:%H:%M:%S ", t);
+ ap_snprintf(tstr + strlen(tstr), 80-strlen(tstr), "%c%.2d%.2d]",
+ sign, timz/60, timz%60);
+ return ap_pstrdup(r->pool, tstr);
+}
+
+
+
+
+/*
+** +-------------------------------------------------------+
+** | |
+** | rewriting lockfile support
+** | |
+** +-------------------------------------------------------+
+*/
+
+#ifdef WIN32
+#define REWRITELOCK_MODE ( _S_IREAD|_S_IWRITE )
+#else
+#define REWRITELOCK_MODE ( S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH )
+#endif
+
+static void rewritelock_create(server_rec *s, pool *p)
+{
+ rewrite_server_conf *conf;
+
+ conf = ap_get_module_config(s->module_config, &rewrite_module);
+
+ /* only operate if a lockfile is used */
+ if (lockname == NULL || *(lockname) == '\0') {
+ return;
+ }
+
+ /* fixup the path, especially for rewritelock_remove() */
+ lockname = ap_server_root_relative(p, lockname);
+
+ /* create the lockfile */
+ unlink(lockname);
+ if ((lockfd = ap_popenf(p, lockname, O_WRONLY|O_CREAT,
+ REWRITELOCK_MODE)) < 0) {
+ ap_log_error(APLOG_MARK, APLOG_ERR, s,
+ "mod_rewrite: Parent could not create RewriteLock "
+ "file %s", lockname);
+ exit(1);
+ }
+#if !defined(OS2) && !defined(WIN32)
+ /* make sure the childs have access to this file */
+ if (geteuid() == 0 /* is superuser */)
+ chown(lockname, ap_user_id, -1 /* no gid change */);
+#endif
+
+ return;
+}
+
+static void rewritelock_open(server_rec *s, pool *p)
+{
+ rewrite_server_conf *conf;
+
+ conf = ap_get_module_config(s->module_config, &rewrite_module);
+
+ /* only operate if a lockfile is used */
+ if (lockname == NULL || *(lockname) == '\0') {
+ return;
+ }
+
+ /* open the lockfile (once per child) to get a unique fd */
+ if ((lockfd = ap_popenf(p, lockname, O_WRONLY,
+ REWRITELOCK_MODE)) < 0) {
+ ap_log_error(APLOG_MARK, APLOG_ERR, s,
+ "mod_rewrite: Child could not open RewriteLock "
+ "file %s", lockname);
+ exit(1);
+ }
+ return;
+}
+
+static void rewritelock_remove(void *data)
+{
+ /* only operate if a lockfile is used */
+ if (lockname == NULL || *(lockname) == '\0') {
+ return;
+ }
+
+ /* remove the lockfile */
+ unlink(lockname);
+ lockname = NULL;
+ lockfd = -1;
+}
+
+static void rewritelock_alloc(request_rec *r)
+{
+ if (lockfd != -1) {
+ fd_lock(r, lockfd);
+ }
+ return;
+}
+
+static void rewritelock_free(request_rec *r)
+{
+ if (lockfd != -1) {
+ fd_unlock(r, lockfd);
+ }
+ return;
+}
+
+
+/*
+** +-------------------------------------------------------+
+** | |
+** | program map support
+** | |
+** +-------------------------------------------------------+
+*/
+
+static void run_rewritemap_programs(server_rec *s, pool *p)
+{
+ rewrite_server_conf *conf;
+ FILE *fpin;
+ FILE *fpout;
+ FILE *fperr;
+ array_header *rewritemaps;
+ rewritemap_entry *entries;
+ rewritemap_entry *map;
+ int i;
+ int rc;
+
+ conf = ap_get_module_config(s->module_config, &rewrite_module);
+
+ /* If the engine isn't turned on,
+ * don't even try to do anything.
+ */
+ if (conf->state == ENGINE_DISABLED) {
+ return;
+ }
+
+ rewritemaps = conf->rewritemaps;
+ entries = (rewritemap_entry *)rewritemaps->elts;
+ for (i = 0; i < rewritemaps->nelts; i++) {
+ map = &entries[i];
+ if (map->type != MAPTYPE_PRG) {
+ continue;
+ }
+ if (map->datafile == NULL
+ || *(map->datafile) == '\0'
+ || map->fpin != -1
+ || map->fpout != -1 ) {
+ continue;
+ }
+ fpin = NULL;
+ fpout = NULL;
+ rc = ap_spawn_child(p, rewritemap_program_child,
+ (void *)map->datafile, kill_after_timeout,
+ &fpin, &fpout, &fperr);
+ if (rc == 0 || fpin == NULL || fpout == NULL) {
+ ap_log_error(APLOG_MARK, APLOG_ERR, s,
+ "mod_rewrite: could not fork child for "
+ "RewriteMap process");
+ exit(1);
+ }
+ map->fpin = fileno(fpin);
+ map->fpout = fileno(fpout);
+ map->fperr = fileno(fperr);
+ }
+ return;
+}
+
+/* child process code */
+static int rewritemap_program_child(void *cmd, child_info *pinfo)
+{
+ int child_pid = 1;
+
+ /*
+ * Prepare for exec
+ */
+ ap_cleanup_for_exec();
+#ifdef SIGHUP
+ signal(SIGHUP, SIG_IGN);
+#endif
+
+ /*
+ * Exec() the child program
+ */
+#if defined(WIN32)
+ /* MS Windows */
+ {
+ char pCommand[MAX_STRING_LEN];
+ STARTUPINFO si;
+ PROCESS_INFORMATION pi;
+
+ ap_snprintf(pCommand, sizeof(pCommand), "%s /C %s", SHELL_PATH, cmd);
+
+ memset(&si, 0, sizeof(si));
+ memset(&pi, 0, sizeof(pi));
+
+ si.cb = sizeof(si);
+ si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
+ si.wShowWindow = SW_HIDE;
+ si.hStdInput = pinfo->hPipeInputRead;
+ si.hStdOutput = pinfo->hPipeOutputWrite;
+ si.hStdError = pinfo->hPipeErrorWrite;
+
+ if (CreateProcess(NULL, pCommand, NULL, NULL, TRUE, 0,
+ environ, NULL, &si, &pi)) {
+ CloseHandle(pi.hProcess);
+ CloseHandle(pi.hThread);
+ child_pid = pi.dwProcessId;
+ }
+ }
+#elif defined(OS2)
+ /* IBM OS/2 */
+ execl(SHELL_PATH, SHELL_PATH, "/c", (char *)cmd, NULL);
+#else
+ /* Standard Unix */
+ execl(SHELL_PATH, SHELL_PATH, "-c", (char *)cmd, NULL);
+#endif
+ return(child_pid);
+}
+
+
+
+
+/*
+** +-------------------------------------------------------+
+** | |
+** | environment variable support
+** | |
+** +-------------------------------------------------------+
+*/
+
+
+static void expand_variables_inbuffer(request_rec *r, char *buf, int buf_len)
+{
+ char *newbuf;
+ newbuf = expand_variables(r, buf);
+ if (strcmp(newbuf, buf) != 0) {
+ ap_cpystrn(buf, newbuf, buf_len);
+ }
+ return;
+}
+
+static char *expand_variables(request_rec *r, char *str)
+{
+ char output[MAX_STRING_LEN];
+ char input[MAX_STRING_LEN];
+ char *cp;
+ char *cp2;
+ char *cp3;
+ int expanded;
+ char *outp;
+ char *endp;
+
+ ap_cpystrn(input, str, sizeof(input));
+ output[0] = '\0';
+ outp = output;
+ endp = output + sizeof(output);
+ expanded = 0;
+ for (cp = input; cp < input+MAX_STRING_LEN; ) {
+ if ((cp2 = strstr(cp, "%{")) != NULL) {
+ if ((cp3 = strstr(cp2, "}")) != NULL) {
+ *cp2 = '\0';
+ outp = ap_cpystrn(outp, cp, endp - outp);
+
+ cp2 += 2;
+ *cp3 = '\0';
+ outp = ap_cpystrn(outp, lookup_variable(r, cp2), endp - outp);
+
+ cp = cp3+1;
+ expanded = 1;
+ continue;
+ }
+ }
+ outp = ap_cpystrn(outp, cp, endp - outp);
+ break;
+ }
+ return expanded ? ap_pstrdup(r->pool, output) : str;
+}
+
+static char *lookup_variable(request_rec *r, char *var)
+{
+ const char *result;
+ char resultbuf[LONG_STRING_LEN];
+ time_t tc;
+ struct tm *tm;
+ request_rec *rsub;
+#ifndef WIN32
+ struct passwd *pw;
+ struct group *gr;
+ struct stat finfo;
+#endif
+
+ result = NULL;
+
+ /* HTTP headers */
+ if (strcasecmp(var, "HTTP_USER_AGENT") == 0) {
+ result = lookup_header(r, "User-Agent");
+ }
+ else if (strcasecmp(var, "HTTP_REFERER") == 0) {
+ result = lookup_header(r, "Referer");
+ }
+ else if (strcasecmp(var, "HTTP_COOKIE") == 0) {
+ result = lookup_header(r, "Cookie");
+ }
+ else if (strcasecmp(var, "HTTP_FORWARDED") == 0) {
+ result = lookup_header(r, "Forwarded");
+ }
+ else if (strcasecmp(var, "HTTP_HOST") == 0) {
+ result = lookup_header(r, "Host");
+ }
+ else if (strcasecmp(var, "HTTP_PROXY_CONNECTION") == 0) {
+ result = lookup_header(r, "Proxy-Connection");
+ }
+ else if (strcasecmp(var, "HTTP_ACCEPT") == 0) {
+ result = lookup_header(r, "Accept");
+ }
+ /* all other headers from which we are still not know about */
+ else if (strlen(var) > 5 && strncasecmp(var, "HTTP:", 5) == 0) {
+ result = lookup_header(r, var+5);
+ }
+
+ /* connection stuff */
+ else if (strcasecmp(var, "REMOTE_ADDR") == 0) {
+ result = r->connection->remote_ip;
+ }
+ else if (strcasecmp(var, "REMOTE_HOST") == 0) {
+ result = (char *)ap_get_remote_host(r->connection,
+ r->per_dir_config, REMOTE_NAME);
+ }
+ else if (strcasecmp(var, "REMOTE_USER") == 0) {
+ result = r->connection->user;
+ }
+ else if (strcasecmp(var, "REMOTE_IDENT") == 0) {
+ result = (char *)ap_get_remote_logname(r);
+ }
+
+ /* request stuff */
+ else if (strcasecmp(var, "THE_REQUEST") == 0) { /* non-standard */
+ result = r->the_request;
+ }
+ else if (strcasecmp(var, "REQUEST_METHOD") == 0) {
+ result = r->method;
+ }
+ else if (strcasecmp(var, "REQUEST_URI") == 0) { /* non-standard */
+ result = r->uri;
+ }
+ else if (strcasecmp(var, "SCRIPT_FILENAME") == 0 ||
+ strcasecmp(var, "REQUEST_FILENAME") == 0 ) {
+ result = r->filename;
+ }
+ else if (strcasecmp(var, "PATH_INFO") == 0) {
+ result = r->path_info;
+ }
+ else if (strcasecmp(var, "QUERY_STRING") == 0) {
+ result = r->args;
+ }
+ else if (strcasecmp(var, "AUTH_TYPE") == 0) {
+ result = r->connection->ap_auth_type;
+ }
+ else if (strcasecmp(var, "IS_SUBREQ") == 0) { /* non-standard */
+ result = (r->main != NULL ? "true" : "false");
+ }
+
+ /* internal server stuff */
+ else if (strcasecmp(var, "DOCUMENT_ROOT") == 0) {
+ result = ap_document_root(r);
+ }
+ else if (strcasecmp(var, "SERVER_ADMIN") == 0) {
+ result = r->server->server_admin;
+ }
+ else if (strcasecmp(var, "SERVER_NAME") == 0) {
+ result = ap_get_server_name(r);
+ }
+ else if (strcasecmp(var, "SERVER_ADDR") == 0) { /* non-standard */
+ result = r->connection->local_ip;
+ }
+ else if (strcasecmp(var, "SERVER_PORT") == 0) {
+ ap_snprintf(resultbuf, sizeof(resultbuf), "%u", ap_get_server_port(r));
+ result = resultbuf;
+ }
+ else if (strcasecmp(var, "SERVER_PROTOCOL") == 0) {
+ result = r->protocol;
+ }
+ else if (strcasecmp(var, "SERVER_SOFTWARE") == 0) {
+ result = ap_get_server_version();
+ }
+ else if (strcasecmp(var, "API_VERSION") == 0) { /* non-standard */
+ ap_snprintf(resultbuf, sizeof(resultbuf), "%d:%d",
+ MODULE_MAGIC_NUMBER_MAJOR, MODULE_MAGIC_NUMBER_MINOR);
+ result = resultbuf;
+ }
+
+ /* underlaying Unix system stuff */
+ else if (strcasecmp(var, "TIME_YEAR") == 0) {
+ tc = time(NULL);
+ tm = localtime(&tc);
+ ap_snprintf(resultbuf, sizeof(resultbuf), "%02d%02d",
+ (tm->tm_year / 100) + 19, tm->tm_year % 100);
+ result = resultbuf;
+ }
+#define MKTIMESTR(format, tmfield) \
+ tc = time(NULL); \
+ tm = localtime(&tc); \
+ ap_snprintf(resultbuf, sizeof(resultbuf), format, tm->tmfield); \
+ result = resultbuf;
+ else if (strcasecmp(var, "TIME_MON") == 0) {
+ MKTIMESTR("%02d", tm_mon+1)
+ }
+ else if (strcasecmp(var, "TIME_DAY") == 0) {
+ MKTIMESTR("%02d", tm_mday)
+ }
+ else if (strcasecmp(var, "TIME_HOUR") == 0) {
+ MKTIMESTR("%02d", tm_hour)
+ }
+ else if (strcasecmp(var, "TIME_MIN") == 0) {
+ MKTIMESTR("%02d", tm_min)
+ }
+ else if (strcasecmp(var, "TIME_SEC") == 0) {
+ MKTIMESTR("%02d", tm_sec)
+ }
+ else if (strcasecmp(var, "TIME_WDAY") == 0) {
+ MKTIMESTR("%d", tm_wday)
+ }
+ else if (strcasecmp(var, "TIME") == 0) {
+ tc = time(NULL);
+ tm = localtime(&tc);
+ ap_snprintf(resultbuf, sizeof(resultbuf),
+ "%02d%02d%02d%02d%02d%02d%02d", (tm->tm_year / 100) + 19,
+ (tm->tm_year % 100), tm->tm_mon+1, tm->tm_mday,
+ tm->tm_hour, tm->tm_min, tm->tm_sec);
+ result = resultbuf;
+ rewritelog(r, 1, "RESULT='%s'", result);
+ }
+
+ /* all other env-variables from the parent Apache process */
+ else if (strlen(var) > 4 && strncasecmp(var, "ENV:", 4) == 0) {
+ /* first try the internal Apache notes structure */
+ result = ap_table_get(r->notes, var+4);
+ /* second try the internal Apache env structure */
+ if (result == NULL) {
+ result = ap_table_get(r->subprocess_env, var+4);
+ }
+ /* third try the external OS env */
+ if (result == NULL) {
+ result = getenv(var+4);
+ }
+ }
+
+#define LOOKAHEAD(subrecfunc) \
+ if ( \
+ /* filename is safe to use */ \
+ r->filename != NULL \
+ /* - and we're either not in a subrequest */ \
+ && ( r->main == NULL \
+ /* - or in a subrequest where paths are non-NULL... */ \
+ || ( r->main->uri != NULL && r->uri != NULL \
+ /* ...and sub and main paths differ */ \
+ && strcmp(r->main->uri, r->uri) != 0))) { \
+ /* process a file-based subrequest */ \
+ rsub = subrecfunc(r->filename, r); \
+ /* now recursively lookup the variable in the sub_req */ \
+ result = lookup_variable(rsub, var+5); \
+ /* copy it up to our scope before we destroy sub_req's pool */ \
+ result = ap_pstrdup(r->pool, result); \
+ /* cleanup by destroying the subrequest */ \
+ ap_destroy_sub_req(rsub); \
+ /* log it */ \
+ rewritelog(r, 5, "lookahead: path=%s var=%s -> val=%s", \
+ r->filename, var+5, result); \
+ /* return ourself to prevent re-pstrdup */ \
+ return (char *)result; \
+ }
+
+ /* look-ahead for parameter through URI-based sub-request */
+ else if (strlen(var) > 5 && strncasecmp(var, "LA-U:", 5) == 0) {
+ LOOKAHEAD(ap_sub_req_lookup_uri)
+ }
+ /* look-ahead for parameter through file-based sub-request */
+ else if (strlen(var) > 5 && strncasecmp(var, "LA-F:", 5) == 0) {
+ LOOKAHEAD(ap_sub_req_lookup_file)
+ }
+
+#ifndef WIN32
+ /* Win32 has a rather different view of file ownerships.
+ For now, just forget it */
+
+ /* file stuff */
+ else if (strcasecmp(var, "SCRIPT_USER") == 0) {
+ result = "";
+ if (r->finfo.st_mode != 0) {
+ if ((pw = getpwuid(r->finfo.st_uid)) != NULL) {
+ result = pw->pw_name;
+ }
+ }
+ else {
+ if (stat(r->filename, &finfo) == 0) {
+ if ((pw = getpwuid(finfo.st_uid)) != NULL) {
+ result = pw->pw_name;
+ }
+ }
+ }
+ }
+ else if (strcasecmp(var, "SCRIPT_GROUP") == 0) {
+ result = "";
+ if (r->finfo.st_mode != 0) {
+ if ((gr = getgrgid(r->finfo.st_gid)) != NULL) {
+ result = gr->gr_name;
+ }
+ }
+ else {
+ if (stat(r->filename, &finfo) == 0) {
+ if ((gr = getgrgid(finfo.st_gid)) != NULL) {
+ result = gr->gr_name;
+ }
+ }
+ }
+ }
+#endif /* ndef WIN32 */
+
+ if (result == NULL) {
+ return ap_pstrdup(r->pool, "");
+ }
+ else {
+ return ap_pstrdup(r->pool, result);
+ }
+}
+
+static char *lookup_header(request_rec *r, const char *name)
+{
+ array_header *hdrs_arr;
+ table_entry *hdrs;
+ int i;
+
+ hdrs_arr = ap_table_elts(r->headers_in);
+ hdrs = (table_entry *)hdrs_arr->elts;
+ for (i = 0; i < hdrs_arr->nelts; ++i) {
+ if (hdrs[i].key == NULL) {
+ continue;
+ }
+ if (strcasecmp(hdrs[i].key, name) == 0) {
+ ap_table_merge(r->notes, VARY_KEY_THIS, name);
+ return hdrs[i].val;
+ }
+ }
+ return NULL;
+}
+
+
+
+
+/*
+** +-------------------------------------------------------+
+** | |
+** | caching support
+** | |
+** +-------------------------------------------------------+
+*/
+
+
+static cache *init_cache(pool *p)
+{
+ cache *c;
+
+ c = (cache *)ap_palloc(p, sizeof(cache));
+ c->pool = ap_make_sub_pool(p);
+ c->lists = ap_make_array(c->pool, 2, sizeof(cachelist));
+ return c;
+}
+
+static void set_cache_string(cache *c, char *res, int mode, time_t t,
+ char *key, char *value)
+{
+ cacheentry ce;
+
+ ce.time = t;
+ ce.key = key;
+ ce.value = value;
+ store_cache_string(c, res, &ce);
+ return;
+}
+
+static char *get_cache_string(cache *c, char *res, int mode,
+ time_t t, char *key)
+{
+ cacheentry *ce;
+
+ ce = retrieve_cache_string(c, res, key);
+ if (ce == NULL) {
+ return NULL;
+ }
+ if (mode & CACHEMODE_TS) {
+ if (t != ce->time) {
+ return NULL;
+ }
+ }
+ else if (mode & CACHEMODE_TTL) {
+ if (t > ce->time) {
+ return NULL;
+ }
+ }
+ return ap_pstrdup(c->pool, ce->value);
+}
+
+static int cache_tlb_hash(char *key)
+{
+ unsigned long n;
+ char *p;
+
+ n = 0;
+ for (p=key; *p != '\0'; ++p) {
+ n = n * 53711 + 134561 + (unsigned)(*p & 0xff);
+ }
+
+ return n % CACHE_TLB_ROWS;
+}
+
+static cacheentry *cache_tlb_lookup(cachetlbentry *tlb, cacheentry *elt,
+ char *key)
+{
+ int ix = cache_tlb_hash(key);
+ int i;
+ int j;
+
+ for (i=0; i < CACHE_TLB_COLS; ++i) {
+ j = tlb[ix].t[i];
+ if (j < 0)
+ return NULL;
+ if (strcmp(elt[j].key, key) == 0)
+ return &elt[j];
+ }
+ return NULL;
+}
+
+static void cache_tlb_replace(cachetlbentry *tlb, cacheentry *elt,
+ cacheentry *e)
+{
+ int ix = cache_tlb_hash(e->key);
+ int i;
+
+ tlb = &tlb[ix];
+
+ for (i=1; i < CACHE_TLB_COLS; ++i)
+ tlb->t[i] = tlb->t[i-1];
+
+ tlb->t[0] = e - elt;
+}
+
+static void store_cache_string(cache *c, char *res, cacheentry *ce)
+{
+ int i;
+ int j;
+ cachelist *l;
+ cacheentry *e;
+ cachetlbentry *t;
+ int found_list;
+
+ found_list = 0;
+ /* first try to edit an existing entry */
+ for (i = 0; i < c->lists->nelts; i++) {
+ l = &(((cachelist *)c->lists->elts)[i]);
+ if (strcmp(l->resource, res) == 0) {
+ found_list = 1;
+
+ e = cache_tlb_lookup((cachetlbentry *)l->tlb->elts,
+ (cacheentry *)l->entries->elts, ce->key);
+ if (e != NULL) {
+ e->time = ce->time;
+ e->value = ap_pstrdup(c->pool, ce->value);
+ return;
+ }
+
+ for (j = 0; j < l->entries->nelts; j++) {
+ e = &(((cacheentry *)l->entries->elts)[j]);
+ if (strcmp(e->key, ce->key) == 0) {
+ e->time = ce->time;
+ e->value = ap_pstrdup(c->pool, ce->value);
+ cache_tlb_replace((cachetlbentry *)l->tlb->elts,
+ (cacheentry *)l->entries->elts, e);
+ return;
+ }
+ }
+ }
+ }
+
+ /* create a needed new list */
+ if (!found_list) {
+ l = ap_push_array(c->lists);
+ l->resource = ap_pstrdup(c->pool, res);
+ l->entries = ap_make_array(c->pool, 2, sizeof(cacheentry));
+ l->tlb = ap_make_array(c->pool, CACHE_TLB_ROWS,
+ sizeof(cachetlbentry));
+ for (i=0; itlb->elts)[i];
+ for (j=0; jt[j] = -1;
+ }
+ }
+
+ /* create the new entry */
+ for (i = 0; i < c->lists->nelts; i++) {
+ l = &(((cachelist *)c->lists->elts)[i]);
+ if (strcmp(l->resource, res) == 0) {
+ e = ap_push_array(l->entries);
+ e->time = ce->time;
+ e->key = ap_pstrdup(c->pool, ce->key);
+ e->value = ap_pstrdup(c->pool, ce->value);
+ cache_tlb_replace((cachetlbentry *)l->tlb->elts,
+ (cacheentry *)l->entries->elts, e);
+ return;
+ }
+ }
+
+ /* not reached, but when it is no problem... */
+ return;
+}
+
+static cacheentry *retrieve_cache_string(cache *c, char *res, char *key)
+{
+ int i;
+ int j;
+ cachelist *l;
+ cacheentry *e;
+
+ for (i = 0; i < c->lists->nelts; i++) {
+ l = &(((cachelist *)c->lists->elts)[i]);
+ if (strcmp(l->resource, res) == 0) {
+
+ e = cache_tlb_lookup((cachetlbentry *)l->tlb->elts,
+ (cacheentry *)l->entries->elts, key);
+ if (e != NULL)
+ return e;
+
+ for (j = 0; j < l->entries->nelts; j++) {
+ e = &(((cacheentry *)l->entries->elts)[j]);
+ if (strcmp(e->key, key) == 0) {
+ return e;
+ }
+ }
+ }
+ }
+ return NULL;
+}
+
+
+
+
+/*
+** +-------------------------------------------------------+
+** | |
+** | misc functions
+** | |
+** +-------------------------------------------------------+
+*/
+
+static char *subst_prefix_path(request_rec *r, char *input, char *match,
+ char *subst)
+{
+ char matchbuf[LONG_STRING_LEN];
+ char substbuf[LONG_STRING_LEN];
+ char *output;
+ int l;
+
+ output = input;
+
+ /* first create a match string which always has a trailing slash */
+ l = ap_cpystrn(matchbuf, match, sizeof(matchbuf)) - matchbuf;
+ if (matchbuf[l-1] != '/') {
+ matchbuf[l] = '/';
+ matchbuf[l+1] = '\0';
+ l++;
+ }
+ /* now compare the prefix */
+ if (strncmp(input, matchbuf, l) == 0) {
+ rewritelog(r, 5, "strip matching prefix: %s -> %s", output, output+l);
+ output = ap_pstrdup(r->pool, output+l);
+
+ /* and now add the base-URL as replacement prefix */
+ l = ap_cpystrn(substbuf, subst, sizeof(substbuf)) - substbuf;
+ if (substbuf[l-1] != '/') {
+ substbuf[l] = '/';
+ substbuf[l+1] = '\0';
+ l++;
+ }
+ if (output[0] == '/') {
+ rewritelog(r, 4, "add subst prefix: %s -> %s%s",
+ output, substbuf, output+1);
+ output = ap_pstrcat(r->pool, substbuf, output+1, NULL);
+ }
+ else {
+ rewritelog(r, 4, "add subst prefix: %s -> %s%s",
+ output, substbuf, output);
+ output = ap_pstrcat(r->pool, substbuf, output, NULL);
+ }
+ }
+ return output;
+}
+
+
+/*
+**
+** own command line parser which don't have the '\\' problem
+**
+*/
+
+static int parseargline(char *str, char **a1, char **a2, char **a3)
+{
+ char *cp;
+ int isquoted;
+
+#define SKIP_WHITESPACE(cp) \
+ for ( ; *cp == ' ' || *cp == '\t'; ) { \
+ cp++; \
+ };
+
+#define CHECK_QUOTATION(cp,isquoted) \
+ isquoted = 0; \
+ if (*cp == '"') { \
+ isquoted = 1; \
+ cp++; \
+ }
+
+#define DETERMINE_NEXTSTRING(cp,isquoted) \
+ for ( ; *cp != '\0'; cp++) { \
+ if ( (isquoted && (*cp == ' ' || *cp == '\t')) \
+ || (*cp == '\\' && (*(cp+1) == ' ' || *(cp+1) == '\t'))) { \
+ cp++; \
+ continue; \
+ } \
+ if ( (!isquoted && (*cp == ' ' || *cp == '\t')) \
+ || (isquoted && *cp == '"') ) { \
+ break; \
+ } \
+ }
+
+ cp = str;
+ SKIP_WHITESPACE(cp);
+
+ /* determine first argument */
+ CHECK_QUOTATION(cp, isquoted);
+ *a1 = cp;
+ DETERMINE_NEXTSTRING(cp, isquoted);
+ if (*cp == '\0') {
+ return 1;
+ }
+ *cp++ = '\0';
+
+ SKIP_WHITESPACE(cp);
+
+ /* determine second argument */
+ CHECK_QUOTATION(cp, isquoted);
+ *a2 = cp;
+ DETERMINE_NEXTSTRING(cp, isquoted);
+ if (*cp == '\0') {
+ *cp++ = '\0';
+ *a3 = NULL;
+ return 0;
+ }
+ *cp++ = '\0';
+
+ SKIP_WHITESPACE(cp);
+
+ /* again check if there are only two arguments */
+ if (*cp == '\0') {
+ *cp++ = '\0';
+ *a3 = NULL;
+ return 0;
+ }
+
+ /* determine second argument */
+ CHECK_QUOTATION(cp, isquoted);
+ *a3 = cp;
+ DETERMINE_NEXTSTRING(cp, isquoted);
+ *cp++ = '\0';
+
+ return 0;
+}
+
+
+static void add_env_variable(request_rec *r, char *s)
+{
+ char var[MAX_STRING_LEN];
+ char val[MAX_STRING_LEN];
+ char *cp;
+ int n;
+
+ if ((cp = strchr(s, ':')) != NULL) {
+ n = ((cp-s) > MAX_STRING_LEN-1 ? MAX_STRING_LEN-1 : (cp-s));
+ memcpy(var, s, n);
+ var[n] = '\0';
+ ap_cpystrn(val, cp+1, sizeof(val));
+ ap_table_set(r->subprocess_env, var, val);
+ rewritelog(r, 5, "setting env variable '%s' to '%s'", var, val);
+ }
+}
+
+
+
+/*
+**
+** stat() for only the prefix of a path
+**
+*/
+
+static int prefix_stat(const char *path, struct stat *sb)
+{
+ char curpath[LONG_STRING_LEN];
+ char *cp;
+
+ ap_cpystrn(curpath, path, sizeof(curpath));
+ if (curpath[0] != '/') {
+ return 0;
+ }
+ if ((cp = strchr(curpath+1, '/')) != NULL) {
+ *cp = '\0';
+ }
+ if (stat(curpath, sb) == 0) {
+ return 1;
+ }
+ else {
+ return 0;
+ }
+}
+
+
+/*
+**
+** File locking
+**
+*/
+
+#ifdef USE_FCNTL
+static struct flock lock_it;
+static struct flock unlock_it;
+#endif
+
+static void fd_lock(request_rec *r, int fd)
+{
+ int rc;
+
+#ifdef USE_FCNTL
+ lock_it.l_whence = SEEK_SET; /* from current point */
+ lock_it.l_start = 0; /* -"- */
+ lock_it.l_len = 0; /* until end of file */
+ lock_it.l_type = F_WRLCK; /* set exclusive/write lock */
+ lock_it.l_pid = 0; /* pid not actually interesting */
+
+ while ( ((rc = fcntl(fd, F_SETLKW, &lock_it)) < 0)
+ && (errno == EINTR) ) {
+ continue;
+ }
+#endif
+#ifdef USE_FLOCK
+ while ( ((rc = flock(fd, LOCK_EX)) < 0)
+ && (errno == EINTR) ) {
+ continue;
+ }
+#endif
+#ifdef USE_LOCKING
+ /* Lock the first byte, always, assume we want to append
+ and seek to the end afterwards */
+ lseek(fd, 0, SEEK_SET);
+ rc = _locking(fd, _LK_LOCK, 1);
+ lseek(fd, 0, SEEK_END);
+#endif
+
+ if (rc < 0) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
+ "mod_rewrite: failed to lock file descriptor");
+ exit(1);
+ }
+ return;
+}
+
+static void fd_unlock(request_rec *r, int fd)
+{
+ int rc;
+
+#ifdef USE_FCNTL
+ unlock_it.l_whence = SEEK_SET; /* from current point */
+ unlock_it.l_start = 0; /* -"- */
+ unlock_it.l_len = 0; /* until end of file */
+ unlock_it.l_type = F_UNLCK; /* unlock */
+ unlock_it.l_pid = 0; /* pid not actually interesting */
+
+ rc = fcntl(fd, F_SETLKW, &unlock_it);
+#endif
+#ifdef USE_FLOCK
+ rc = flock(fd, LOCK_UN);
+#endif
+#ifdef USE_LOCKING
+ lseek(fd, 0, SEEK_SET);
+ rc = _locking(fd, _LK_UNLCK, 1);
+ lseek(fd, 0, SEEK_END);
+#endif
+
+ if (rc < 0) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
+ "mod_rewrite: failed to unlock file descriptor");
+ exit(1);
+ }
+}
+
+/*
+**
+** Lexicographic Compare
+**
+*/
+
+static int compare_lexicography(char *cpNum1, char *cpNum2)
+{
+ int i;
+ int n1, n2;
+
+ n1 = strlen(cpNum1);
+ n2 = strlen(cpNum2);
+ if (n1 > n2) {
+ return 1;
+ }
+ if (n1 < n2) {
+ return -1;
+ }
+ for (i = 0; i < n1; i++) {
+ if (cpNum1[i] > cpNum2[i]) {
+ return 1;
+ }
+ if (cpNum1[i] < cpNum2[i]) {
+ return -1;
+ }
+ }
+ return 0;
+}
+
+
+/*EOF*/
diff --git a/modules/mappers/mod_rewrite.dsp b/modules/mappers/mod_rewrite.dsp
new file mode 100644
index 00000000000..4a0ffd1bf68
--- /dev/null
+++ b/modules/mappers/mod_rewrite.dsp
@@ -0,0 +1,117 @@
+# Microsoft Developer Studio Project File - Name="ApacheModuleRewrite" - Package Owner=<4>
+# Microsoft Developer Studio Generated Build File, Format Version 5.00
+# ** DO NOT EDIT **
+
+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102
+
+CFG=ApacheModuleRewrite - Win32 Release
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,
+!MESSAGE use the Export Makefile command and run
+!MESSAGE
+!MESSAGE NMAKE /f "ApacheModuleRewrite.mak".
+!MESSAGE
+!MESSAGE You can specify a configuration when running NMAKE
+!MESSAGE by defining the macro CFG on the command line. For example:
+!MESSAGE
+!MESSAGE NMAKE /f "ApacheModuleRewrite.mak"\
+ CFG="ApacheModuleRewrite - Win32 Release"
+!MESSAGE
+!MESSAGE Possible choices for configuration are:
+!MESSAGE
+!MESSAGE "ApacheModuleRewrite - Win32 Release" (based on\
+ "Win32 (x86) Dynamic-Link Library")
+!MESSAGE "ApacheModuleRewrite - Win32 Debug" (based on\
+ "Win32 (x86) Dynamic-Link Library")
+!MESSAGE
+
+# Begin Project
+# PROP Scc_ProjName ""
+# PROP Scc_LocalPath ""
+CPP=cl.exe
+MTL=midl.exe
+RSC=rc.exe
+
+!IF "$(CFG)" == "ApacheModuleRewrite - Win32 Release"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir ".\Release"
+# PROP BASE Intermediate_Dir ".\Release"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir ".\ApacheModuleRewriteR"
+# PROP Intermediate_Dir ".\ApacheModuleRewriteR"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /c
+# ADD CPP /nologo /MD /W3 /GX /O2 /I "..\..\include" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "NO_DBM_REWRITEMAP" /D "SHARED_MODULE" /D "WIN32_LEAN_AND_MEAN" /YX /FD /c
+# ADD BASE MTL /nologo /D "NDEBUG" /win32
+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
+# ADD BASE RSC /l 0x809 /d "NDEBUG"
+# ADD RSC /l 0x809 /d "NDEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /machine:I386
+# ADD LINK32 ..\..\CoreR\ApacheCore.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ws2_32.lib /nologo /subsystem:windows /dll /machine:I386
+
+!ELSEIF "$(CFG)" == "ApacheModuleRewrite - Win32 Debug"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 1
+# PROP BASE Output_Dir ".\Debug"
+# PROP BASE Intermediate_Dir ".\Debug"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 1
+# PROP Output_Dir ".\ApacheModuleRewriteD"
+# PROP Intermediate_Dir ".\ApacheModuleRewriteD"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /c
+# ADD CPP /nologo /MDd /W3 /Gm /GX /Zi /Od /I "..\..\include" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "NO_DBM_REWRITEMAP" /D "SHARED_MODULE" /D "WIN32_LEAN_AND_MEAN" /YX /FD /c
+# ADD BASE MTL /nologo /D "_DEBUG" /win32
+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
+# ADD BASE RSC /l 0x809 /d "_DEBUG"
+# ADD RSC /l 0x809 /d "_DEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /debug /machine:I386
+# ADD LINK32 ..\..\CoreD\ApacheCore.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ws2_32.lib /nologo /subsystem:windows /dll /debug /machine:I386
+
+!ENDIF
+
+# Begin Target
+
+# Name "ApacheModuleRewrite - Win32 Release"
+# Name "ApacheModuleRewrite - Win32 Debug"
+# Begin Group "Source Files"
+
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;hpj;bat;for;f90"
+# Begin Source File
+
+SOURCE=..\..\modules\standard\mod_rewrite.c
+# End Source File
+# Begin Source File
+
+SOURCE=.\passwd.c
+# End Source File
+# End Group
+# Begin Group "Header Files"
+
+# PROP Default_Filter "h;hpp;hxx;hm;inl;fi;fd"
+# Begin Source File
+
+SOURCE=.\readdir.h
+# End Source File
+# End Group
+# Begin Group "Resource Files"
+
+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe"
+# End Group
+# End Target
+# End Project
diff --git a/modules/mappers/mod_rewrite.h b/modules/mappers/mod_rewrite.h
new file mode 100644
index 00000000000..22ff3375589
--- /dev/null
+++ b/modules/mappers/mod_rewrite.h
@@ -0,0 +1,497 @@
+/* ====================================================================
+ * Copyright (c) 1996-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+
+#ifndef _MOD_REWRITE_H
+#define _MOD_REWRITE_H 1
+
+/*
+** _ _ _
+** _ __ ___ ___ __| | _ __ _____ ___ __(_) |_ ___
+** | '_ ` _ \ / _ \ / _` | | '__/ _ \ \ /\ / / '__| | __/ _ \
+** | | | | | | (_) | (_| | | | | __/\ V V /| | | | || __/
+** |_| |_| |_|\___/ \__,_|___|_| \___| \_/\_/ |_| |_|\__\___|
+** |_____|
+**
+** URL Rewriting Module
+**
+** This module uses a rule-based rewriting engine (based on a
+** regular-expression parser) to rewrite requested URLs on the fly.
+**
+** It supports an unlimited number of additional rule conditions (which can
+** operate on a lot of variables, even on HTTP headers) for granular
+** matching and even external database lookups (either via plain text
+** tables, DBM hash files or even external processes) for advanced URL
+** substitution.
+**
+** It operates on the full URLs (including the PATH_INFO part) both in
+** per-server context (httpd.conf) and per-dir context (.htaccess) and even
+** can generate QUERY_STRING parts on result. The rewriting result finally
+** can lead to internal subprocessing, external request redirection or even
+** to internal proxy throughput.
+**
+** This module was originally written in April 1996 and
+** gifted exclusively to the The Apache Group in July 1997 by
+**
+** Ralf S. Engelschall
+** rse@engelschall.com
+** www.engelschall.com
+*/
+
+
+ /* Include from the underlaying Unix system ... */
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+ /* Include from the Apache server ... */
+#define CORE_PRIVATE
+#include "httpd.h"
+#include "http_config.h"
+#include "http_conf_globals.h"
+#include "http_request.h"
+#include "http_core.h"
+#include "http_log.h"
+#include "http_vhost.h"
+
+ /*
+ * The key in the r->notes table wherein we store our accumulated
+ * Vary values, and the one used for per-condition checks in a chain.
+ */
+#define VARY_KEY "rewrite-Vary"
+#define VARY_KEY_THIS "rewrite-Vary-this"
+
+ /* The NDBM support:
+ * We support only NDBM files.
+ * But we have to stat the file for the mtime,
+ * so we also need to know the file extension
+ */
+#ifndef NO_DBM_REWRITEMAP
+#if defined(__GLIBC__) && defined(__GLIBC_MINOR__) \
+ && __GLIBC__ >= 2 && __GLIBC_MINOR__ >= 1
+#include
+#else
+#include
+#endif
+#if defined(DBM_SUFFIX)
+#define NDBM_FILE_SUFFIX DBM_SUFFIX
+#elif defined(__FreeBSD__) || (defined(DB_LOCK) && defined(DB_SHMEM))
+#define NDBM_FILE_SUFFIX ".db"
+#else
+#define NDBM_FILE_SUFFIX ".pag"
+#endif
+#endif
+
+
+ /* The locking support:
+ * Try to determine whether we should use fcntl() or flock().
+ * Would be better ap_config.h could provide this... :-(
+ */
+#if defined(USE_FCNTL_SERIALIZED_ACCEPT)
+#define USE_FCNTL 1
+#include
+#endif
+#if defined(USE_FLOCK_SERIALIZED_ACCEPT)
+#define USE_FLOCK 1
+#include
+#endif
+#if !defined(USE_FCNTL) && !defined(USE_FLOCK)
+#define USE_FLOCK 1
+#if !defined(MPE) && !defined(WIN32) && !defined(__TANDEM)
+#include
+#endif
+#ifndef LOCK_UN
+#undef USE_FLOCK
+#define USE_FCNTL 1
+#include
+#endif
+#endif
+#ifdef AIX
+#undef USE_FLOCK
+#define USE_FCNTL 1
+#include
+#endif
+#ifdef WIN32
+#undef USE_FCNTL
+#define USE_LOCKING
+#include
+#endif
+
+
+/*
+**
+** Some defines
+**
+*/
+
+#define ENVVAR_SCRIPT_URL "SCRIPT_URL"
+#define ENVVAR_SCRIPT_URI "SCRIPT_URI"
+
+#ifndef SUPPORT_DBM_REWRITEMAP
+#define SUPPORT_DBM_REWRITEMAP 0
+#endif
+
+#define REWRITE_FORCED_MIMETYPE_NOTEVAR "rewrite-forced-mimetype"
+
+#define CONDFLAG_NONE 1<<0
+#define CONDFLAG_NOCASE 1<<1
+#define CONDFLAG_NOTMATCH 1<<2
+#define CONDFLAG_ORNEXT 1<<3
+
+#define RULEFLAG_NONE 1<<0
+#define RULEFLAG_FORCEREDIRECT 1<<1
+#define RULEFLAG_LASTRULE 1<<2
+#define RULEFLAG_NEWROUND 1<<3
+#define RULEFLAG_CHAIN 1<<4
+#define RULEFLAG_IGNOREONSUBREQ 1<<5
+#define RULEFLAG_NOTMATCH 1<<6
+#define RULEFLAG_PROXY 1<<7
+#define RULEFLAG_PASSTHROUGH 1<<8
+#define RULEFLAG_FORBIDDEN 1<<9
+#define RULEFLAG_GONE 1<<10
+#define RULEFLAG_QSAPPEND 1<<11
+#define RULEFLAG_NOCASE 1<<12
+
+#define MAPTYPE_TXT 1<<0
+#define MAPTYPE_DBM 1<<1
+#define MAPTYPE_PRG 1<<2
+#define MAPTYPE_INT 1<<3
+#define MAPTYPE_RND 1<<4
+
+#define ENGINE_DISABLED 1<<0
+#define ENGINE_ENABLED 1<<1
+
+#define OPTION_NONE 1<<0
+#define OPTION_INHERIT 1<<1
+
+#define CACHEMODE_TS 1<<0
+#define CACHEMODE_TTL 1<<1
+
+#define CACHE_TLB_ROWS 1024
+#define CACHE_TLB_COLS 4
+
+#ifndef FALSE
+#define FALSE 0
+#define TRUE !FALSE
+#endif
+
+#ifndef NO
+#define NO FALSE
+#define YES TRUE
+#endif
+
+#ifndef RAND_MAX
+#define RAND_MAX 32767
+#endif
+
+#ifndef LONG_STRING_LEN
+#define LONG_STRING_LEN 2048
+#endif
+
+#define MAX_ENV_FLAGS 15
+
+#define MAX_NMATCH 10
+
+/*
+**
+** our private data structures we handle with
+**
+*/
+
+ /* the list structures for holding the mapfile information
+ * and the rewrite rules
+ */
+typedef struct {
+ char *name; /* the name of the map */
+ char *datafile; /* filename for map data files */
+ char *checkfile; /* filename to check for map existence */
+ int type; /* the type of the map */
+ int fpin; /* in file pointer for program maps */
+ int fpout; /* out file pointer for program maps */
+ int fperr; /* err file pointer for program maps */
+ char *(*func)(request_rec *, /* function pointer for internal maps */
+ char *);
+} rewritemap_entry;
+
+typedef struct {
+ char *input; /* Input string of RewriteCond */
+ char *pattern; /* the RegExp pattern string */
+ regex_t *regexp;
+ int flags; /* Flags which control the match */
+} rewritecond_entry;
+
+typedef struct {
+ array_header *rewriteconds; /* the corresponding RewriteCond entries */
+ char *pattern; /* the RegExp pattern string */
+ regex_t *regexp; /* the RegExp pattern compilation */
+ char *output; /* the Substitution string */
+ int flags; /* Flags which control the substitution */
+ char *forced_mimetype; /* forced MIME type of substitution */
+ int forced_responsecode; /* forced HTTP redirect response status */
+ char *env[MAX_ENV_FLAGS+1]; /* added environment variables */
+ int skip; /* number of next rules to skip */
+} rewriterule_entry;
+
+
+ /* the per-server or per-virtual-server configuration
+ * statically generated once on startup for every server
+ */
+typedef struct {
+ int state; /* the RewriteEngine state */
+ int options; /* the RewriteOption state */
+ char *rewritelogfile; /* the RewriteLog filename */
+ int rewritelogfp; /* the RewriteLog open filepointer */
+ int rewriteloglevel; /* the RewriteLog level of verbosity */
+ array_header *rewritemaps; /* the RewriteMap entries */
+ array_header *rewriteconds; /* the RewriteCond entries (temporary) */
+ array_header *rewriterules; /* the RewriteRule entries */
+ server_rec *server; /* the corresponding server indicator */
+} rewrite_server_conf;
+
+
+ /* the per-directory configuration
+ * generated on-the-fly by Apache server for current request
+ */
+typedef struct {
+ int state; /* the RewriteEngine state */
+ int options; /* the RewriteOption state */
+ array_header *rewriteconds; /* the RewriteCond entries (temporary) */
+ array_header *rewriterules; /* the RewriteRule entries */
+ char *directory; /* the directory where it applies */
+ char *baseurl; /* the base-URL where it applies */
+} rewrite_perdir_conf;
+
+
+ /* the cache structures,
+ * a 4-way hash table with LRU functionality
+ */
+typedef struct cacheentry {
+ time_t time;
+ char *key;
+ char *value;
+} cacheentry;
+
+typedef struct tlbentry {
+ int t[CACHE_TLB_COLS];
+} cachetlbentry;
+
+typedef struct cachelist {
+ char *resource;
+ array_header *entries;
+ array_header *tlb;
+} cachelist;
+
+typedef struct cache {
+ pool *pool;
+ array_header *lists;
+} cache;
+
+
+ /* the regex structure for the
+ * substitution of backreferences
+ */
+typedef struct backrefinfo {
+ char *source;
+ int nsub;
+ regmatch_t regmatch[10];
+} backrefinfo;
+
+
+/*
+**
+** forward declarations
+**
+*/
+
+ /* config structure handling */
+static void *config_server_create(pool *p, server_rec *s);
+static void *config_server_merge (pool *p, void *basev, void *overridesv);
+static void *config_perdir_create(pool *p, char *path);
+static void *config_perdir_merge (pool *p, void *basev, void *overridesv);
+
+ /* config directive handling */
+static const char *cmd_rewriteengine(cmd_parms *cmd,
+ rewrite_perdir_conf *dconf, int flag);
+static const char *cmd_rewriteoptions(cmd_parms *cmd,
+ rewrite_perdir_conf *dconf,
+ char *option);
+static const char *cmd_rewriteoptions_setoption(pool *p, int *options,
+ char *name);
+static const char *cmd_rewritelog (cmd_parms *cmd, void *dconf, char *a1);
+static const char *cmd_rewriteloglevel(cmd_parms *cmd, void *dconf, char *a1);
+static const char *cmd_rewritemap (cmd_parms *cmd, void *dconf, char *a1,
+ char *a2);
+static const char *cmd_rewritelock(cmd_parms *cmd, void *dconf, char *a1);
+static const char *cmd_rewritebase(cmd_parms *cmd, rewrite_perdir_conf *dconf,
+ char *a1);
+static const char *cmd_rewritecond(cmd_parms *cmd, rewrite_perdir_conf *dconf,
+ char *str);
+static const char *cmd_rewritecond_parseflagfield(pool *p,
+ rewritecond_entry *new,
+ char *str);
+static const char *cmd_rewritecond_setflag(pool *p, rewritecond_entry *cfg,
+ char *key, char *val);
+static const char *cmd_rewriterule(cmd_parms *cmd, rewrite_perdir_conf *dconf,
+ char *str);
+static const char *cmd_rewriterule_parseflagfield(pool *p,
+ rewriterule_entry *new,
+ char *str);
+static const char *cmd_rewriterule_setflag(pool *p, rewriterule_entry *cfg,
+ char *key, char *val);
+
+ /* initialisation */
+static void init_module(server_rec *s, pool *p);
+static void init_child(server_rec *s, pool *p);
+
+ /* runtime hooks */
+static int hook_uri2file (request_rec *r);
+static int hook_mimetype (request_rec *r);
+static int hook_fixup (request_rec *r);
+static int handler_redirect(request_rec *r);
+
+ /* rewriting engine */
+static int apply_rewrite_list(request_rec *r, array_header *rewriterules,
+ char *perdir);
+static int apply_rewrite_rule(request_rec *r, rewriterule_entry *p,
+ char *perdir);
+static int apply_rewrite_cond(request_rec *r, rewritecond_entry *p,
+ char *perdir, backrefinfo *briRR,
+ backrefinfo *briRC);
+
+ /* URI transformation function */
+static void splitout_queryargs(request_rec *r, int qsappend);
+static void fully_qualify_uri(request_rec *r);
+static void reduce_uri(request_rec *r);
+static void expand_backref_inbuffer(pool *p, char *buf, int nbuf,
+ backrefinfo *bri, char c);
+static char *expand_tildepaths(request_rec *r, char *uri);
+static void expand_map_lookups(request_rec *r, char *uri, int uri_len);
+
+ /* rewrite map support functions */
+static char *lookup_map(request_rec *r, char *name, char *key);
+static char *lookup_map_txtfile(request_rec *r, char *file, char *key);
+#ifndef NO_DBM_REWRITEMAP
+static char *lookup_map_dbmfile(request_rec *r, char *file, char *key);
+#endif
+static char *lookup_map_program(request_rec *r, int fpin,
+ int fpout, char *key);
+static char *lookup_map_internal(request_rec *r,
+ char *(*func)(request_rec *r, char *key),
+ char *key);
+static char *rewrite_mapfunc_toupper(request_rec *r, char *key);
+static char *rewrite_mapfunc_tolower(request_rec *r, char *key);
+static char *rewrite_mapfunc_escape(request_rec *r, char *key);
+static char *rewrite_mapfunc_unescape(request_rec *r, char *key);
+static char *select_random_value_part(request_rec *r, char *value);
+static void rewrite_rand_init(void);
+static int rewrite_rand(int l, int h);
+
+ /* rewriting logfile support */
+static void open_rewritelog(server_rec *s, pool *p);
+static void rewritelog(request_rec *r, int level, const char *text, ...)
+ __attribute__((format(printf,3,4)));
+static char *current_logtime(request_rec *r);
+
+ /* rewriting lockfile support */
+static void rewritelock_create(server_rec *s, pool *p);
+static void rewritelock_open(server_rec *s, pool *p);
+static void rewritelock_remove(void *data);
+static void rewritelock_alloc(request_rec *r);
+static void rewritelock_free(request_rec *r);
+
+ /* program map support */
+static void run_rewritemap_programs(server_rec *s, pool *p);
+static int rewritemap_program_child(void *cmd, child_info *pinfo);
+
+ /* env variable support */
+static void expand_variables_inbuffer(request_rec *r, char *buf, int buf_len);
+static char *expand_variables(request_rec *r, char *str);
+static char *lookup_variable(request_rec *r, char *var);
+static char *lookup_header(request_rec *r, const char *name);
+
+ /* caching functions */
+static cache *init_cache(pool *p);
+static char *get_cache_string(cache *c, char *res, int mode, time_t mtime,
+ char *key);
+static void set_cache_string(cache *c, char *res, int mode, time_t mtime,
+ char *key, char *value);
+static cacheentry *retrieve_cache_string(cache *c, char *res, char *key);
+static void store_cache_string(cache *c, char *res, cacheentry *ce);
+
+ /* misc functions */
+static char *subst_prefix_path(request_rec *r, char *input, char *match,
+ char *subst);
+static int parseargline(char *str, char **a1, char **a2, char **a3);
+static int prefix_stat(const char *path, struct stat *sb);
+static void add_env_variable(request_rec *r, char *s);
+
+ /* File locking */
+static void fd_lock(request_rec *r, int fd);
+static void fd_unlock(request_rec *r, int fd);
+
+ /* Lexicographic Comparison */
+static int compare_lexicography(char *cpNum1, char *cpNum2);
+
+#endif /* _MOD_REWRITE_H */
+
+/*EOF*/
diff --git a/modules/mappers/mod_so.c b/modules/mappers/mod_so.c
new file mode 100644
index 00000000000..0f0b63d37c6
--- /dev/null
+++ b/modules/mappers/mod_so.c
@@ -0,0 +1,360 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+/*
+ * This module is used to load Apache modules at runtime. This means that the
+ * server functionality can be extended without recompiling and even without
+ * taking the server down at all. Only a HUP or USR1 signal needs to be send
+ * to the server to reload the dynamically loaded modules.
+ *
+ * To use, you'll first need to build your module as a shared library, then
+ * update your configuration (httpd.conf) to get the Apache core to load the
+ * module at start-up.
+ *
+ * The easiest way to build a module as a shared library is to use the
+ * `SharedModule' command in the Configuration file, instead of `AddModule'.
+ * You should also change the file extension from `.o' to `.so'. So, for
+ * example, to build the status module as a shared library edit Configuration
+ * and change
+ * AddModule modules/standard/mod_status.o
+ * to
+ * SharedModule modules/standard/mod_status.so
+ *
+ * Run Configure and make. Now Apache's httpd binary will _not_ include
+ * mod_status. Instead a shared object called mod_status.so will be build, in
+ * the modules/standard directory. You can build most of the modules as shared
+ * libraries like this.
+ *
+ * To use the shared module, move the .so file(s) into an appropriate
+ * directory. You might like to create a directory called "modules" under you
+ * server root for this (e.g. /usr/local/httpd/modules).
+ *
+ * Then edit your conf/httpd.conf file, and add LoadModule lines. For
+ * example
+ * LoadModule status_module modules/mod_status.so
+ *
+ * The first argument is the module's structure name (look at the end of the
+ * module source to find this). The second option is the path to the module
+ * file, relative to the server root. Put these directives right at the top
+ * of your httpd.conf file.
+ *
+ * Now you can start Apache. A message will be logged at "debug" level to your
+ * error_log to confirm that the module(s) are loaded (use "LogLevel debug"
+ * directive to get these log messages).
+ *
+ * If you edit the LoadModule directives while the server is live you can get
+ * Apache to re-load the modules by sending it a HUP or USR1 signal as normal.
+ * You can use this to dynamically change the capability of your server
+ * without bringing it down.
+ *
+ * Because currently there is only limited built-in support in the Configure
+ * script for creating the shared library files (`.so'), please consult your
+ * vendors cc(1), ld(1) and dlopen(3) manpages to find out the appropriate
+ * compiler and linker flags and insert them manually into the Configuration
+ * file under CFLAGS_SHLIB, LDFLAGS_SHLIB and LDFLAGS_SHLIB_EXPORT.
+ *
+ * If you still have problems figuring out the flags both try the paper
+ * http://developer.netscape.com/library/documentation/enterprise
+ * /unix/svrplug.htm#1013807
+ * or install a Perl 5 interpreter on your platform and then run the command
+ *
+ * $ perl -V:usedl -V:ccdlflags -V:cccdlflags -V:lddlflags
+ *
+ * This gives you what type of dynamic loading Perl 5 uses on your platform
+ * and which compiler and linker flags Perl 5 uses to create the shared object
+ * files.
+ *
+ * Another location where you can find useful hints is the `ltconfig' script
+ * of the GNU libtool 1.2 package. Search for your platform name inside the
+ * various "case" constructs.
+ *
+ */
+
+
+#define CORE_PRIVATE
+#include "httpd.h"
+#include "http_config.h"
+#include "http_log.h"
+
+module MODULE_VAR_EXPORT so_module;
+
+
+/*
+ * Server configuration to keep track of actually
+ * loaded modules and the corresponding module name.
+ */
+
+typedef struct moduleinfo {
+ char *name;
+ module *modp;
+} moduleinfo;
+
+typedef struct so_server_conf {
+ array_header *loaded_modules;
+} so_server_conf;
+
+static void *so_sconf_create(pool *p, server_rec *s)
+{
+ so_server_conf *soc;
+
+ soc = (so_server_conf *)ap_pcalloc(p, sizeof(so_server_conf));
+ soc->loaded_modules = ap_make_array(p, DYNAMIC_MODULE_LIMIT,
+ sizeof(moduleinfo));
+#ifndef NO_DLOPEN
+ ap_os_dso_init();
+#endif
+
+ return (void *)soc;
+}
+
+#ifndef NO_DLOPEN
+
+/*
+ * This is the cleanup for a loaded shared object. It unloads the module.
+ * This is called as a cleanup function from the core.
+ */
+
+static void unload_module(moduleinfo *modi)
+{
+ /* only unload if module information is still existing */
+ if (modi->modp == NULL)
+ return;
+
+ /* remove the module pointer from the core structure */
+ ap_remove_loaded_module(modi->modp);
+
+ /* unload the module space itself */
+ ap_os_dso_unload((ap_os_dso_handle_t)modi->modp->dynamic_load_handle);
+
+ /* destroy the module information */
+ modi->modp = NULL;
+ modi->name = NULL;
+}
+
+/*
+ * This is the cleanup routine for files loaded by
+ * load_file(). Unfortunately we don't keep a record of the filename
+ * that was loaded, so we can't report the unload for debug purposes
+ * or include the filename in error message.
+ */
+
+static void unload_file(void *handle)
+{
+ ap_os_dso_unload((ap_os_dso_handle_t)handle);
+}
+
+/*
+ * This is called for the directive LoadModule and actually loads
+ * a shared object file into the address space of the server process.
+ */
+
+static const char *load_module(cmd_parms *cmd, void *dummy,
+ char *modname, char *filename)
+{
+ ap_os_dso_handle_t modhandle;
+ module *modp;
+ const char *szModuleFile=ap_server_root_relative(cmd->pool, filename);
+ so_server_conf *sconf;
+ moduleinfo *modi;
+ moduleinfo *modie;
+ int i;
+
+ /*
+ * check for already existing module
+ * If it already exists, we have nothing to do
+ */
+ sconf = (so_server_conf *)ap_get_module_config(cmd->server->module_config,
+ &so_module);
+ modie = (moduleinfo *)sconf->loaded_modules->elts;
+ for (i = 0; i < sconf->loaded_modules->nelts; i++) {
+ modi = &modie[i];
+ if (modi->name != NULL && strcmp(modi->name, modname) == 0)
+ return NULL;
+ }
+ modi = ap_push_array(sconf->loaded_modules);
+ modi->name = modname;
+
+ /*
+ * Load the file into the Apache address space
+ */
+ if (!(modhandle = ap_os_dso_load(szModuleFile))) {
+ const char *my_error = ap_os_dso_error();
+ return ap_pstrcat (cmd->pool, "Cannot load ", szModuleFile,
+ " into server: ",
+ my_error ? my_error : "(reason unknown)",
+ NULL);
+ }
+ ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, NULL,
+ "loaded module %s", modname);
+
+ /*
+ * Retrieve the pointer to the module structure through the module name:
+ * First with the hidden variant (prefix `AP_') and then with the plain
+ * symbol name.
+ */
+ if (!(modp = (module *)(ap_os_dso_sym(modhandle, modname)))) {
+ return ap_pstrcat(cmd->pool, "Can't locate API module structure `", modname,
+ "' in file ", szModuleFile, ": ", ap_os_dso_error(), NULL);
+ }
+ modi->modp = modp;
+ modp->dynamic_load_handle = (void *)modhandle;
+
+ /*
+ * Make sure the found module structure is really a module structure
+ *
+ */
+ if (modp->magic != MODULE_MAGIC_COOKIE) {
+ return ap_pstrcat(cmd->pool, "API module structure `", modname,
+ "' in file ", szModuleFile, " is garbled -"
+ " perhaps this is not an Apache module DSO?", NULL);
+ }
+
+ /*
+ * Add this module to the Apache core structures
+ */
+ ap_add_loaded_module(modp);
+
+ /*
+ * Register a cleanup in the config pool (normally pconf). When
+ * we do a restart (or shutdown) this cleanup will cause the
+ * shared object to be unloaded.
+ */
+ ap_register_cleanup(cmd->pool, modi,
+ (void (*)(void*))unload_module, ap_null_cleanup);
+
+ /*
+ * Finally we need to run the configuration process for the module
+ */
+ ap_single_module_configure(cmd->pool, cmd->server, modp);
+
+ return NULL;
+}
+
+/*
+ * This implements the LoadFile directive and loads an arbitrary
+ * shared object file into the adress space of the server process.
+ */
+
+static const char *load_file(cmd_parms *cmd, void *dummy, char *filename)
+{
+ ap_os_dso_handle_t handle;
+ char *file;
+
+ file = ap_server_root_relative(cmd->pool, filename);
+
+ if (!(handle = ap_os_dso_load(file))) {
+ const char *my_error = ap_os_dso_error();
+ return ap_pstrcat (cmd->pool, "Cannot load ", filename,
+ " into server:",
+ my_error ? my_error : "(reason unknown)",
+ NULL);
+ }
+
+ ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, NULL,
+ "loaded file %s", filename);
+
+ ap_register_cleanup(cmd->pool, (void *)handle, unload_file, ap_null_cleanup);
+
+ return NULL;
+}
+
+#else /* not NO_DLOPEN */
+
+static const char *load_file(cmd_parms *cmd, void *dummy, char *filename)
+{
+ fprintf(stderr, "WARNING: LoadFile not supported on this platform\n");
+ return NULL;
+}
+
+static const char *load_module(cmd_parms *cmd, void *dummy,
+ char *modname, char *filename)
+{
+ fprintf(stderr, "WARNING: LoadModule not supported on this platform\n");
+ return NULL;
+}
+
+#endif /* NO_DLOPEN */
+
+static const command_rec so_cmds[] = {
+ { "LoadModule", load_module, NULL, RSRC_CONF, TAKE2,
+ "a module name and the name of a shared object file to load it from"},
+ { "LoadFile", load_file, NULL, RSRC_CONF, ITERATE,
+ "shared object file or library to load into the server at runtime"},
+ { NULL }
+};
+
+module MODULE_VAR_EXPORT so_module = {
+ STANDARD_MODULE_STUFF,
+ NULL, /* initializer */
+ NULL, /* create per-dir config */
+ NULL, /* merge per-dir config */
+ so_sconf_create, /* server config */
+ NULL, /* merge server config */
+ so_cmds, /* command table */
+ NULL, /* handlers */
+ NULL, /* filename translation */
+ NULL, /* check_user_id */
+ NULL, /* check auth */
+ NULL, /* check access */
+ NULL, /* type_checker */
+ NULL, /* fixer_upper */
+ NULL, /* logger */
+ NULL, /* header parser */
+ NULL, /* child_init */
+ NULL, /* child_exit */
+ NULL /* post read-request */
+};
diff --git a/modules/mappers/mod_speling.c b/modules/mappers/mod_speling.c
new file mode 100644
index 00000000000..067fd77c719
--- /dev/null
+++ b/modules/mappers/mod_speling.c
@@ -0,0 +1,558 @@
+#define WANT_BASENAME_MATCH
+/* ====================================================================
+ * Copyright (c) 1996-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+#include "httpd.h"
+#include "http_core.h"
+#include "http_config.h"
+#include "http_log.h"
+
+/* mod_speling.c - by Alexei Kosut June, 1996
+ *
+ * This module is transparent, and simple. It attempts to correct
+ * misspellings of URLs that users might have entered, namely by checking
+ * capitalizations. If it finds a match, it sends a redirect.
+ *
+ * 08-Aug-1997
+ * o Upgraded module interface to apache_1.3a2-dev API (more NULL's in
+ * speling_module).
+ * o Integrated tcsh's "spelling correction" routine which allows one
+ * misspelling (character insertion/omission/typo/transposition).
+ * Rewrote it to ignore case as well. This ought to catch the majority
+ * of misspelled requests.
+ * o Commented out the second pass where files' suffixes are stripped.
+ * Given the better hit rate of the first pass, this rather ugly
+ * (request index.html, receive index.db ?!?!) solution can be
+ * omitted.
+ * o wrote a "kind of" html page for mod_speling
+ *
+ * Activate it with "CheckSpelling On"
+ */
+
+MODULE_VAR_EXPORT module speling_module;
+
+typedef struct {
+ int enabled;
+} spconfig;
+
+/*
+ * Create a configuration specific to this module for a server or directory
+ * location, and fill it with the default settings.
+ *
+ * The API says that in the absence of a merge function, the record for the
+ * closest ancestor is used exclusively. That's what we want, so we don't
+ * bother to have such a function.
+ */
+
+static void *mkconfig(pool *p)
+{
+ spconfig *cfg = ap_pcalloc(p, sizeof(spconfig));
+
+ cfg->enabled = 0;
+ return cfg;
+}
+
+/*
+ * Respond to a callback to create configuration record for a server or
+ * vhost environment.
+ */
+static void *create_mconfig_for_server(pool *p, server_rec *s)
+{
+ return mkconfig(p);
+}
+
+/*
+ * Respond to a callback to create a config record for a specific directory.
+ */
+static void *create_mconfig_for_directory(pool *p, char *dir)
+{
+ return mkconfig(p);
+}
+
+/*
+ * Handler for the CheckSpelling directive, which is FLAG.
+ */
+static const char *set_speling(cmd_parms *cmd, void *mconfig, int arg)
+{
+ spconfig *cfg = (spconfig *) mconfig;
+
+ cfg->enabled = arg;
+ return NULL;
+}
+
+/*
+ * Define the directives specific to this module. This structure is referenced
+ * later by the 'module' structure.
+ */
+static const command_rec speling_cmds[] =
+{
+ { "CheckSpelling", set_speling, NULL, OR_OPTIONS, FLAG,
+ "whether or not to fix miscapitalized/misspelled requests" },
+ { NULL }
+};
+
+typedef enum {
+ SP_IDENTICAL = 0,
+ SP_MISCAPITALIZED = 1,
+ SP_TRANSPOSITION = 2,
+ SP_MISSINGCHAR = 3,
+ SP_EXTRACHAR = 4,
+ SP_SIMPLETYPO = 5,
+ SP_VERYDIFFERENT = 6
+} sp_reason;
+
+static const char *sp_reason_str[] =
+{
+ "identical",
+ "miscapitalized",
+ "transposed characters",
+ "character missing",
+ "extra character",
+ "mistyped character",
+ "common basename",
+};
+
+typedef struct {
+ const char *name;
+ sp_reason quality;
+} misspelled_file;
+
+/*
+ * spdist() is taken from Kernighan & Pike,
+ * _The_UNIX_Programming_Environment_
+ * and adapted somewhat to correspond better to psychological reality.
+ * (Note the changes to the return values)
+ *
+ * According to Pollock and Zamora, CACM April 1984 (V. 27, No. 4),
+ * page 363, the correct order for this is:
+ * OMISSION = TRANSPOSITION > INSERTION > SUBSTITUTION
+ * thus, it was exactly backwards in the old version. -- PWP
+ *
+ * This routine was taken out of tcsh's spelling correction code
+ * (tcsh-6.07.04) and re-converted to apache data types ("char" type
+ * instead of tcsh's NLS'ed "Char"). Plus it now ignores the case
+ * during comparisons, so is a "approximate strcasecmp()".
+ * NOTE that is still allows only _one_ real "typo",
+ * it does NOT try to correct multiple errors.
+ */
+
+static sp_reason spdist(const char *s, const char *t)
+{
+ for (; ap_tolower(*s) == ap_tolower(*t); t++, s++) {
+ if (*t == '\0') {
+ return SP_MISCAPITALIZED; /* exact match (sans case) */
+ }
+ }
+ if (*s) {
+ if (*t) {
+ if (s[1] && t[1] && ap_tolower(*s) == ap_tolower(t[1])
+ && ap_tolower(*t) == ap_tolower(s[1])
+ && strcasecmp(s + 2, t + 2) == 0) {
+ return SP_TRANSPOSITION; /* transposition */
+ }
+ if (strcasecmp(s + 1, t + 1) == 0) {
+ return SP_SIMPLETYPO; /* 1 char mismatch */
+ }
+ }
+ if (strcasecmp(s + 1, t) == 0) {
+ return SP_EXTRACHAR; /* extra character */
+ }
+ }
+ if (*t && strcasecmp(s, t + 1) == 0) {
+ return SP_MISSINGCHAR; /* missing character */
+ }
+ return SP_VERYDIFFERENT; /* distance too large to fix. */
+}
+
+static int sort_by_quality(const void *left, const void *rite)
+{
+ return (int) (((misspelled_file *) left)->quality)
+ - (int) (((misspelled_file *) rite)->quality);
+}
+
+static int check_speling(request_rec *r)
+{
+ spconfig *cfg;
+ char *good, *bad, *postgood, *url;
+ int filoc, dotloc, urlen, pglen;
+ DIR *dirp;
+ struct DIR_TYPE *dir_entry;
+ array_header *candidates = NULL;
+
+ cfg = ap_get_module_config(r->per_dir_config, &speling_module);
+ if (!cfg->enabled) {
+ return DECLINED;
+ }
+
+ /* We only want to worry about GETs */
+ if (r->method_number != M_GET) {
+ return DECLINED;
+ }
+
+ /* We've already got a file of some kind or another */
+ if (r->proxyreq || (r->finfo.st_mode != 0)) {
+ return DECLINED;
+ }
+
+ /* This is a sub request - don't mess with it */
+ if (r->main) {
+ return DECLINED;
+ }
+
+ /*
+ * The request should end up looking like this:
+ * r->uri: /correct-url/mispelling/more
+ * r->filename: /correct-file/mispelling r->path_info: /more
+ *
+ * So we do this in steps. First break r->filename into two pieces
+ */
+
+ filoc = ap_rind(r->filename, '/');
+ /*
+ * Don't do anything if the request doesn't contain a slash, or
+ * requests "/"
+ */
+ if (filoc == -1 || strcmp(r->uri, "/") == 0) {
+ return DECLINED;
+ }
+
+ /* good = /correct-file */
+ good = ap_pstrndup(r->pool, r->filename, filoc);
+ /* bad = mispelling */
+ bad = ap_pstrdup(r->pool, r->filename + filoc + 1);
+ /* postgood = mispelling/more */
+ postgood = ap_pstrcat(r->pool, bad, r->path_info, NULL);
+
+ urlen = strlen(r->uri);
+ pglen = strlen(postgood);
+
+ /* Check to see if the URL pieces add up */
+ if (strcmp(postgood, r->uri + (urlen - pglen))) {
+ return DECLINED;
+ }
+
+ /* url = /correct-url */
+ url = ap_pstrndup(r->pool, r->uri, (urlen - pglen));
+
+ /* Now open the directory and do ourselves a check... */
+ dirp = ap_popendir(r->pool, good);
+ if (dirp == NULL) { /* Oops, not a directory... */
+ return DECLINED;
+ }
+
+ candidates = ap_make_array(r->pool, 2, sizeof(misspelled_file));
+
+ dotloc = ap_ind(bad, '.');
+ if (dotloc == -1) {
+ dotloc = strlen(bad);
+ }
+
+ while ((dir_entry = readdir(dirp)) != NULL) {
+ sp_reason q;
+
+ /*
+ * If we end up with a "fixed" URL which is identical to the
+ * requested one, we must have found a broken symlink or some such.
+ * Do _not_ try to redirect this, it causes a loop!
+ */
+ if (strcmp(bad, dir_entry->d_name) == 0) {
+ ap_pclosedir(r->pool, dirp);
+ return OK;
+ }
+ /*
+ * miscapitalization errors are checked first (like, e.g., lower case
+ * file, upper case request)
+ */
+ else if (strcasecmp(bad, dir_entry->d_name) == 0) {
+ misspelled_file *sp_new;
+
+ sp_new = (misspelled_file *) ap_push_array(candidates);
+ sp_new->name = ap_pstrdup(r->pool, dir_entry->d_name);
+ sp_new->quality = SP_MISCAPITALIZED;
+ }
+ /*
+ * simple typing errors are checked next (like, e.g.,
+ * missing/extra/transposed char)
+ */
+ else if ((q = spdist(bad, dir_entry->d_name)) != SP_VERYDIFFERENT) {
+ misspelled_file *sp_new;
+
+ sp_new = (misspelled_file *) ap_push_array(candidates);
+ sp_new->name = ap_pstrdup(r->pool, dir_entry->d_name);
+ sp_new->quality = q;
+ }
+ /*
+ * The spdist() should have found the majority of the misspelled
+ * requests. It is of questionable use to continue looking for
+ * files with the same base name, but potentially of totally wrong
+ * type (index.html <-> index.db).
+ * I would propose to not set the WANT_BASENAME_MATCH define.
+ * 08-Aug-1997
+ *
+ * However, Alexei replied giving some reasons to add it anyway:
+ * > Oh, by the way, I remembered why having the
+ * > extension-stripping-and-matching stuff is a good idea:
+ * >
+ * > If you're using MultiViews, and have a file named foobar.html,
+ * > which you refer to as "foobar", and someone tried to access
+ * > "Foobar", mod_speling won't find it, because it won't find
+ * > anything matching that spelling. With the extension-munging,
+ * > it would locate "foobar.html". Not perfect, but I ran into
+ * > that problem when I first wrote the module.
+ */
+ else {
+#ifdef WANT_BASENAME_MATCH
+ /*
+ * Okay... we didn't find anything. Now we take out the hard-core
+ * power tools. There are several cases here. Someone might have
+ * entered a wrong extension (.htm instead of .html or vice
+ * versa) or the document could be negotiated. At any rate, now
+ * we just compare stuff before the first dot. If it matches, we
+ * figure we got us a match. This can result in wrong things if
+ * there are files of different content types but the same prefix
+ * (e.g. foo.gif and foo.html) This code will pick the first one
+ * it finds. Better than a Not Found, though.
+ */
+ int entloc = ap_ind(dir_entry->d_name, '.');
+ if (entloc == -1) {
+ entloc = strlen(dir_entry->d_name);
+ }
+
+ if ((dotloc == entloc)
+ && !strncasecmp(bad, dir_entry->d_name, dotloc)) {
+ misspelled_file *sp_new;
+
+ sp_new = (misspelled_file *) ap_push_array(candidates);
+ sp_new->name = ap_pstrdup(r->pool, dir_entry->d_name);
+ sp_new->quality = SP_VERYDIFFERENT;
+ }
+#endif
+ }
+ }
+ ap_pclosedir(r->pool, dirp);
+
+ if (candidates->nelts != 0) {
+ /* Wow... we found us a mispelling. Construct a fixed url */
+ char *nuri;
+ const char *ref;
+ misspelled_file *variant = (misspelled_file *) candidates->elts;
+ int i;
+
+ ref = ap_table_get(r->headers_in, "Referer");
+
+ qsort((void *) candidates->elts, candidates->nelts,
+ sizeof(misspelled_file), sort_by_quality);
+
+ /*
+ * Conditions for immediate redirection:
+ * a) the first candidate was not found by stripping the suffix
+ * AND b) there exists only one candidate OR the best match is not
+ * ambiguous
+ * then return a redirection right away.
+ */
+ if (variant[0].quality != SP_VERYDIFFERENT
+ && (candidates->nelts == 1
+ || variant[0].quality != variant[1].quality)) {
+
+ nuri = ap_pstrcat(r->pool, url, variant[0].name, r->path_info,
+ r->parsed_uri.query ? "?" : "",
+ r->parsed_uri.query ? r->parsed_uri.query : "",
+ NULL);
+
+ ap_table_setn(r->headers_out, "Location",
+ ap_construct_url(r->pool, nuri, r));
+
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_INFO, r,
+ ref ? "Fixed spelling: %s to %s from %s"
+ : "Fixed spelling: %s to %s",
+ r->uri, nuri, ref);
+
+ return HTTP_MOVED_PERMANENTLY;
+ }
+ /*
+ * Otherwise, a "[300] Multiple Choices" list with the variants is
+ * returned.
+ */
+ else {
+ pool *p;
+ table *notes;
+ pool *sub_pool;
+ array_header *t;
+ array_header *v;
+
+
+ if (r->main == NULL) {
+ p = r->pool;
+ notes = r->notes;
+ }
+ else {
+ p = r->main->pool;
+ notes = r->main->notes;
+ }
+
+ sub_pool = ap_make_sub_pool(p);
+ t = ap_make_array(sub_pool, candidates->nelts * 8 + 8,
+ sizeof(char *));
+ v = ap_make_array(sub_pool, candidates->nelts * 5,
+ sizeof(char *));
+
+ /* Generate the response text. */
+
+ *(const char **)ap_push_array(t) =
+ "The document name you requested (";
+ *(const char **)ap_push_array(t) = r->uri;
+ *(const char **)ap_push_array(t) =
+ " ) could not be found on this server.\n"
+ "However, we found documents with names similar "
+ "to the one you requested."
+ "Available documents:\n \n";
+
+ for (i = 0; i < candidates->nelts; ++i) {
+ char *vuri;
+ const char *reason;
+
+ reason = sp_reason_str[(int) (variant[i].quality)];
+ /* The format isn't very neat... */
+ vuri = ap_pstrcat(sub_pool, url, variant[i].name, r->path_info,
+ (r->parsed_uri.query != NULL) ? "?" : "",
+ (r->parsed_uri.query != NULL)
+ ? r->parsed_uri.query : "",
+ NULL);
+ *(const char **)ap_push_array(v) = "\"";
+ *(const char **)ap_push_array(v) = vuri;
+ *(const char **)ap_push_array(v) = "\";\"";
+ *(const char **)ap_push_array(v) = reason;
+ *(const char **)ap_push_array(v) = "\"";
+
+ *(const char **)ap_push_array(t) = "- ";
+ *(const char **)ap_push_array(t) = vuri;
+ *(const char **)ap_push_array(t) = " (";
+ *(const char **)ap_push_array(t) = reason;
+ *(const char **)ap_push_array(t) = ")\n";
+
+ /*
+ * when we have printed the "close matches" and there are
+ * more "distant matches" (matched by stripping the suffix),
+ * then we insert an additional separator text to suggest
+ * that the user LOOK CLOSELY whether these are really the
+ * files she wanted.
+ */
+ if (i > 0 && i < candidates->nelts - 1
+ && variant[i].quality != SP_VERYDIFFERENT
+ && variant[i + 1].quality == SP_VERYDIFFERENT) {
+ *(const char **)ap_push_array(t) =
+ "
\nFurthermore, the following related "
+ "documents were found:\n\n";
+ }
+ }
+ *(const char **)ap_push_array(t) = " \n";
+
+ /* If we know there was a referring page, add a note: */
+ if (ref != NULL) {
+ *(const char **)ap_push_array(t) =
+ "Please consider informing the owner of the "
+ "referring page "
+ "about the broken link.\n";
+ }
+
+
+ /* Pass our table to http_protocol.c (see mod_negotiation): */
+ ap_table_setn(notes, "variant-list", ap_array_pstrcat(p, t, 0));
+
+ ap_table_mergen(r->subprocess_env, "VARIANTS",
+ ap_array_pstrcat(p, v, ','));
+
+ ap_destroy_pool(sub_pool);
+
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_INFO, r,
+ ref ? "Spelling fix: %s: %d candidates from %s"
+ : "Spelling fix: %s: %d candidates",
+ r->uri, candidates->nelts, ref);
+
+ return HTTP_MULTIPLE_CHOICES;
+ }
+ }
+
+ return OK;
+}
+
+module MODULE_VAR_EXPORT speling_module =
+{
+ STANDARD_MODULE_STUFF,
+ NULL, /* initializer */
+ create_mconfig_for_directory, /* create per-dir config */
+ NULL, /* merge per-dir config */
+ create_mconfig_for_server, /* server config */
+ NULL, /* merge server config */
+ speling_cmds, /* command table */
+ NULL, /* handlers */
+ NULL, /* filename translation */
+ NULL, /* check_user_id */
+ NULL, /* check auth */
+ NULL, /* check access */
+ NULL, /* type_checker */
+ check_speling, /* fixups */
+ NULL, /* logger */
+ NULL, /* header parser */
+ NULL, /* child_init */
+ NULL, /* child_exit */
+ NULL /* post read-request */
+};
diff --git a/modules/mappers/mod_speling.dsp b/modules/mappers/mod_speling.dsp
new file mode 100644
index 00000000000..499a72f3f72
--- /dev/null
+++ b/modules/mappers/mod_speling.dsp
@@ -0,0 +1,113 @@
+# Microsoft Developer Studio Project File - Name="ApacheModuleSpeling" - Package Owner=<4>
+# Microsoft Developer Studio Generated Build File, Format Version 5.00
+# ** DO NOT EDIT **
+
+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102
+
+CFG=ApacheModuleSpeling - Win32 Release
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,
+!MESSAGE use the Export Makefile command and run
+!MESSAGE
+!MESSAGE NMAKE /f "ApacheModuleSpeling.mak".
+!MESSAGE
+!MESSAGE You can specify a configuration when running NMAKE
+!MESSAGE by defining the macro CFG on the command line. For example:
+!MESSAGE
+!MESSAGE NMAKE /f "ApacheModuleSpeling.mak"\
+ CFG="ApacheModuleSpeling - Win32 Release"
+!MESSAGE
+!MESSAGE Possible choices for configuration are:
+!MESSAGE
+!MESSAGE "ApacheModuleSpeling - Win32 Release" (based on\
+ "Win32 (x86) Dynamic-Link Library")
+!MESSAGE "ApacheModuleSpeling - Win32 Debug" (based on\
+ "Win32 (x86) Dynamic-Link Library")
+!MESSAGE
+
+# Begin Project
+# PROP Scc_ProjName ""
+# PROP Scc_LocalPath ""
+CPP=cl.exe
+MTL=midl.exe
+RSC=rc.exe
+
+!IF "$(CFG)" == "ApacheModuleSpeling - Win32 Release"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir ".\Release"
+# PROP BASE Intermediate_Dir ".\Release"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir ".\ApacheModuleSpelingR"
+# PROP Intermediate_Dir ".\ApacheModuleSpelingR"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /c
+# ADD CPP /nologo /MD /W3 /GX /O2 /I "..\..\include" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "SHARED_MODULE" /YX /FD /c
+# ADD BASE MTL /nologo /D "NDEBUG" /win32
+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
+# ADD BASE RSC /l 0x809 /d "NDEBUG"
+# ADD RSC /l 0x809 /d "NDEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /machine:I386
+# ADD LINK32 ..\..\CoreR\ApacheCore.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /dll /machine:I386
+
+!ELSEIF "$(CFG)" == "ApacheModuleSpeling - Win32 Debug"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 1
+# PROP BASE Output_Dir ".\Debug"
+# PROP BASE Intermediate_Dir ".\Debug"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 1
+# PROP Output_Dir ".\ApacheModuleSpelingD"
+# PROP Intermediate_Dir ".\ApacheModuleSpelingD"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /c
+# ADD CPP /nologo /MDd /W3 /Gm /GX /Zi /Od /I "..\..\include" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "SHARED_MODULE" /YX /FD /c
+# ADD BASE MTL /nologo /D "_DEBUG" /win32
+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
+# ADD BASE RSC /l 0x809 /d "_DEBUG"
+# ADD RSC /l 0x809 /d "_DEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /debug /machine:I386
+# ADD LINK32 ..\..\CoreD\ApacheCore.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /dll /debug /machine:I386
+
+!ENDIF
+
+# Begin Target
+
+# Name "ApacheModuleSpeling - Win32 Release"
+# Name "ApacheModuleSpeling - Win32 Debug"
+# Begin Group "Source Files"
+
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;hpj;bat;for;f90"
+# Begin Source File
+
+SOURCE=..\..\modules\standard\mod_speling.c
+# End Source File
+# End Group
+# Begin Group "Header Files"
+
+# PROP Default_Filter "h;hpp;hxx;hm;inl;fi;fd"
+# Begin Source File
+
+SOURCE=.\readdir.h
+# End Source File
+# End Group
+# Begin Group "Resource Files"
+
+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe"
+# End Group
+# End Target
+# End Project
diff --git a/modules/mappers/mod_userdir.c b/modules/mappers/mod_userdir.c
new file mode 100644
index 00000000000..5c0e26d2753
--- /dev/null
+++ b/modules/mappers/mod_userdir.c
@@ -0,0 +1,349 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+/*
+ * mod_userdir... implement the UserDir command. Broken away from the
+ * Alias stuff for a couple of good and not-so-good reasons:
+ *
+ * 1) It shows a real minimal working example of how to do something like
+ * this.
+ * 2) I know people who are actually interested in changing this *particular*
+ * aspect of server functionality without changing the rest of it. That's
+ * what this whole modular arrangement is supposed to be good at...
+ *
+ * Modified by Alexei Kosut to support the following constructs
+ * (server running at www.foo.com, request for /~bar/one/two.html)
+ *
+ * UserDir public_html -> ~bar/public_html/one/two.html
+ * UserDir /usr/web -> /usr/web/bar/one/two.html
+ * UserDir /home/ * /www -> /home/bar/www/one/two.html
+ * NOTE: theses ^ ^ space only added allow it to work in a comment, ignore
+ * UserDir http://x/users -> (302) http://x/users/bar/one/two.html
+ * UserDir http://x/ * /y -> (302) http://x/bar/y/one/two.html
+ * NOTE: here also ^ ^
+ *
+ * In addition, you can use multiple entries, to specify alternate
+ * user directories (a la Directory Index). For example:
+ *
+ * UserDir public_html /usr/web http://www.xyz.com/users
+ *
+ * Modified by Ken Coar to provide for the following:
+ *
+ * UserDir disable[d] username ...
+ * UserDir enable[d] username ...
+ *
+ * If "disabled" has no other arguments, *all* ~ references are
+ * disabled, except those explicitly turned on with the "enabled" keyword.
+ */
+
+#include "httpd.h"
+#include "http_config.h"
+
+module userdir_module;
+
+typedef struct userdir_config {
+ int globally_disabled;
+ char *userdir;
+ table *enabled_users;
+ table *disabled_users;
+} userdir_config;
+
+/*
+ * Server config for this module: global disablement flag, a list of usernames
+ * ineligible for UserDir access, a list of those immune to global (but not
+ * explicit) disablement, and the replacement string for all others.
+ */
+
+static void *create_userdir_config(pool *p, server_rec *s)
+{
+ userdir_config
+ * newcfg = (userdir_config *) ap_pcalloc(p, sizeof(userdir_config));
+
+ newcfg->globally_disabled = 0;
+ newcfg->userdir = DEFAULT_USER_DIR;
+ newcfg->enabled_users = ap_make_table(p, 4);
+ newcfg->disabled_users = ap_make_table(p, 4);
+ return (void *) newcfg;
+}
+
+#define O_DEFAULT 0
+#define O_ENABLE 1
+#define O_DISABLE 2
+
+static const char *set_user_dir(cmd_parms *cmd, void *dummy, char *arg)
+{
+ userdir_config
+ * s_cfg = (userdir_config *) ap_get_module_config
+ (
+ cmd->server->module_config,
+ &userdir_module
+ );
+ char *username;
+ const char
+ *usernames = arg;
+ char *kw = ap_getword_conf(cmd->pool, &usernames);
+ table *usertable;
+
+ /*
+ * Let's do the comparisons once.
+ */
+ if ((!strcasecmp(kw, "disable")) || (!strcasecmp(kw, "disabled"))) {
+ /*
+ * If there are no usernames specified, this is a global disable - we
+ * need do no more at this point than record the fact.
+ */
+ if (strlen(usernames) == 0) {
+ s_cfg->globally_disabled = 1;
+ return NULL;
+ }
+ usertable = s_cfg->disabled_users;
+ }
+ else if ((!strcasecmp(kw, "enable")) || (!strcasecmp(kw, "enabled"))) {
+ /*
+ * The "disable" keyword can stand alone or take a list of names, but
+ * the "enable" keyword requires the list. Whinge if it doesn't have
+ * it.
+ */
+ if (strlen(usernames) == 0) {
+ return "UserDir \"enable\" keyword requires a list of usernames";
+ }
+ usertable = s_cfg->enabled_users;
+ }
+ else {
+ /*
+ * If the first (only?) value isn't one of our keywords, just copy
+ * the string to the userdir string.
+ */
+ s_cfg->userdir = ap_pstrdup(cmd->pool, arg);
+ return NULL;
+ }
+ /*
+ * Now we just take each word in turn from the command line and add it to
+ * the appropriate table.
+ */
+ while (*usernames) {
+ username = ap_getword_conf(cmd->pool, &usernames);
+ ap_table_setn(usertable, username, kw);
+ }
+ return NULL;
+}
+
+static const command_rec userdir_cmds[] = {
+ {"UserDir", set_user_dir, NULL, RSRC_CONF, RAW_ARGS,
+ "the public subdirectory in users' home directories, or 'disabled', or 'disabled username username...', or 'enabled username username...'"},
+ {NULL}
+};
+
+static int translate_userdir(request_rec *r)
+{
+ void *server_conf = r->server->module_config;
+ const userdir_config *s_cfg =
+ (userdir_config *) ap_get_module_config(server_conf, &userdir_module);
+ char *name = r->uri;
+ const char *userdirs = s_cfg->userdir;
+ const char *w, *dname;
+ char *redirect;
+ char *x = NULL;
+ struct stat statbuf;
+
+ /*
+ * If the URI doesn't match our basic pattern, we've nothing to do with
+ * it.
+ */
+ if (
+ (s_cfg->userdir == NULL) ||
+ (name[0] != '/') ||
+ (name[1] != '~')
+ ) {
+ return DECLINED;
+ }
+
+ dname = name + 2;
+ w = ap_getword(r->pool, &dname, '/');
+
+ /*
+ * The 'dname' funny business involves backing it up to capture the '/'
+ * delimiting the "/~user" part from the rest of the URL, in case there
+ * was one (the case where there wasn't being just "GET /~user HTTP/1.0",
+ * for which we don't want to tack on a '/' onto the filename).
+ */
+
+ if (dname[-1] == '/') {
+ --dname;
+ }
+
+ /*
+ * If there's no username, it's not for us. Ignore . and .. as well.
+ */
+ if (w[0] == '\0' || (w[1] == '.' && (w[2] == '\0' || (w[2] == '.' && w[3] == '\0')))) {
+ return DECLINED;
+ }
+ /*
+ * Nor if there's an username but it's in the disabled list.
+ */
+ if (ap_table_get(s_cfg->disabled_users, w) != NULL) {
+ return DECLINED;
+ }
+ /*
+ * If there's a global interdiction on UserDirs, check to see if this
+ * name is one of the Blessed.
+ */
+ if (
+ s_cfg->globally_disabled &&
+ (ap_table_get(s_cfg->enabled_users, w) == NULL)
+ ) {
+ return DECLINED;
+ }
+
+ /*
+ * Special cases all checked, onward to normal substitution processing.
+ */
+
+ while (*userdirs) {
+ const char *userdir = ap_getword_conf(r->pool, &userdirs);
+ char *filename = NULL;
+
+ if (strchr(userdir, '*'))
+ x = ap_getword(r->pool, &userdir, '*');
+
+ if (userdir[0] == '\0' || ap_os_is_path_absolute(userdir)) {
+ if (x) {
+#ifdef HAVE_DRIVE_LETTERS
+ /*
+ * Crummy hack. Need to figure out whether we have been
+ * redirected to a URL or to a file on some drive. Since I
+ * know of no protocols that are a single letter, if the : is
+ * the second character, I will assume a file was specified
+ */
+ if (strchr(x + 2, ':'))
+#else
+ if (strchr(x, ':'))
+#endif /* WIN32 */
+ {
+ redirect = ap_pstrcat(r->pool, x, w, userdir, dname, NULL);
+ ap_table_setn(r->headers_out, "Location", redirect);
+ return REDIRECT;
+ }
+ else
+ filename = ap_pstrcat(r->pool, x, w, userdir, NULL);
+ }
+ else
+ filename = ap_pstrcat(r->pool, userdir, "/", w, NULL);
+ }
+ else if (strchr(userdir, ':')) {
+ redirect = ap_pstrcat(r->pool, userdir, "/", w, dname, NULL);
+ ap_table_setn(r->headers_out, "Location", redirect);
+ return REDIRECT;
+ }
+ else {
+#ifdef WIN32
+ /* Need to figure out home dirs on NT */
+ return DECLINED;
+#else /* WIN32 */
+ struct passwd *pw;
+ if ((pw = getpwnam(w))) {
+#ifdef OS2
+ /* Need to manually add user name for OS/2 */
+ filename = ap_pstrcat(r->pool, pw->pw_dir, w, "/", userdir, NULL);
+#else
+ filename = ap_pstrcat(r->pool, pw->pw_dir, "/", userdir, NULL);
+#endif
+ }
+#endif /* WIN32 */
+ }
+
+ /*
+ * Now see if it exists, or we're at the last entry. If we are at the
+ * last entry, then use the filename generated (if there is one)
+ * anyway, in the hope that some handler might handle it. This can be
+ * used, for example, to run a CGI script for the user.
+ */
+ if (filename && (!*userdirs || stat(filename, &statbuf) != -1)) {
+ r->filename = ap_pstrcat(r->pool, filename, dname, NULL);
+ /* when statbuf contains info on r->filename we can save a syscall
+ * by copying it to r->finfo
+ */
+ if (*userdirs && dname[0] == 0)
+ r->finfo = statbuf;
+ return OK;
+ }
+ }
+
+ return DECLINED;
+}
+
+module userdir_module = {
+ STANDARD_MODULE_STUFF,
+ NULL, /* initializer */
+ NULL, /* dir config creater */
+ NULL, /* dir merger --- default is to override */
+ create_userdir_config, /* server config */
+ NULL, /* merge server config */
+ userdir_cmds, /* command table */
+ NULL, /* handlers */
+ translate_userdir, /* filename translation */
+ NULL, /* check_user_id */
+ NULL, /* check auth */
+ NULL, /* check access */
+ NULL, /* type_checker */
+ NULL, /* fixups */
+ NULL, /* logger */
+ NULL, /* header parser */
+ NULL, /* child_init */
+ NULL, /* child_exit */
+ NULL /* post read-request */
+};
diff --git a/modules/mappers/mod_vhost_alias.c b/modules/mappers/mod_vhost_alias.c
new file mode 100644
index 00000000000..65cc5a2ef41
--- /dev/null
+++ b/modules/mappers/mod_vhost_alias.c
@@ -0,0 +1,482 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+/*
+ * mod_vhost_alias.c: support for dynamically configured mass virtual hosting
+ *
+ * Copyright (c) 1998-1999 Demon Internet Ltd.
+ *
+ * This software was submitted by Demon Internet to the Apache Group
+ * in May 1999. Future revisions and derivatives of this source code
+ * must acknowledge Demon Internet as the original contributor of
+ * this module. All other licensing and usage conditions are those
+ * of the Apache Group.
+ *
+ * Originally written by Tony Finch .
+ *
+ * Implementation ideas were taken from mod_alias.c. The overall
+ * concept is derived from the OVERRIDE_DOC_ROOT/OVERRIDE_CGIDIR
+ * patch to Apache 1.3b3 and a similar feature in Demon's thttpd,
+ * both written by James Grinter .
+ */
+
+#include "httpd.h"
+#include "http_config.h"
+#include "http_core.h"
+
+
+module MODULE_VAR_EXPORT vhost_alias_module;
+
+
+/*
+ * basic configuration things
+ * we abbreviate "mod_vhost_alias" to "mva" for shorter names
+ */
+
+typedef enum {
+ VHOST_ALIAS_UNSET, VHOST_ALIAS_NONE, VHOST_ALIAS_NAME, VHOST_ALIAS_IP
+} mva_mode_e;
+
+/*
+ * Per-server module config record.
+ */
+typedef struct mva_sconf_t {
+ char *doc_root;
+ char *cgi_root;
+ mva_mode_e doc_root_mode;
+ mva_mode_e cgi_root_mode;
+} mva_sconf_t;
+
+static void *mva_create_server_config(pool *p, server_rec *s)
+{
+ mva_sconf_t *conf;
+
+ conf = (mva_sconf_t *) ap_pcalloc(p, sizeof(mva_sconf_t));
+ conf->doc_root = NULL;
+ conf->cgi_root = NULL;
+ conf->doc_root_mode = VHOST_ALIAS_UNSET;
+ conf->cgi_root_mode = VHOST_ALIAS_UNSET;
+ return conf;
+}
+
+static void *mva_merge_server_config(pool *p, void *parentv, void *childv)
+{
+ mva_sconf_t *parent = (mva_sconf_t *) parentv;
+ mva_sconf_t *child = (mva_sconf_t *) childv;
+ mva_sconf_t *conf;
+
+ conf = (mva_sconf_t *) ap_pcalloc(p, sizeof(*conf));
+ if (child->doc_root_mode == VHOST_ALIAS_UNSET) {
+ conf->doc_root_mode = parent->doc_root_mode;
+ conf->doc_root = parent->doc_root;
+ }
+ else {
+ conf->doc_root_mode = child->doc_root_mode;
+ conf->doc_root = child->doc_root;
+ }
+ if (child->cgi_root_mode == VHOST_ALIAS_UNSET) {
+ conf->cgi_root_mode = parent->cgi_root_mode;
+ conf->cgi_root = parent->cgi_root;
+ }
+ else {
+ conf->cgi_root_mode = child->cgi_root_mode;
+ conf->cgi_root = child->cgi_root;
+ }
+ return conf;
+}
+
+
+/*
+ * These are just here to tell us what vhost_alias_set should do.
+ * We don't put anything into them; we just use the cell addresses.
+ */
+static int vhost_alias_set_doc_root_ip,
+ vhost_alias_set_cgi_root_ip,
+ vhost_alias_set_doc_root_name,
+ vhost_alias_set_cgi_root_name;
+
+static const char *vhost_alias_set(cmd_parms *cmd, void *dummy, char *map)
+{
+ mva_sconf_t *conf;
+ mva_mode_e mode, *pmode;
+ char **pmap;
+ char *p;
+
+ conf = (mva_sconf_t *) ap_get_module_config(cmd->server->module_config,
+ &vhost_alias_module);
+ /* there ought to be a better way of doing this */
+ if (&vhost_alias_set_doc_root_ip == cmd->info) {
+ mode = VHOST_ALIAS_IP;
+ pmap = &conf->doc_root;
+ pmode = &conf->doc_root_mode;
+ }
+ else if (&vhost_alias_set_cgi_root_ip == cmd->info) {
+ mode = VHOST_ALIAS_IP;
+ pmap = &conf->cgi_root;
+ pmode = &conf->cgi_root_mode;
+ }
+ else if (&vhost_alias_set_doc_root_name == cmd->info) {
+ mode = VHOST_ALIAS_NAME;
+ pmap = &conf->doc_root;
+ pmode = &conf->doc_root_mode;
+ }
+ else if (&vhost_alias_set_cgi_root_name == cmd->info) {
+ mode = VHOST_ALIAS_NAME;
+ pmap = &conf->cgi_root;
+ pmode = &conf->cgi_root_mode;
+ }
+ else {
+ return "INTERNAL ERROR: unknown command info";
+ }
+
+ if (*map != '/') {
+ if (strcasecmp(map, "none")) {
+ return "format string must start with '/' or be 'none'";
+ }
+ *pmap = NULL;
+ *pmode = VHOST_ALIAS_NONE;
+ return NULL;
+ }
+
+ /* sanity check */
+ p = map;
+ while (*p != '\0') {
+ if (*p++ != '%') {
+ continue;
+ }
+ /* we just found a '%' */
+ if (*p == 'p' || *p == '%') {
+ ++p;
+ continue;
+ }
+ /* optional dash */
+ if (*p == '-') {
+ ++p;
+ }
+ /* digit N */
+ if (ap_isdigit(*p)) {
+ ++p;
+ }
+ else {
+ return "syntax error in format string";
+ }
+ /* optional plus */
+ if (*p == '+') {
+ ++p;
+ }
+ /* do we end here? */
+ if (*p != '.') {
+ continue;
+ }
+ ++p;
+ /* optional dash */
+ if (*p == '-') {
+ ++p;
+ }
+ /* digit M */
+ if (ap_isdigit(*p)) {
+ ++p;
+ }
+ else {
+ return "syntax error in format string";
+ }
+ /* optional plus */
+ if (*p == '+') {
+ ++p;
+ }
+ }
+ *pmap = map;
+ *pmode = mode;
+ return NULL;
+}
+
+static const command_rec mva_commands[] =
+{
+ {"VirtualScriptAlias", vhost_alias_set, &vhost_alias_set_cgi_root_name,
+ RSRC_CONF, TAKE1, "how to create a ScriptAlias based on the host"},
+ {"VirtualDocumentRoot", vhost_alias_set, &vhost_alias_set_doc_root_name,
+ RSRC_CONF, TAKE1, "how to create the DocumentRoot based on the host"},
+ {"VirtualScriptAliasIP", vhost_alias_set, &vhost_alias_set_cgi_root_ip,
+ RSRC_CONF, TAKE1, "how to create a ScriptAlias based on the host"},
+ {"VirtualDocumentRootIP", vhost_alias_set, &vhost_alias_set_doc_root_ip,
+ RSRC_CONF, TAKE1, "how to create the DocumentRoot based on the host"},
+ { NULL }
+};
+
+
+/*
+ * This really wants to be a nested function
+ * but C is too feeble to support them.
+ */
+static ap_inline void vhost_alias_checkspace(request_rec *r, char *buf,
+ char **pdest, int size)
+{
+ /* XXX: what if size > HUGE_STRING_LEN? */
+ if (*pdest + size > buf + HUGE_STRING_LEN) {
+ **pdest = '\0';
+ if (r->filename) {
+ r->filename = ap_pstrcat(r->pool, r->filename, buf, NULL);
+ }
+ else {
+ r->filename = ap_pstrdup(r->pool, buf);
+ }
+ *pdest = buf;
+ }
+}
+
+static void vhost_alias_interpolate(request_rec *r, const char *name,
+ const char *map, const char *uri)
+{
+ /* 0..9 9..0 */
+ enum { MAXDOTS = 19 };
+ const char *dots[MAXDOTS+1];
+ int ndots;
+
+ char buf[HUGE_STRING_LEN];
+ char *dest, last;
+
+ int N, M, Np, Mp, Nd, Md;
+ const char *start, *end;
+
+ const char *p;
+
+ ndots = 0;
+ dots[ndots++] = name-1; /* slightly naughty */
+ for (p = name; *p; ++p){
+ if (*p == '.' && ndots < MAXDOTS) {
+ dots[ndots++] = p;
+ }
+ }
+ dots[ndots] = p;
+
+ r->filename = NULL;
+
+ dest = buf;
+ last = '\0';
+ while (*map) {
+ if (*map != '%') {
+ /* normal characters */
+ vhost_alias_checkspace(r, buf, &dest, 1);
+ last = *dest++ = *map++;
+ continue;
+ }
+ /* we are in a format specifier */
+ ++map;
+ /* can't be a slash */
+ last = '\0';
+ /* %% -> % */
+ if (*map == '%') {
+ ++map;
+ vhost_alias_checkspace(r, buf, &dest, 1);
+ *dest++ = '%';
+ continue;
+ }
+ /* port number */
+ if (*map == 'p') {
+ ++map;
+ /* no. of decimal digits in a short plus one */
+ vhost_alias_checkspace(r, buf, &dest, 7);
+ dest += ap_snprintf(dest, 7, "%d", ap_get_server_port(r));
+ continue;
+ }
+ /* deal with %-N+.-M+ -- syntax is already checked */
+ N = M = 0; /* value */
+ Np = Mp = 0; /* is there a plus? */
+ Nd = Md = 0; /* is there a dash? */
+ if (*map == '-') ++map, Nd = 1;
+ N = *map++ - '0';
+ if (*map == '+') ++map, Np = 1;
+ if (*map == '.') {
+ ++map;
+ if (*map == '-') {
+ ++map, Md = 1;
+ }
+ M = *map++ - '0';
+ if (*map == '+') {
+ ++map, Mp = 1;
+ }
+ }
+ /* note that N and M are one-based indices, not zero-based */
+ start = dots[0]+1; /* ptr to the first character */
+ end = dots[ndots]; /* ptr to the character after the last one */
+ if (N != 0) {
+ if (N > ndots) {
+ start = "_";
+ end = start+1;
+ }
+ else if (!Nd) {
+ start = dots[N-1]+1;
+ if (!Np) {
+ end = dots[N];
+ }
+ }
+ else {
+ if (!Np) {
+ start = dots[ndots-N]+1;
+ }
+ end = dots[ndots-N+1];
+ }
+ }
+ if (M != 0) {
+ if (M > end - start) {
+ start = "_";
+ end = start+1;
+ }
+ else if (!Md) {
+ start = start+M-1;
+ if (!Mp) {
+ end = start+1;
+ }
+ }
+ else {
+ if (!Mp) {
+ start = end-M;
+ }
+ end = end-M+1;
+ }
+ }
+ vhost_alias_checkspace(r, buf, &dest, end - start);
+ for (p = start; p < end; ++p) {
+ *dest++ = ap_tolower(*p);
+ }
+ }
+ *dest = '\0';
+ /* no double slashes */
+ if (last == '/') {
+ ++uri;
+ }
+ if (r->filename) {
+ r->filename = ap_pstrcat(r->pool, r->filename, buf, uri, NULL);
+ }
+ else {
+ r->filename = ap_pstrcat(r->pool, buf, uri, NULL);
+ }
+}
+
+static int mva_translate(request_rec *r)
+{
+ mva_sconf_t *conf;
+ const char *name, *map, *uri;
+ mva_mode_e mode;
+ int cgi;
+
+ conf = (mva_sconf_t *) ap_get_module_config(r->server->module_config,
+ &vhost_alias_module);
+ if (!strncmp(r->uri, "/cgi-bin/", 9)) {
+ mode = conf->cgi_root_mode;
+ map = conf->cgi_root;
+ uri = r->uri + 8;
+ /*
+ * can't force cgi immediately because we might not handle this
+ * call if the mode is wrong
+ */
+ cgi = 1;
+ }
+ else if (r->uri[0] == '/') {
+ mode = conf->doc_root_mode;
+ map = conf->doc_root;
+ uri = r->uri;
+ cgi = 0;
+ }
+ else {
+ return DECLINED;
+ }
+
+ if (mode == VHOST_ALIAS_NAME) {
+ name = ap_get_server_name(r);
+ }
+ else if (mode == VHOST_ALIAS_IP) {
+ name = r->connection->local_ip;
+ }
+ else {
+ return DECLINED;
+ }
+
+ vhost_alias_interpolate(r, name, map, uri);
+
+ if (cgi) {
+ /* see is_scriptaliased() in mod_cgi */
+ r->handler = "cgi-script";
+ ap_table_setn(r->notes, "alias-forced-type", r->handler);
+ }
+
+ return OK;
+}
+
+
+module MODULE_VAR_EXPORT vhost_alias_module =
+{
+ STANDARD_MODULE_STUFF,
+ NULL, /* initializer */
+ NULL, /* dir config creater */
+ NULL, /* dir merger --- default is to override */
+ mva_create_server_config, /* server config */
+ mva_merge_server_config, /* merge server configs */
+ mva_commands, /* command table */
+ NULL, /* handlers */
+ mva_translate, /* filename translation */
+ NULL, /* check_user_id */
+ NULL, /* check auth */
+ NULL, /* check access */
+ NULL, /* type_checker */
+ NULL, /* fixups */
+ NULL, /* logger */
+ NULL, /* header parser */
+ NULL, /* child_init */
+ NULL, /* child_exit */
+ NULL /* post read-request */
+};
diff --git a/modules/metadata/.indent.pro b/modules/metadata/.indent.pro
new file mode 100644
index 00000000000..a9fbe9f9a1f
--- /dev/null
+++ b/modules/metadata/.indent.pro
@@ -0,0 +1,54 @@
+-i4 -npsl -di0 -br -nce -d0 -cli0 -npcs -nfc1
+-TBUFF
+-TFILE
+-TTRANS
+-TUINT4
+-T_trans
+-Tallow_options_t
+-Tapache_sfio
+-Tarray_header
+-Tbool_int
+-Tbuf_area
+-Tbuff_struct
+-Tbuffy
+-Tcmd_how
+-Tcmd_parms
+-Tcommand_rec
+-Tcommand_struct
+-Tconn_rec
+-Tcore_dir_config
+-Tcore_server_config
+-Tdir_maker_func
+-Tevent
+-Tglobals_s
+-Thandler_func
+-Thandler_rec
+-Tjoblist_s
+-Tlisten_rec
+-Tmerger_func
+-Tmode_t
+-Tmodule
+-Tmodule_struct
+-Tmutex
+-Tn_long
+-Tother_child_rec
+-Toverrides_t
+-Tparent_score
+-Tpid_t
+-Tpiped_log
+-Tpool
+-Trequest_rec
+-Trequire_line
+-Trlim_t
+-Tscoreboard
+-Tsemaphore
+-Tserver_addr_rec
+-Tserver_rec
+-Tserver_rec_chain
+-Tshort_score
+-Ttable
+-Ttable_entry
+-Tthread
+-Tu_wide_int
+-Tvtime_t
+-Twide_int
diff --git a/modules/metadata/mod_cern_meta.c b/modules/metadata/mod_cern_meta.c
new file mode 100644
index 00000000000..dbc1de6cabb
--- /dev/null
+++ b/modules/metadata/mod_cern_meta.c
@@ -0,0 +1,395 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * IT'S CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+/*
+ * mod_cern_meta.c
+ * version 0.1.0
+ * status beta
+ *
+ * Andrew Wilson 25.Jan.96
+ *
+ * *** IMPORTANT ***
+ * This version of mod_cern_meta.c controls Meta File behaviour on a
+ * per-directory basis. Previous versions of the module defined behaviour
+ * on a per-server basis. The upshot is that you'll need to revisit your
+ * configuration files in order to make use of the new module.
+ * ***
+ *
+ * Emulate the CERN HTTPD Meta file semantics. Meta files are HTTP
+ * headers that can be output in addition to the normal range of
+ * headers for each file accessed. They appear rather like the Apache
+ * .asis files, and are able to provide a crude way of influencing
+ * the Expires: header, as well as providing other curiosities.
+ * There are many ways to manage meta information, this one was
+ * chosen because there is already a large number of CERN users
+ * who can exploit this module. It should be noted that there are probably
+ * more sensitive ways of managing the Expires: header specifically.
+ *
+ * The module obeys the following directives, which can appear
+ * in the server's .conf files and in .htaccess files.
+ *
+ * MetaFiles
+ *
+ * turns on|off meta file processing for any directory.
+ * Default value is off
+ *
+ * # turn on MetaFiles in this directory
+ * MetaFiles on
+ *
+ * MetaDir
+ *
+ * specifies the name of the directory in which Apache can find
+ * meta information files. The directory is usually a 'hidden'
+ * subdirectory of the directory that contains the file being
+ * accessed. eg:
+ *
+ * # .meta files are in the *same* directory as the
+ * # file being accessed
+ * MetaDir .
+ *
+ * the default is to look in a '.web' subdirectory. This is the
+ * same as for CERN 3.+ webservers and behaviour is the same as
+ * for the directive:
+ *
+ * MetaDir .web
+ *
+ * MetaSuffix
+ *
+ * specifies the file name suffix for the file containing the
+ * meta information. eg:
+ *
+ * # our meta files are suffixed with '.cern_meta'
+ * MetaSuffix .cern_meta
+ *
+ * the default is to look for files with the suffix '.meta'. This
+ * behaviour is the same as for the directive:
+ *
+ * MetaSuffix .meta
+ *
+ * When accessing the file
+ *
+ * DOCUMENT_ROOT/somedir/index.html
+ *
+ * this module will look for the file
+ *
+ * DOCUMENT_ROOT/somedir/.web/index.html.meta
+ *
+ * and will use its contents to generate additional MIME header
+ * information.
+ *
+ * For more information on the CERN Meta file semantics see:
+ *
+ * http://www.w3.org/hypertext/WWW/Daemon/User/Config/General.html#MetaDir
+ *
+ * Change-log:
+ * 29.Jan.96 pfopen/pfclose instead of fopen/fclose
+ * DECLINE when real file not found, we may be checking each
+ * of the index.html/index.shtml/index.htm variants and don't
+ * need to report missing ones as spurious errors.
+ * 31.Jan.96 log_error reports about a malformed .meta file, rather
+ * than a script error.
+ * 20.Jun.96 MetaFiles default off, added, so that module
+ * can be configured per-directory. Prior to this the module
+ * was running for each request anywhere on the server, naughty..
+ * 29.Jun.96 All directives made per-directory.
+ */
+
+#include "httpd.h"
+#include "http_config.h"
+#include
+#include
+#include "util_script.h"
+#include "http_log.h"
+#include "http_request.h"
+
+#define DIR_CMD_PERMS OR_INDEXES
+
+#define DEFAULT_METADIR ".web"
+#define DEFAULT_METASUFFIX ".meta"
+#define DEFAULT_METAFILES 0
+
+module MODULE_VAR_EXPORT cern_meta_module;
+
+typedef struct {
+ char *metadir;
+ char *metasuffix;
+ char *metafiles;
+} cern_meta_dir_config;
+
+static void *create_cern_meta_dir_config(pool *p, char *dummy)
+{
+ cern_meta_dir_config *new =
+ (cern_meta_dir_config *) ap_palloc(p, sizeof(cern_meta_dir_config));
+
+ new->metadir = NULL;
+ new->metasuffix = NULL;
+ new->metafiles = DEFAULT_METAFILES;
+
+ return new;
+}
+
+static void *merge_cern_meta_dir_configs(pool *p, void *basev, void *addv)
+{
+ cern_meta_dir_config *base = (cern_meta_dir_config *) basev;
+ cern_meta_dir_config *add = (cern_meta_dir_config *) addv;
+ cern_meta_dir_config *new =
+ (cern_meta_dir_config *) ap_palloc(p, sizeof(cern_meta_dir_config));
+
+ new->metadir = add->metadir ? add->metadir : base->metadir;
+ new->metasuffix = add->metasuffix ? add->metasuffix : base->metasuffix;
+ new->metafiles = add->metafiles;
+
+ return new;
+}
+
+static const char *set_metadir(cmd_parms *parms, cern_meta_dir_config * dconf, char *arg)
+{
+ dconf->metadir = arg;
+ return NULL;
+}
+
+static const char *set_metasuffix(cmd_parms *parms, cern_meta_dir_config * dconf, char *arg)
+{
+ dconf->metasuffix = arg;
+ return NULL;
+}
+
+static const char *set_metafiles(cmd_parms *parms, cern_meta_dir_config * dconf, char *arg)
+{
+ dconf->metafiles = arg;
+ return NULL;
+}
+
+
+static const command_rec cern_meta_cmds[] =
+{
+ {"MetaFiles", set_metafiles, NULL, DIR_CMD_PERMS, FLAG,
+ "Limited to 'on' or 'off'"},
+ {"MetaDir", set_metadir, NULL, DIR_CMD_PERMS, TAKE1,
+ "the name of the directory containing meta files"},
+ {"MetaSuffix", set_metasuffix, NULL, DIR_CMD_PERMS, TAKE1,
+ "the filename suffix for meta files"},
+ {NULL}
+};
+
+/* XXX: this is very similar to ap_scan_script_header_err_core...
+ * are the differences deliberate, or just a result of bit rot?
+ */
+static int scan_meta_file(request_rec *r, FILE *f)
+{
+ char w[MAX_STRING_LEN];
+ char *l;
+ int p;
+ table *tmp_headers;
+
+ tmp_headers = ap_make_table(r->pool, 5);
+ while (fgets(w, MAX_STRING_LEN - 1, f) != NULL) {
+
+ /* Delete terminal (CR?)LF */
+
+ p = strlen(w);
+ if (p > 0 && w[p - 1] == '\n') {
+ if (p > 1 && w[p - 2] == '\015')
+ w[p - 2] = '\0';
+ else
+ w[p - 1] = '\0';
+ }
+
+ if (w[0] == '\0') {
+ return OK;
+ }
+
+ /* if we see a bogus header don't ignore it. Shout and scream */
+
+ if (!(l = strchr(w, ':'))) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "malformed header in meta file: %s", r->filename);
+ return SERVER_ERROR;
+ }
+
+ *l++ = '\0';
+ while (*l && ap_isspace(*l))
+ ++l;
+
+ if (!strcasecmp(w, "Content-type")) {
+ char *tmp;
+ /* Nuke trailing whitespace */
+
+ char *endp = l + strlen(l) - 1;
+ while (endp > l && ap_isspace(*endp))
+ *endp-- = '\0';
+
+ tmp = ap_pstrdup(r->pool, l);
+ ap_content_type_tolower(tmp);
+ r->content_type = tmp;
+ }
+ else if (!strcasecmp(w, "Status")) {
+ sscanf(l, "%d", &r->status);
+ r->status_line = ap_pstrdup(r->pool, l);
+ }
+ else {
+ ap_table_set(tmp_headers, w, l);
+ }
+ }
+ ap_overlap_tables(r->headers_out, tmp_headers, AP_OVERLAP_TABLES_SET);
+ return OK;
+}
+
+static int add_cern_meta_data(request_rec *r)
+{
+ char *metafilename;
+ char *last_slash;
+ char *real_file;
+ char *scrap_book;
+ FILE *f;
+ cern_meta_dir_config *dconf;
+ int rv;
+ request_rec *rr;
+
+ dconf = ap_get_module_config(r->per_dir_config, &cern_meta_module);
+
+ if (!dconf->metafiles) {
+ return DECLINED;
+ };
+
+ /* if ./.web/$1.meta exists then output 'asis' */
+
+ if (r->finfo.st_mode == 0) {
+ return DECLINED;
+ };
+
+ /* is this a directory? */
+ if (S_ISDIR(r->finfo.st_mode) || r->uri[strlen(r->uri) - 1] == '/') {
+ return DECLINED;
+ };
+
+ /* what directory is this file in? */
+ scrap_book = ap_pstrdup(r->pool, r->filename);
+ /* skip leading slash, recovered in later processing */
+ scrap_book++;
+ last_slash = strrchr(scrap_book, '/');
+ if (last_slash != NULL) {
+ /* skip over last slash */
+ real_file = last_slash;
+ real_file++;
+ *last_slash = '\0';
+ }
+ else {
+ /* no last slash, buh?! */
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "internal error in mod_cern_meta: %s", r->filename);
+ /* should really barf, but hey, let's be friends... */
+ return DECLINED;
+ };
+
+ metafilename = ap_pstrcat(r->pool, "/", scrap_book, "/",
+ dconf->metadir ? dconf->metadir : DEFAULT_METADIR,
+ "/", real_file,
+ dconf->metasuffix ? dconf->metasuffix : DEFAULT_METASUFFIX,
+ NULL);
+
+ /* XXX: it sucks to require this subrequest to complete, because this
+ * means people must leave their meta files accessible to the world.
+ * A better solution might be a "safe open" feature of pfopen to avoid
+ * pipes, symlinks, and crap like that.
+ */
+ rr = ap_sub_req_lookup_file(metafilename, r);
+ if (rr->status != HTTP_OK) {
+ ap_destroy_sub_req(rr);
+ return DECLINED;
+ }
+ ap_destroy_sub_req(rr);
+
+ f = ap_pfopen(r->pool, metafilename, "r");
+ if (f == NULL) {
+ if (errno == ENOENT) {
+ return DECLINED;
+ }
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
+ "meta file permissions deny server access: %s", metafilename);
+ return FORBIDDEN;
+ };
+
+ /* read the headers in */
+ rv = scan_meta_file(r, f);
+ ap_pfclose(r->pool, f);
+
+ return rv;
+}
+
+module MODULE_VAR_EXPORT cern_meta_module =
+{
+ STANDARD_MODULE_STUFF,
+ NULL, /* initializer */
+ create_cern_meta_dir_config, /* dir config creater */
+ merge_cern_meta_dir_configs, /* dir merger --- default is to override */
+ NULL, /* server config */
+ NULL, /* merge server configs */
+ cern_meta_cmds, /* command table */
+ NULL, /* handlers */
+ NULL, /* filename translation */
+ NULL, /* check_user_id */
+ NULL, /* check auth */
+ NULL, /* check access */
+ NULL, /* type_checker */
+ add_cern_meta_data, /* fixups */
+ NULL, /* logger */
+ NULL, /* header parser */
+ NULL, /* child_init */
+ NULL, /* child_exit */
+ NULL /* post read-request */
+};
diff --git a/modules/metadata/mod_cern_meta.dsp b/modules/metadata/mod_cern_meta.dsp
new file mode 100644
index 00000000000..3564c0e2ef6
--- /dev/null
+++ b/modules/metadata/mod_cern_meta.dsp
@@ -0,0 +1,113 @@
+# Microsoft Developer Studio Project File - Name="ApacheModuleCERNMeta" - Package Owner=<4>
+# Microsoft Developer Studio Generated Build File, Format Version 5.00
+# ** DO NOT EDIT **
+
+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102
+
+CFG=ApacheModuleCERNMeta - Win32 Release
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,
+!MESSAGE use the Export Makefile command and run
+!MESSAGE
+!MESSAGE NMAKE /f "ApacheModuleCERNMeta.mak".
+!MESSAGE
+!MESSAGE You can specify a configuration when running NMAKE
+!MESSAGE by defining the macro CFG on the command line. For example:
+!MESSAGE
+!MESSAGE NMAKE /f "ApacheModuleCERNMeta.mak"\
+ CFG="ApacheModuleCERNMeta - Win32 Release"
+!MESSAGE
+!MESSAGE Possible choices for configuration are:
+!MESSAGE
+!MESSAGE "ApacheModuleCERNMeta - Win32 Release" (based on\
+ "Win32 (x86) Dynamic-Link Library")
+!MESSAGE "ApacheModuleCERNMeta - Win32 Debug" (based on\
+ "Win32 (x86) Dynamic-Link Library")
+!MESSAGE
+
+# Begin Project
+# PROP Scc_ProjName ""
+# PROP Scc_LocalPath ""
+CPP=cl.exe
+MTL=midl.exe
+RSC=rc.exe
+
+!IF "$(CFG)" == "ApacheModuleCERNMeta - Win32 Release"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir ".\Release"
+# PROP BASE Intermediate_Dir ".\Release"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir ".\ApacheModuleCERNMetaR"
+# PROP Intermediate_Dir ".\ApacheModuleCERNMetaR"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /c
+# ADD CPP /nologo /MD /W3 /GX /O2 /I "..\..\include" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "SHARED_MODULE" /YX /FD /c
+# ADD BASE MTL /nologo /D "NDEBUG" /win32
+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
+# ADD BASE RSC /l 0x809 /d "NDEBUG"
+# ADD RSC /l 0x809 /d "NDEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /machine:I386
+# ADD LINK32 ..\..\CoreR\ApacheCore.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /dll /machine:I386
+
+!ELSEIF "$(CFG)" == "ApacheModuleCERNMeta - Win32 Debug"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 1
+# PROP BASE Output_Dir ".\Debug"
+# PROP BASE Intermediate_Dir ".\Debug"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 1
+# PROP Output_Dir ".\ApacheModuleCERNMetaD"
+# PROP Intermediate_Dir ".\ApacheModuleCERNMetaD"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /c
+# ADD CPP /nologo /MDd /W3 /Gm /GX /Zi /Od /I "..\..\include" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "SHARED_MODULE" /YX /FD /c
+# ADD BASE MTL /nologo /D "_DEBUG" /win32
+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
+# ADD BASE RSC /l 0x809 /d "_DEBUG"
+# ADD RSC /l 0x809 /d "_DEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /debug /machine:I386
+# ADD LINK32 ..\..\CoreD\ApacheCore.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /dll /debug /machine:I386
+
+!ENDIF
+
+# Begin Target
+
+# Name "ApacheModuleCERNMeta - Win32 Release"
+# Name "ApacheModuleCERNMeta - Win32 Debug"
+# Begin Group "Source Files"
+
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;hpj;bat;for;f90"
+# Begin Source File
+
+SOURCE=..\..\modules\standard\mod_cern_meta.c
+# End Source File
+# End Group
+# Begin Group "Header Files"
+
+# PROP Default_Filter "h;hpp;hxx;hm;inl;fi;fd"
+# Begin Source File
+
+SOURCE=.\readdir.h
+# End Source File
+# End Group
+# Begin Group "Resource Files"
+
+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe"
+# End Group
+# End Target
+# End Project
diff --git a/modules/metadata/mod_env.c b/modules/metadata/mod_env.c
new file mode 100644
index 00000000000..351a48712b0
--- /dev/null
+++ b/modules/metadata/mod_env.c
@@ -0,0 +1,270 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * IT'S CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+/*
+ * mod_env.c
+ * version 0.0.5
+ * status beta
+ * Pass environment variables to CGI/SSI scripts.
+ *
+ * Andrew Wilson 06.Dec.95
+ *
+ * Change log:
+ * 08.Dec.95 Now allows PassEnv directive to appear more than once in
+ * conf files.
+ * 10.Dec.95 optimisation. getenv() only called at startup and used
+ * to build a fast-to-access table. table used to build
+ * per-server environment for each request.
+ * robustness. better able to handle errors in configuration
+ * files:
+ * 1) PassEnv directive present, but no environment variable listed
+ * 2) PassEnv FOO present, but $FOO not present in environment
+ * 3) no PassEnv directive present
+ * 23.Dec.95 Now allows SetEnv directive with same semantics as 'sh' setenv:
+ * SetEnv Var sets Var to the empty string
+ * SetEnv Var Val sets Var to the value Val
+ * Values containing whitespace should be quoted, eg:
+ * SetEnv Var "this is some text"
+ * Environment variables take their value from the last instance
+ * of PassEnv / SetEnv to be reached in the configuration file.
+ * For example, the sequence:
+ * PassEnv FOO
+ * SetEnv FOO override
+ * Causes FOO to take the value 'override'.
+ * 23.Feb.96 Added UnsetEnv directive to allow environment variables
+ * to be removed.
+ * Virtual hosts now 'inherit' parent server environment which
+ * they're able to overwrite with their own directives or
+ * selectively ignore with UnsetEnv.
+ * *** IMPORTANT - the way that virtual hosts inherit their ***
+ * *** environment variables from the default server's ***
+ * *** configuration has changed. You should test your ***
+ * *** configuration carefully before accepting this ***
+ * *** version of the module in a live webserver which used ***
+ * *** older versions of the module. ***
+ */
+
+#include "httpd.h"
+#include "http_config.h"
+
+typedef struct {
+ table *vars;
+ char *unsetenv;
+ int vars_present;
+} env_dir_config_rec;
+
+module MODULE_VAR_EXPORT env_module;
+
+static void *create_env_dir_config(pool *p, char *dummy)
+{
+ env_dir_config_rec *new =
+ (env_dir_config_rec *) ap_palloc(p, sizeof(env_dir_config_rec));
+ new->vars = ap_make_table(p, 50);
+ new->unsetenv = "";
+ new->vars_present = 0;
+ return (void *) new;
+}
+
+static void *merge_env_dir_configs(pool *p, void *basev, void *addv)
+{
+ env_dir_config_rec *base = (env_dir_config_rec *) basev;
+ env_dir_config_rec *add = (env_dir_config_rec *) addv;
+ env_dir_config_rec *new =
+ (env_dir_config_rec *) ap_palloc(p, sizeof(env_dir_config_rec));
+
+ table *new_table;
+ table_entry *elts;
+ array_header *arr;
+
+ int i;
+ const char *uenv, *unset;
+
+ /*
+ * new_table = copy_table( p, base->vars );
+ * foreach $element ( @add->vars ) {
+ * table_set( new_table, $element.key, $element.val );
+ * };
+ * foreach $unsetenv ( @UNSETENV ) {
+ * table_unset( new_table, $unsetenv );
+ * }
+ */
+
+ new_table = ap_copy_table(p, base->vars);
+
+ arr = ap_table_elts(add->vars);
+ elts = (table_entry *)arr->elts;
+
+ for (i = 0; i < arr->nelts; ++i) {
+ ap_table_setn(new_table, elts[i].key, elts[i].val);
+ }
+
+ unset = add->unsetenv;
+ uenv = ap_getword_conf(p, &unset);
+ while (uenv[0] != '\0') {
+ ap_table_unset(new_table, uenv);
+ uenv = ap_getword_conf(p, &unset);
+ }
+
+ new->vars = new_table;
+
+ new->vars_present = base->vars_present || add->vars_present;
+
+ return new;
+}
+
+static const char *add_env_module_vars_passed(cmd_parms *cmd,
+ env_dir_config_rec *sconf,
+ const char *arg)
+{
+ table *vars = sconf->vars;
+ char *env_var;
+ char *name_ptr;
+
+ while (*arg) {
+ name_ptr = ap_getword_conf(cmd->pool, &arg);
+ env_var = getenv(name_ptr);
+ if (env_var != NULL) {
+ sconf->vars_present = 1;
+ ap_table_setn(vars, name_ptr, ap_pstrdup(cmd->pool, env_var));
+ }
+ }
+ return NULL;
+}
+
+static const char *add_env_module_vars_set(cmd_parms *cmd,
+ env_dir_config_rec *sconf,
+ const char *arg)
+{
+ table *vars = sconf->vars;
+ char *name, *value;
+
+ name = ap_getword_conf(cmd->pool, &arg);
+ value = ap_getword_conf(cmd->pool, &arg);
+
+ /* name is mandatory, value is optional. no value means
+ * set the variable to an empty string
+ */
+
+
+ if ((*name == '\0') || (*arg != '\0')) {
+ return "SetEnv takes one or two arguments. An environment variable name and an optional value to pass to CGI.";
+ }
+
+ sconf->vars_present = 1;
+ ap_table_setn(vars, name, value);
+
+ return NULL;
+}
+
+static const char *add_env_module_vars_unset(cmd_parms *cmd,
+ env_dir_config_rec *sconf,
+ char *arg)
+{
+ sconf->unsetenv = sconf->unsetenv ?
+ ap_pstrcat(cmd->pool, sconf->unsetenv, " ", arg, NULL) :
+ arg;
+ return NULL;
+}
+
+static const command_rec env_module_cmds[] =
+{
+ {"PassEnv", add_env_module_vars_passed, NULL,
+ OR_FILEINFO, RAW_ARGS, "a list of environment variables to pass to CGI."},
+ {"SetEnv", add_env_module_vars_set, NULL,
+ OR_FILEINFO, RAW_ARGS, "an environment variable name and a value to pass to CGI."},
+ {"UnsetEnv", add_env_module_vars_unset, NULL,
+ OR_FILEINFO, RAW_ARGS, "a list of variables to remove from the CGI environment."},
+ {NULL},
+};
+
+static int fixup_env_module(request_rec *r)
+{
+ table *e = r->subprocess_env;
+ env_dir_config_rec *sconf = ap_get_module_config(r->per_dir_config,
+ &env_module);
+ table *vars = sconf->vars;
+
+ if (!sconf->vars_present)
+ return DECLINED;
+
+ r->subprocess_env = ap_overlay_tables(r->pool, e, vars);
+
+ return OK;
+}
+
+module MODULE_VAR_EXPORT env_module =
+{
+ STANDARD_MODULE_STUFF,
+ NULL, /* initializer */
+ create_env_dir_config, /* dir config creater */
+ merge_env_dir_configs, /* dir merger --- default is to override */
+ NULL, /* server config */
+ NULL, /* merge server configs */
+ env_module_cmds, /* command table */
+ NULL, /* handlers */
+ NULL, /* filename translation */
+ NULL, /* check_user_id */
+ NULL, /* check auth */
+ NULL, /* check access */
+ NULL, /* type_checker */
+ fixup_env_module, /* fixups */
+ NULL, /* logger */
+ NULL, /* header parser */
+ NULL, /* child_init */
+ NULL, /* child_exit */
+ NULL /* post read-request */
+};
diff --git a/modules/metadata/mod_expires.c b/modules/metadata/mod_expires.c
new file mode 100644
index 00000000000..4fcf51a8106
--- /dev/null
+++ b/modules/metadata/mod_expires.c
@@ -0,0 +1,510 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * IT'S CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+/*
+ * mod_expires.c
+ * version 0.0.11
+ * status beta
+ *
+ * Andrew Wilson 26.Jan.96
+ *
+ * This module allows you to control the form of the Expires: header
+ * that Apache issues for each access. Directives can appear in
+ * configuration files or in .htaccess files so expiry semantics can
+ * be defined on a per-directory basis.
+ *
+ * DIRECTIVE SYNTAX
+ *
+ * Valid directives are:
+ *
+ * ExpiresActive on | off
+ * ExpiresDefault
+ * ExpiresByType type/encoding
+ *
+ * Valid values for are:
+ *
+ * 'M' expires header shows file modification date +
+ * 'A' expires header shows access time +
+ *
+ * [I'm not sure which of these is best under different
+ * circumstances, I guess it's for other people to explore.
+ * The effects may be indistinguishable for a number of cases]
+ *
+ * should be an integer value [acceptable to atoi()]
+ *
+ * There is NO space between the and .
+ *
+ * For example, a directory which contains information which changes
+ * frequently might contain:
+ *
+ * # reports generated by cron every hour. don't let caches
+ * # hold onto stale information
+ * ExpiresDefault M3600
+ *
+ * Another example, our html pages can change all the time, the gifs
+ * tend not to change often:
+ *
+ * # pages are hot (1 week), images are cold (1 month)
+ * ExpiresByType text/html A604800
+ * ExpiresByType image/gif A2592000
+ *
+ * Expires can be turned on for all URLs on the server by placing the
+ * following directive in a conf file:
+ *
+ * ExpiresActive on
+ *
+ * ExpiresActive can also appear in .htaccess files, enabling the
+ * behaviour to be turned on or off for each chosen directory.
+ *
+ * # turn off Expires behaviour in this directory
+ * # and subdirectories
+ * ExpiresActive off
+ *
+ * Directives defined for a directory are valid in subdirectories
+ * unless explicitly overridden by new directives in the subdirectory
+ * .htaccess files.
+ *
+ * ALTERNATIVE DIRECTIVE SYNTAX
+ *
+ * Directives can also be defined in a more readable syntax of the form:
+ *
+ * ExpiresDefault " [plus] { }*"
+ * ExpiresByType type/encoding " [plus] { }*"
+ *
+ * where is one of:
+ * access
+ * now equivalent to 'access'
+ * modification
+ *
+ * where the 'plus' keyword is optional
+ *
+ * where should be an integer value [acceptable to atoi()]
+ *
+ * where is one of:
+ * years
+ * months
+ * weeks
+ * days
+ * hours
+ * minutes
+ * seconds
+ *
+ * For example, any of the following directives can be used to make
+ * documents expire 1 month after being accessed, by default:
+ *
+ * ExpiresDefault "access plus 1 month"
+ * ExpiresDefault "access plus 4 weeks"
+ * ExpiresDefault "access plus 30 days"
+ *
+ * The expiry time can be fine-tuned by adding several ' '
+ * clauses:
+ *
+ * ExpiresByType text/html "access plus 1 month 15 days 2 hours"
+ * ExpiresByType image/gif "modification plus 5 hours 3 minutes"
+ *
+ * ---
+ *
+ * Change-log:
+ * 29.Jan.96 Hardened the add_* functions. Server will now bail out
+ * if bad directives are given in the conf files.
+ * 02.Feb.96 Returns DECLINED if not 'ExpiresActive on', giving other
+ * expires-aware modules a chance to play with the same
+ * directives. [Michael Rutman]
+ * 03.Feb.96 Call tzset() before localtime(). Trying to get the module
+ * to work properly in non GMT timezones.
+ * 12.Feb.96 Modified directive syntax to allow more readable commands:
+ * ExpiresDefault "now plus 10 days 20 seconds"
+ * ExpiresDefault "access plus 30 days"
+ * ExpiresDefault "modification plus 1 year 10 months 30 days"
+ * 13.Feb.96 Fix call to table_get() with NULL 2nd parameter [Rob Hartill]
+ * 19.Feb.96 Call gm_timestr_822() to get time formatted correctly, can't
+ * rely on presence of HTTP_TIME_FORMAT in Apache 1.1+.
+ * 21.Feb.96 This version (0.0.9) reverses assumptions made in 0.0.8
+ * about star/star handlers. Reverting to 0.0.7 behaviour.
+ * 08.Jun.96 allows ExpiresDefault to be used with responses that use
+ * the DefaultType by not DECLINING, but instead skipping
+ * the table_get check and then looking for an ExpiresDefault.
+ * [Rob Hartill]
+ * 04.Nov.96 'const' definitions added.
+ *
+ * TODO
+ * add support for Cache-Control: max-age=20 from the HTTP/1.1
+ * proposal (in this case, a ttl of 20 seconds) [ask roy]
+ * add per-file expiry and explicit expiry times - duplicates some
+ * of the mod_cern_meta.c functionality. eg:
+ * ExpiresExplicit index.html "modification plus 30 days"
+ *
+ * BUGS
+ * Hi, welcome to the internet.
+ */
+
+#include
+#include "httpd.h"
+#include "http_config.h"
+#include "http_log.h"
+
+typedef struct {
+ int active;
+ char *expiresdefault;
+ table *expiresbytype;
+} expires_dir_config;
+
+/* from mod_dir, why is this alias used?
+ */
+#define DIR_CMD_PERMS OR_INDEXES
+
+#define ACTIVE_ON 1
+#define ACTIVE_OFF 0
+#define ACTIVE_DONTCARE 2
+
+module MODULE_VAR_EXPORT expires_module;
+
+static void *create_dir_expires_config(pool *p, char *dummy)
+{
+ expires_dir_config *new =
+ (expires_dir_config *) ap_pcalloc(p, sizeof(expires_dir_config));
+ new->active = ACTIVE_DONTCARE;
+ new->expiresdefault = "";
+ new->expiresbytype = ap_make_table(p, 4);
+ return (void *) new;
+}
+
+static const char *set_expiresactive(cmd_parms *cmd, expires_dir_config * dir_config, int arg)
+{
+ /* if we're here at all it's because someone explicitly
+ * set the active flag
+ */
+ dir_config->active = ACTIVE_ON;
+ if (arg == 0) {
+ dir_config->active = ACTIVE_OFF;
+ };
+ return NULL;
+}
+
+/* check_code() parse 'code' and return NULL or an error response
+ * string. If we return NULL then real_code contains code converted
+ * to the cnnnn format.
+ */
+static char *check_code(pool *p, const char *code, char **real_code)
+{
+ char *word;
+ char base = 'X';
+ int modifier = 0;
+ int num = 0;
+ int factor = 0;
+
+ /* 0.0.4 compatibility?
+ */
+ if ((code[0] == 'A') || (code[0] == 'M')) {
+ *real_code = (char *)code;
+ return NULL;
+ };
+
+ /* [plus] { }*
+ */
+
+ /*
+ */
+ word = ap_getword_conf(p, &code);
+ if (!strncasecmp(word, "now", 1) ||
+ !strncasecmp(word, "access", 1)) {
+ base = 'A';
+ }
+ else if (!strncasecmp(word, "modification", 1)) {
+ base = 'M';
+ }
+ else {
+ return ap_pstrcat(p, "bad expires code, unrecognised '",
+ word, "'", NULL);
+ };
+
+ /* [plus]
+ */
+ word = ap_getword_conf(p, &code);
+ if (!strncasecmp(word, "plus", 1)) {
+ word = ap_getword_conf(p, &code);
+ };
+
+ /* { }*
+ */
+ while (word[0]) {
+ /*
+ */
+ if (ap_isdigit(word[0])) {
+ num = atoi(word);
+ }
+ else {
+ return ap_pstrcat(p, "bad expires code, numeric value expected '",
+ word, "'", NULL);
+ };
+
+ /*
+ */
+ word = ap_getword_conf(p, &code);
+ if (word[0]) {
+ /* do nothing */
+ }
+ else {
+ return ap_pstrcat(p, "bad expires code, missing ", NULL);
+ };
+
+ factor = 0;
+ if (!strncasecmp(word, "years", 1)) {
+ factor = 60 * 60 * 24 * 365;
+ }
+ else if (!strncasecmp(word, "months", 2)) {
+ factor = 60 * 60 * 24 * 30;
+ }
+ else if (!strncasecmp(word, "weeks", 1)) {
+ factor = 60 * 60 * 24 * 7;
+ }
+ else if (!strncasecmp(word, "days", 1)) {
+ factor = 60 * 60 * 24;
+ }
+ else if (!strncasecmp(word, "hours", 1)) {
+ factor = 60 * 60;
+ }
+ else if (!strncasecmp(word, "minutes", 2)) {
+ factor = 60;
+ }
+ else if (!strncasecmp(word, "seconds", 1)) {
+ factor = 1;
+ }
+ else {
+ return ap_pstrcat(p, "bad expires code, unrecognised ",
+ "'", word, "'", NULL);
+ };
+
+ modifier = modifier + factor * num;
+
+ /* next
+ */
+ word = ap_getword_conf(p, &code);
+ };
+
+ *real_code = ap_psprintf(p, "%c%d", base, modifier);
+
+ return NULL;
+}
+
+static const char *set_expiresbytype(cmd_parms *cmd, expires_dir_config * dir_config, char *mime, char *code)
+{
+ char *response, *real_code;
+
+ if ((response = check_code(cmd->pool, code, &real_code)) == NULL) {
+ ap_table_setn(dir_config->expiresbytype, mime, real_code);
+ return NULL;
+ };
+ return ap_pstrcat(cmd->pool,
+ "'ExpiresByType ", mime, " ", code, "': ", response, NULL);
+}
+
+static const char *set_expiresdefault(cmd_parms *cmd, expires_dir_config * dir_config, char *code)
+{
+ char *response, *real_code;
+
+ if ((response = check_code(cmd->pool, code, &real_code)) == NULL) {
+ dir_config->expiresdefault = real_code;
+ return NULL;
+ };
+ return ap_pstrcat(cmd->pool,
+ "'ExpiresDefault ", code, "': ", response, NULL);
+}
+
+static const command_rec expires_cmds[] =
+{
+ {"ExpiresActive", set_expiresactive, NULL, DIR_CMD_PERMS, FLAG,
+ "Limited to 'on' or 'off'"},
+ {"ExpiresBytype", set_expiresbytype, NULL, DIR_CMD_PERMS, TAKE2,
+ "a MIME type followed by an expiry date code"},
+ {"ExpiresDefault", set_expiresdefault, NULL, DIR_CMD_PERMS, TAKE1,
+ "an expiry date code"},
+ {NULL}
+};
+
+static void *merge_expires_dir_configs(pool *p, void *basev, void *addv)
+{
+ expires_dir_config *new = (expires_dir_config *) ap_pcalloc(p, sizeof(expires_dir_config));
+ expires_dir_config *base = (expires_dir_config *) basev;
+ expires_dir_config *add = (expires_dir_config *) addv;
+
+ if (add->active == ACTIVE_DONTCARE) {
+ new->active = base->active;
+ }
+ else {
+ new->active = add->active;
+ };
+
+ if (add->expiresdefault != '\0') {
+ new->expiresdefault = add->expiresdefault;
+ };
+
+ new->expiresbytype = ap_overlay_tables(p, add->expiresbytype,
+ base->expiresbytype);
+ return new;
+}
+
+static int add_expires(request_rec *r)
+{
+ expires_dir_config *conf;
+ char *code;
+ time_t base;
+ time_t additional;
+ time_t expires;
+ char age[20];
+
+ if (ap_is_HTTP_ERROR(r->status)) /* Don't add Expires headers to errors */
+ return DECLINED;
+
+ if (r->main != NULL) /* Say no to subrequests */
+ return DECLINED;
+
+ conf = (expires_dir_config *) ap_get_module_config(r->per_dir_config, &expires_module);
+ if (conf == NULL) {
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "internal error: %s", r->filename);
+ return SERVER_ERROR;
+ };
+
+ if (conf->active != ACTIVE_ON)
+ return DECLINED;
+
+ /* we perhaps could use the default_type(r) in its place but that
+ * may be 2nd guesing the desired configuration... calling table_get
+ * with a NULL key will SEGV us
+ *
+ * I still don't know *why* r->content_type would ever be NULL, this
+ * is possibly a result of fixups being called in many different
+ * places. Fixups is probably the wrong place to be doing all this
+ * work... Bah.
+ *
+ * Changed as of 08.Jun.96 don't DECLINE, look for an ExpiresDefault.
+ */
+ if (r->content_type == NULL)
+ code = NULL;
+ else
+ code = (char *) ap_table_get(conf->expiresbytype, r->content_type);
+
+ if (code == NULL) {
+ /* no expires defined for that type, is there a default? */
+ code = conf->expiresdefault;
+
+ if (code[0] == '\0')
+ return OK;
+ };
+
+ /* we have our code */
+
+ switch (code[0]) {
+ case 'M':
+ if (r->finfo.st_mode == 0) {
+ /* file doesn't exist on disk, so we can't do anything based on
+ * modification time. Note that this does _not_ log an error.
+ */
+ return DECLINED;
+ }
+ base = r->finfo.st_mtime;
+ additional = atoi(&code[1]);
+ break;
+ case 'A':
+ /* there's been some discussion and it's possible that
+ * 'access time' will be stored in request structure
+ */
+ base = r->request_time;
+ additional = atoi(&code[1]);
+ break;
+ default:
+ /* expecting the add_* routines to be case-hardened this
+ * is just a reminder that module is beta
+ */
+ ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
+ "internal error: bad expires code: %s", r->filename);
+ return SERVER_ERROR;
+ };
+
+ expires = base + additional;
+ ap_snprintf(age, sizeof(age), "max-age=%d", (int) expires - (int) r->request_time);
+ ap_table_setn(r->headers_out, "Cache-Control", ap_pstrdup(r->pool, age));
+ tzset(); /* redundant? called implicitly by localtime, at least
+ * under FreeBSD
+ */
+ ap_table_setn(r->headers_out, "Expires", ap_gm_timestr_822(r->pool, expires));
+ return OK;
+}
+
+module MODULE_VAR_EXPORT expires_module =
+{
+ STANDARD_MODULE_STUFF,
+ NULL, /* initializer */
+ create_dir_expires_config, /* dir config creater */
+ merge_expires_dir_configs, /* dir merger --- default is to override */
+ NULL, /* server config */
+ NULL, /* merge server configs */
+ expires_cmds, /* command table */
+ NULL, /* handlers */
+ NULL, /* filename translation */
+ NULL, /* check_user_id */
+ NULL, /* check auth */
+ NULL, /* check access */
+ NULL, /* type_checker */
+ add_expires, /* fixups */
+ NULL, /* logger */
+ NULL, /* header parser */
+ NULL, /* child_init */
+ NULL, /* child_exit */
+ NULL /* post read-request */
+};
diff --git a/modules/metadata/mod_expires.dsp b/modules/metadata/mod_expires.dsp
new file mode 100644
index 00000000000..0b2fe902bb2
--- /dev/null
+++ b/modules/metadata/mod_expires.dsp
@@ -0,0 +1,113 @@
+# Microsoft Developer Studio Project File - Name="ApacheModuleExpires" - Package Owner=<4>
+# Microsoft Developer Studio Generated Build File, Format Version 5.00
+# ** DO NOT EDIT **
+
+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102
+
+CFG=ApacheModuleExpires - Win32 Release
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,
+!MESSAGE use the Export Makefile command and run
+!MESSAGE
+!MESSAGE NMAKE /f "ApacheModuleExpires.mak".
+!MESSAGE
+!MESSAGE You can specify a configuration when running NMAKE
+!MESSAGE by defining the macro CFG on the command line. For example:
+!MESSAGE
+!MESSAGE NMAKE /f "ApacheModuleExpires.mak"\
+ CFG="ApacheModuleExpires - Win32 Release"
+!MESSAGE
+!MESSAGE Possible choices for configuration are:
+!MESSAGE
+!MESSAGE "ApacheModuleExpires - Win32 Release" (based on\
+ "Win32 (x86) Dynamic-Link Library")
+!MESSAGE "ApacheModuleExpires - Win32 Debug" (based on\
+ "Win32 (x86) Dynamic-Link Library")
+!MESSAGE
+
+# Begin Project
+# PROP Scc_ProjName ""
+# PROP Scc_LocalPath ""
+CPP=cl.exe
+MTL=midl.exe
+RSC=rc.exe
+
+!IF "$(CFG)" == "ApacheModuleExpires - Win32 Release"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir ".\Release"
+# PROP BASE Intermediate_Dir ".\Release"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir ".\ApacheModuleExpiresR"
+# PROP Intermediate_Dir ".\ApacheModuleExpiresR"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /c
+# ADD CPP /nologo /MD /W3 /GX /O2 /I "..\..\include" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "SHARED_MODULE" /YX /FD /c
+# ADD BASE MTL /nologo /D "NDEBUG" /win32
+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
+# ADD BASE RSC /l 0x809 /d "NDEBUG"
+# ADD RSC /l 0x809 /d "NDEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /machine:I386
+# ADD LINK32 ..\..\CoreR\ApacheCore.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /dll /machine:I386
+
+!ELSEIF "$(CFG)" == "ApacheModuleExpires - Win32 Debug"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 1
+# PROP BASE Output_Dir ".\Debug"
+# PROP BASE Intermediate_Dir ".\Debug"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 1
+# PROP Output_Dir ".\ApacheModuleExpiresD"
+# PROP Intermediate_Dir ".\ApacheModuleExpiresD"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /c
+# ADD CPP /nologo /MDd /W3 /Gm /GX /Zi /Od /I "..\..\include" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "SHARED_MODULE" /YX /FD /c
+# ADD BASE MTL /nologo /D "_DEBUG" /win32
+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
+# ADD BASE RSC /l 0x809 /d "_DEBUG"
+# ADD RSC /l 0x809 /d "_DEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /debug /machine:I386
+# ADD LINK32 ..\..\CoreD\ApacheCore.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /dll /debug /machine:I386
+
+!ENDIF
+
+# Begin Target
+
+# Name "ApacheModuleExpires - Win32 Release"
+# Name "ApacheModuleExpires - Win32 Debug"
+# Begin Group "Source Files"
+
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;hpj;bat;for;f90"
+# Begin Source File
+
+SOURCE=..\..\modules\standard\mod_expires.c
+# End Source File
+# End Group
+# Begin Group "Header Files"
+
+# PROP Default_Filter "h;hpp;hxx;hm;inl;fi;fd"
+# Begin Source File
+
+SOURCE=.\readdir.h
+# End Source File
+# End Group
+# Begin Group "Resource Files"
+
+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe"
+# End Group
+# End Target
+# End Project
diff --git a/modules/metadata/mod_headers.c b/modules/metadata/mod_headers.c
new file mode 100644
index 00000000000..c3d50503eed
--- /dev/null
+++ b/modules/metadata/mod_headers.c
@@ -0,0 +1,265 @@
+/* ====================================================================
+ * Copyright (c) 1996-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+/*
+ * mod_headers.c: Add/append/remove HTTP response headers
+ * Written by Paul Sutton, paul@ukweb.com, 1 Oct 1996
+ *
+ * New directive, Header, can be used to add/replace/remove HTTP headers.
+ * Valid in both per-server and per-dir configurations.
+ *
+ * Syntax is:
+ *
+ * Header action header value
+ *
+ * Where action is one of:
+ * set - set this header, replacing any old value
+ * add - add this header, possible resulting in two or more
+ * headers with the same name
+ * append - append this text onto any existing header of this same
+ * unset - remove this header
+ *
+ * Where action is unset, the third argument (value) should not be given.
+ * The header name can include the colon, or not.
+ *
+ * The Header directive can only be used where allowed by the FileInfo
+ * override.
+ *
+ * When the request is processed, the header directives are processed in
+ * this order: firstly, the main server, then the virtual server handling
+ * this request (if any), then any sections (working downwards
+ * from the root dir), then an sections (working down from
+ * shortest URL component), the any sections. This order is
+ * important if any 'set' or 'unset' actions are used. For example,
+ * the following two directives have different effect if applied in
+ * the reverse order:
+ *
+ * Header append Author "John P. Doe"
+ * Header unset Author
+ *
+ * Examples:
+ *
+ * To set the "Author" header, use
+ * Header add Author "John P. Doe"
+ *
+ * To remove a header:
+ * Header unset Author
+ *
+ */
+
+#include "httpd.h"
+#include "http_config.h"
+
+typedef enum {
+ hdr_add = 'a', /* add header (could mean multiple hdrs) */
+ hdr_set = 's', /* set (replace old value) */
+ hdr_append = 'm', /* append (merge into any old value) */
+ hdr_unset = 'u' /* unset header */
+} hdr_actions;
+
+typedef struct {
+ hdr_actions action;
+ char *header;
+ char *value;
+} header_entry;
+
+/*
+ * headers_conf is our per-module configuration. This is used as both
+ * a per-dir and per-server config
+ */
+typedef struct {
+ array_header *headers;
+} headers_conf;
+
+module MODULE_VAR_EXPORT headers_module;
+
+static void *create_headers_config(pool *p, server_rec *s)
+{
+ headers_conf *a =
+ (headers_conf *) ap_pcalloc(p, sizeof(headers_conf));
+
+ a->headers = ap_make_array(p, 2, sizeof(header_entry));
+ return a;
+}
+
+static void *create_headers_dir_config(pool *p, char *d)
+{
+ return (headers_conf *) create_headers_config(p, NULL);
+}
+
+static void *merge_headers_config(pool *p, void *basev, void *overridesv)
+{
+ headers_conf *a =
+ (headers_conf *) ap_pcalloc(p, sizeof(headers_conf));
+ headers_conf *base = (headers_conf *) basev, *overrides = (headers_conf *) overridesv;
+
+ a->headers = ap_append_arrays(p, base->headers, overrides->headers);
+
+ return a;
+}
+
+
+static const char *header_cmd(cmd_parms *cmd, headers_conf * dirconf, char *action, char *hdr, char *value)
+{
+ header_entry *new;
+ server_rec *s = cmd->server;
+ headers_conf *serverconf =
+ (headers_conf *) ap_get_module_config(s->module_config, &headers_module);
+ char *colon;
+
+ if (cmd->path) {
+ new = (header_entry *) ap_push_array(dirconf->headers);
+ }
+ else {
+ new = (header_entry *) ap_push_array(serverconf->headers);
+ }
+
+ if (!strcasecmp(action, "set"))
+ new->action = hdr_set;
+ else if (!strcasecmp(action, "add"))
+ new->action = hdr_add;
+ else if (!strcasecmp(action, "append"))
+ new->action = hdr_append;
+ else if (!strcasecmp(action, "unset"))
+ new->action = hdr_unset;
+ else
+ return "first argument must be add, set, append or unset.";
+
+ if (new->action == hdr_unset) {
+ if (value)
+ return "Header unset takes two arguments";
+ }
+ else if (!value)
+ return "Header requires three arguments";
+
+ if ((colon = strchr(hdr, ':')))
+ *colon = '\0';
+
+ new->header = hdr;
+ new->value = value;
+
+ return NULL;
+}
+
+static const command_rec headers_cmds[] =
+{
+ {"Header", header_cmd, NULL, OR_FILEINFO, TAKE23,
+ "an action, header and value"},
+ {NULL}
+};
+
+static void do_headers_fixup(request_rec *r, array_header *headers)
+{
+ int i;
+
+ for (i = 0; i < headers->nelts; ++i) {
+ header_entry *hdr = &((header_entry *) (headers->elts))[i];
+ switch (hdr->action) {
+ case hdr_add:
+ ap_table_addn(r->headers_out, hdr->header, hdr->value);
+ break;
+ case hdr_append:
+ ap_table_mergen(r->headers_out, hdr->header, hdr->value);
+ break;
+ case hdr_set:
+ ap_table_setn(r->headers_out, hdr->header, hdr->value);
+ break;
+ case hdr_unset:
+ ap_table_unset(r->headers_out, hdr->header);
+ break;
+ }
+ }
+
+}
+
+static int fixup_headers(request_rec *r)
+{
+ void *sconf = r->server->module_config;
+ headers_conf *serverconf =
+ (headers_conf *) ap_get_module_config(sconf, &headers_module);
+ void *dconf = r->per_dir_config;
+ headers_conf *dirconf =
+ (headers_conf *) ap_get_module_config(dconf, &headers_module);
+
+ do_headers_fixup(r, serverconf->headers);
+ do_headers_fixup(r, dirconf->headers);
+
+ return DECLINED;
+}
+
+module MODULE_VAR_EXPORT headers_module =
+{
+ STANDARD_MODULE_STUFF,
+ NULL, /* initializer */
+ create_headers_dir_config, /* dir config creater */
+ merge_headers_config, /* dir merger --- default is to override */
+ create_headers_config, /* server config */
+ merge_headers_config, /* merge server configs */
+ headers_cmds, /* command table */
+ NULL, /* handlers */
+ NULL, /* filename translation */
+ NULL, /* check_user_id */
+ NULL, /* check auth */
+ NULL, /* check access */
+ NULL, /* type_checker */
+ fixup_headers, /* fixups */
+ NULL, /* logger */
+ NULL, /* header parser */
+ NULL, /* child_init */
+ NULL, /* child_exit */
+ NULL /* post read-request */
+};
diff --git a/modules/metadata/mod_headers.dsp b/modules/metadata/mod_headers.dsp
new file mode 100644
index 00000000000..1dc76027b31
--- /dev/null
+++ b/modules/metadata/mod_headers.dsp
@@ -0,0 +1,113 @@
+# Microsoft Developer Studio Project File - Name="ApacheModuleHeaders" - Package Owner=<4>
+# Microsoft Developer Studio Generated Build File, Format Version 5.00
+# ** DO NOT EDIT **
+
+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102
+
+CFG=ApacheModuleHeaders - Win32 Release
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,
+!MESSAGE use the Export Makefile command and run
+!MESSAGE
+!MESSAGE NMAKE /f "ApacheModuleHeaders.mak".
+!MESSAGE
+!MESSAGE You can specify a configuration when running NMAKE
+!MESSAGE by defining the macro CFG on the command line. For example:
+!MESSAGE
+!MESSAGE NMAKE /f "ApacheModuleHeaders.mak"\
+ CFG="ApacheModuleHeaders - Win32 Release"
+!MESSAGE
+!MESSAGE Possible choices for configuration are:
+!MESSAGE
+!MESSAGE "ApacheModuleHeaders - Win32 Release" (based on\
+ "Win32 (x86) Dynamic-Link Library")
+!MESSAGE "ApacheModuleHeaders - Win32 Debug" (based on\
+ "Win32 (x86) Dynamic-Link Library")
+!MESSAGE
+
+# Begin Project
+# PROP Scc_ProjName ""
+# PROP Scc_LocalPath ""
+CPP=cl.exe
+MTL=midl.exe
+RSC=rc.exe
+
+!IF "$(CFG)" == "ApacheModuleHeaders - Win32 Release"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir ".\Release"
+# PROP BASE Intermediate_Dir ".\Release"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir ".\ApacheModuleHeadersR"
+# PROP Intermediate_Dir ".\ApacheModuleHeadersR"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /c
+# ADD CPP /nologo /MD /W3 /GX /O2 /I "..\..\include" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "SHARED_MODULE" /YX /FD /c
+# ADD BASE MTL /nologo /D "NDEBUG" /win32
+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
+# ADD BASE RSC /l 0x809 /d "NDEBUG"
+# ADD RSC /l 0x809 /d "NDEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /machine:I386
+# ADD LINK32 ..\..\CoreR\ApacheCore.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /dll /machine:I386
+
+!ELSEIF "$(CFG)" == "ApacheModuleHeaders - Win32 Debug"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 1
+# PROP BASE Output_Dir ".\Debug"
+# PROP BASE Intermediate_Dir ".\Debug"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 1
+# PROP Output_Dir ".\ApacheModuleHeadersD"
+# PROP Intermediate_Dir ".\ApacheModuleHeadersD"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /c
+# ADD CPP /nologo /MDd /W3 /Gm /GX /Zi /Od /I "..\..\include" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "SHARED_MODULE" /YX /FD /c
+# ADD BASE MTL /nologo /D "_DEBUG" /win32
+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
+# ADD BASE RSC /l 0x809 /d "_DEBUG"
+# ADD RSC /l 0x809 /d "_DEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /debug /machine:I386
+# ADD LINK32 ..\..\CoreD\ApacheCore.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /dll /debug /machine:I386
+
+!ENDIF
+
+# Begin Target
+
+# Name "ApacheModuleHeaders - Win32 Release"
+# Name "ApacheModuleHeaders - Win32 Debug"
+# Begin Group "Source Files"
+
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;hpj;bat;for;f90"
+# Begin Source File
+
+SOURCE=..\..\modules\standard\mod_headers.c
+# End Source File
+# End Group
+# Begin Group "Header Files"
+
+# PROP Default_Filter "h;hpp;hxx;hm;inl;fi;fd"
+# Begin Source File
+
+SOURCE=.\readdir.h
+# End Source File
+# End Group
+# Begin Group "Resource Files"
+
+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe"
+# End Group
+# End Target
+# End Project
diff --git a/modules/metadata/mod_mime_magic.c b/modules/metadata/mod_mime_magic.c
new file mode 100644
index 00000000000..7f4d6ba6e30
--- /dev/null
+++ b/modules/metadata/mod_mime_magic.c
@@ -0,0 +1,2474 @@
+/* ====================================================================
+ * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * 4. The names "Apache Server" and "Apache Group" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the Apache Group
+ * for use in the Apache HTTP server project (http://www.apache.org/)."
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Group and was originally based
+ * on public domain software written at the National Center for
+ * Supercomputing Applications, University of Illinois, Urbana-Champaign.
+ * For more information on the Apache Group and the Apache HTTP server
+ * project, please see .
+ *
+ */
+
+/*
+ * mod_mime_magic: MIME type lookup via file magic numbers
+ * Copyright (c) 1996-1997 Cisco Systems, Inc.
+ *
+ * This software was submitted by Cisco Systems to the Apache Group in July
+ * 1997. Future revisions and derivatives of this source code must
+ * acknowledge Cisco Systems as the original contributor of this module.
+ * All other licensing and usage conditions are those of the Apache Group.
+ *
+ * Some of this code is derived from the free version of the file command
+ * originally posted to comp.sources.unix. Copyright info for that program
+ * is included below as required.
+ * ---------------------------------------------------------------------------
+ * - Copyright (c) Ian F. Darwin, 1987. Written by Ian F. Darwin.
+ *
+ * This software is not subject to any license of the American Telephone and
+ * Telegraph Company or of the Regents of the University of California.
+ *
+ * Permission is granted to anyone to use this software for any purpose on any
+ * computer system, and to alter it and redistribute it freely, subject to
+ * the following restrictions:
+ *
+ * 1. The author is not responsible for the consequences of use of this
+ * software, no matter how awful, even if they arise from flaws in it.
+ *
+ * 2. The origin of this software must not be misrepresented, either by
+ * explicit claim or by omission. Since few users ever read sources, credits
+ * must appear in the documentation.
+ *
+ * 3. Altered versions must be plainly marked as such, and must not be
+ * misrepresented as being the original software. Since few users ever read
+ * sources, credits must appear in the documentation.
+ *
+ * 4. This notice may not be removed or altered.
+ * -------------------------------------------------------------------------
+ *
+ * For compliance with Mr Darwin's terms: this has been very significantly
+ * modified from the free "file" command.
+ * - all-in-one file for compilation convenience when moving from one
+ * version of Apache to the next.
+ * - Memory allocation is done through the Apache API's pool structure.
+ * - All functions have had necessary Apache API request or server
+ * structures passed to them where necessary to call other Apache API
+ * routines. (i.e. usually for logging, files, or memory allocation in
+ * itself or a called function.)
+ * - struct magic has been converted from an array to a single-ended linked
+ * list because it only grows one record at a time, it's only accessed
+ * sequentially, and the Apache API has no equivalent of realloc().
+ * - Functions have been changed to get their parameters from the server
+ * configuration instead of globals. (It should be reentrant now but has
+ * not been tested in a threaded environment.)
+ * - Places where it used to print results to stdout now saves them in a
+ * list where they're used to set the MIME type in the Apache request
+ * record.
+ * - Command-line flags have been removed since they will never be used here.
+ *
+ * Ian Kluft
+ * Engineering Information Framework
+ * Central Engineering
+ * Cisco Systems, Inc.
+ * San Jose, CA, USA
+ *
+ * Initial installation July/August 1996
+ * Misc bug fixes May 1997
+ * Submission to Apache Group July 1997
+ *
+ */
+
+#include "httpd.h"
+#include "http_config.h"
+#include "http_request.h"
+#include "http_core.h"
+#include "http_log.h"
+#include "http_protocol.h"
+
+#include
+
+
+/*
+ * data structures and related constants
+ */
+
+#define MODNAME "mod_mime_magic"
+#define MIME_MAGIC_DEBUG 0
+
+#define MIME_BINARY_UNKNOWN "application/octet-stream"
+#define MIME_TEXT_UNKNOWN "text/plain"
+
+#define MAXMIMESTRING 256
+
+/* HOWMANY must be at least 4096 to make gzip -dcq work */
+#define HOWMANY 4096
+/* SMALL_HOWMANY limits how much work we do to figure out text files */
+#define SMALL_HOWMANY 1024
+#define MAXDESC 50 /* max leng of text description */
+#define MAXstring 64 /* max leng of "string" types */
+
+struct magic {
+ struct magic *next; /* link to next entry */
+ int lineno; /* line number from magic file */
+
+ short flag;
+#define INDIR 1 /* if '>(...)' appears, */
+#define UNSIGNED 2 /* comparison is unsigned */
+ short cont_level; /* level of ">" */
+ struct {
+ char type; /* byte short long */
+ long offset; /* offset from indirection */
+ } in;
+ long offset; /* offset to magic number */
+ unsigned char reln; /* relation (0=eq, '>'=gt, etc) */
+ char type; /* int, short, long or string. */
+ char vallen; /* length of string value, if any */
+#define BYTE 1
+#define SHORT 2
+#define LONG 4
+#define STRING 5
+#define DATE 6
+#define BESHORT 7
+#define BELONG 8
+#define BEDATE 9
+#define LESHORT 10
+#define LELONG 11
+#define LEDATE 12
+ union VALUETYPE {
+ unsigned char b;
+ unsigned short h;
+ unsigned long l;
+ char s[MAXstring];
+ unsigned char hs[2]; /* 2 bytes of a fixed-endian "short" */
+ unsigned char hl[4]; /* 2 bytes of a fixed-endian "long" */
+ } value; /* either number or string */
+ unsigned long mask; /* mask before comparison with value */
+ char nospflag; /* supress space character */
+
+ /* NOTE: this string is suspected of overrunning - find it! */
+ char desc[MAXDESC]; /* description */
+};
+
+/*
+ * data structures for tar file recognition
+ * --------------------------------------------------------------------------
+ * Header file for public domain tar (tape archive) program.
+ *
+ * @(#)tar.h 1.20 86/10/29 Public Domain. Created 25 August 1985 by John
+ * Gilmore, ihnp4!hoptoad!gnu.
+ *
+ * Header block on tape.
+ *
+ * I'm going to use traditional DP naming conventions here. A "block" is a big
+ * chunk of stuff that we do I/O on. A "record" is a piece of info that we
+ * care about. Typically many "record"s fit into a "block".
+ */
+#define RECORDSIZE 512
+#define NAMSIZ 100
+#define TUNMLEN 32
+#define TGNMLEN 32
+
+union record {
+ char charptr[RECORDSIZE];
+ struct header {
+ char name[NAMSIZ];
+ char mode[8];
+ char uid[8];
+ char gid[8];
+ char size[12];
+ char mtime[12];
+ char chksum[8];
+ char linkflag;
+ char linkname[NAMSIZ];
+ char magic[8];
+ char uname[TUNMLEN];
+ char gname[TGNMLEN];
+ char devmajor[8];
+ char devminor[8];
+ } header;
+};
+
+/* The magic field is filled with this if uname and gname are valid. */
+#define TMAGIC "ustar " /* 7 chars and a null */
+
+/*
+ * file-function prototypes
+ */
+static int ascmagic(request_rec *, unsigned char *, int);
+static int is_tar(unsigned char *, int);
+static int softmagic(request_rec *, unsigned char *, int);
+static void tryit(request_rec *, unsigned char *, int, int);
+static int zmagic(request_rec *, unsigned char *, int);
+
+static int getvalue(server_rec *, struct magic *, char **);
+static int hextoint(int);
+static char *getstr(server_rec *, char *, char *, int, int *);
+static int parse(server_rec *, pool *p, char *, int);
+
+static int match(request_rec *, unsigned char *, int);
+static int mget(request_rec *, union VALUETYPE *, unsigned char *,
+ struct magic *, int);
+static int mcheck(request_rec *, union VALUETYPE *, struct magic *);
+static void mprint(request_rec *, union VALUETYPE *, struct magic *);
+
+static int uncompress(request_rec *, int,
+ unsigned char **, int);
+static long from_oct(int, char *);
+static int fsmagic(request_rec *r, const char *fn);
+
+/*
+ * includes for ASCII substring recognition formerly "names.h" in file
+ * command
+ *
+ * Original notes: names and types used by ascmagic in file(1). These tokens are
+ * here because they can appear anywhere in the first HOWMANY bytes, while
+ * tokens in /etc/magic must appear at fixed offsets into the file. Don't
+ * make HOWMANY too high unless you have a very fast CPU.
+ */
+
+/* these types are used to index the table 'types': keep em in sync! */
+/* HTML inserted in first because this is a web server module now */
+#define L_HTML 0 /* HTML */
+#define L_C 1 /* first and foremost on UNIX */
+#define L_FORT 2 /* the oldest one */
+#define L_MAKE 3 /* Makefiles */
+#define L_PLI 4 /* PL/1 */
+#define L_MACH 5 /* some kinda assembler */
+#define L_ENG 6 /* English */
+#define L_PAS 7 /* Pascal */
+#define L_MAIL 8 /* Electronic mail */
+#define L_NEWS 9 /* Usenet Netnews */
+
+static char *types[] =
+{
+ "text/html", /* HTML */
+ "text/plain", /* "c program text", */
+ "text/plain", /* "fortran program text", */
+ "text/plain", /* "make commands text", */
+ "text/plain", /* "pl/1 program text", */
+ "text/plain", /* "assembler program text", */
+ "text/plain", /* "English text", */
+ "text/plain", /* "pascal program text", */
+ "message/rfc822", /* "mail text", */
+ "message/news", /* "news text", */
+ "application/binary", /* "can't happen error on names.h/types", */
+ 0
+};
+
+static struct names {
+ char *name;
+ short type;
+} names[] = {
+
+ /* These must be sorted by eye for optimal hit rate */
+ /* Add to this list only after substantial meditation */
+ {
+ "", L_HTML
+ },
+ {
+ "", L_HTML
+ },
+ {
+ "", L_HTML
+ },
+ {
+ "", L_HTML
+ },
+ {
+ "", L_HTML
+ },
+ {
+ "", L_HTML
+ },
+ {
+ " | |