switch to go vendoring

This commit is contained in:
Michael Barz
2023-04-19 20:24:34 +02:00
parent 632fa05ef9
commit afc6ed1e41
8527 changed files with 3004916 additions and 2 deletions
+20
View File
@@ -0,0 +1,20 @@
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Test binary, built with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Dependency directories (remove the comment below to include it)
vendor/
go.sum
# Misc
.DS_Store
logs.txt
+19
View File
@@ -0,0 +1,19 @@
dist: xenial
language: go
env:
- GO111MODULE=ON
go:
- 1.12.x
git:
depth: 1
notifications:
email: true
script:
- go test -v -count=1 .
+9
View File
@@ -0,0 +1,9 @@
# Contributing
1. Fork the repo
1. Make the change
1. Update the README.md with details of the changes (if needed)
1. Open your pull request against the dev branch
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+95
View File
@@ -0,0 +1,95 @@
# icap-client
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE)
[![Project status](https://img.shields.io/badge/version-0.1.0-green.svg)](https://github.com/egirna/icap-client/releases)
[![GoDoc](https://godoc.org/github.com/egirna/icap-client?status.svg)](https://godoc.org/github.com/egirna/icap-client)
Talk to the ICAP servers using probably the first ICAP client package in GO!
### Installing
```console
go get -u github.com/egirna/icap-client
```
### Usage
**Import The Package**
```go
import ic "github.com/egirna/icap-client"
```
**Making a simple RESPMOD call**
```go
req, err := ic.NewRequest(ic.MethodRESPMOD, "icap://<host>:<port>/<path>", httpReq, httpResp)
if err != nil {
log.Fatal(err)
}
client := &ic.Client{
Timeout: 5 * time.Second,
}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
```
**Note**: ``httpReq`` & ``httpResp`` here are ``*http.Response`` & ``*http.Request`` respectively
**Setting preview obtained from OPTIONS call**
```go
optReq, err := ic.NewRequest(ic.MethodOPTIONS, "icap://<host>:<port>/<path>", nil, nil)
if err != nil {
log.Fatal(err)
return
}
client := &ic.Client{
Timeout: 5 * time.Second,
}
req.SetPreview(optReq.PreviewBytes)
// do something with req(ICAP *Request)
```
**DEBUG Mode**
Turn on debug mode to inspect detailed & verbose logs to debug your code during development
```go
ic.SetDebugMode(true)
```
By default the icap-client will dump the debugging logs to the standard output(stdout), but you can always add your custom writer
```go
f, _ := os.OpenFile("logs.txt", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
ic.SetDebugOutput(f)
```
For more details, see the [docs](https://godoc.org/github.com/egirna/icap-client) and [examples](examples/).
### Contributing
This package is still WIP, so totally open to suggestions. See the contributions guide [here](CONTRIBUTING.md).
### License
**icap-client** is licensed under the [Apache License](LICENSE).
+115
View File
@@ -0,0 +1,115 @@
package icapclient
import (
"net/http"
"strconv"
"time"
)
// Client represents the icap client who makes the icap server calls
type Client struct {
scktDriver *Driver
Timeout time.Duration
}
// Do makes does everything required to make a call to the ICAP server
func (c *Client) Do(req *Request) (*Response, error) {
if c.scktDriver == nil { // create a new socket driver if one wasn't explicitly created
port, err := strconv.Atoi(req.URL.Port())
if err != nil {
return nil, err
}
c.scktDriver = NewDriver(req.URL.Hostname(), port)
}
c.setDefaultTimeouts() // assinging default timeouts if not set already
if req.ctx != nil { // connect with the given context if context is set
if err := c.scktDriver.ConnectWithContext(*req.ctx); err != nil {
return nil, err
}
} else {
if err := c.scktDriver.Connect(); err != nil {
return nil, err
}
}
defer c.scktDriver.Close() // closing the socket connection
req.SetDefaultRequestHeaders() // assigning default headers if not set already
logDebug("The request headers: ")
dumpDebug(req.Header)
d, err := DumpRequest(req) // getting the byte representation of the ICAP request
if err != nil {
return nil, err
}
if err := c.scktDriver.Send(d); err != nil { // sending the entire TCP message of the ICAP client to the server connected
return nil, err
}
resp, err := c.scktDriver.Receive() // taking the response
if err != nil {
return nil, err
}
if resp.StatusCode == http.StatusContinue && !req.bodyFittedInPreview && req.previewSet { // this block suggests that the ICAP request contained preview body bytes and whole body did not fit in the preview, so the serber responded with 100 Continue and the client is to send the remaining body bytes only
logDebug("Making request for the rest of the remaining body bytes after preview, as received 100 Continue from the server...")
return c.DoRemaining(req)
}
return resp, nil
}
// DoRemaining requests an ICAP server with the remaining body bytes which did not fit in the preview in the original request
func (c *Client) DoRemaining(req *Request) (*Response, error) {
data := req.remainingPreviewBytes
if !bodyAlreadyChunked(string(data)) { // if the body is not already chunke, then add the basic hexa body bytes notation
ds := string(data)
addHexaBodyByteNotations(&ds)
data = []byte(ds)
}
if err := c.scktDriver.Send(data); err != nil {
return nil, err
}
resp, err := c.scktDriver.Receive()
if err != nil {
return nil, err
}
return resp, nil
}
// SetDriver sets a new socket driver with the client
func (c *Client) SetDriver(d *Driver) {
c.scktDriver = d
}
func (c *Client) setDefaultTimeouts() {
if c.Timeout == 0 {
c.Timeout = defaultTimeout
}
if c.scktDriver.DialerTimeout == 0 {
c.scktDriver.DialerTimeout = c.Timeout
}
if c.scktDriver.ReadTimeout == 0 {
c.scktDriver.ReadTimeout = c.Timeout
}
if c.scktDriver.WriteTimeout == 0 {
c.scktDriver.WriteTimeout = c.Timeout
}
}
+57
View File
@@ -0,0 +1,57 @@
package icapclient
import "time"
// the icap request methods
const (
MethodOPTIONS = "OPTIONS"
MethodRESPMOD = "RESPMOD"
MethodREQMOD = "REQMOD"
)
// the error messages
const (
ErrInvalidScheme = "the url scheme must be icap://"
ErrMethodNotRegistered = "the requested method is not registered"
ErrInvalidHost = "the requested host is invalid"
ErrConnectionNotOpen = "no open connection to close"
ErrInvalidTCPMsg = "invalid tcp message"
ErrREQMODWithNoReq = "http request cannot be nil for method REQMOD"
ErrREQMODWithResp = "http response must be nil for method REQMOD"
ErrRESPMODWithNoResp = "http response cannot be nil for method RESPMOD"
)
// general constants required for the package
const (
SchemeICAP = "icap"
ICAPVersion = "ICAP/1.0"
HTTPVersion = "HTTP/1.1"
SchemeHTTPReq = "http_request"
SchemeHTTPResp = "http_response"
CRLF = "\r\n"
DoubleCRLF = "\r\n\r\n"
LF = "\n"
bodyEndIndicator = CRLF + "0" + CRLF
fullBodyEndIndicatorPreviewMode = "; ieof" + DoubleCRLF
icap100ContinueMsg = "ICAP/1.0 100 Continue" + DoubleCRLF
icap204NoModsMsg = "ICAP/1.0 204 No modifications"
defaultChunkLength = 512
defaultTimeout = 15 * time.Second
)
// Common ICAP headers
const (
PreviewHeader = "Preview"
MethodsHeader = "Methods"
AllowHeader = "Allow"
EncapsulatedHeader = "Encapsulated"
TransferPreviewHeader = "Transfer-Preview"
ServiceHeader = "Service"
ISTagHeader = "ISTag"
OptBodyTypeHeader = "Opt-body-type"
MaxConnectionsHeader = "Max-Connections"
OptionsTTLHeader = "Options-TTL"
ServiceIDHeader = "Service-ID"
TransferIgnoreHeader = "Transfer-Ignore"
TransferCompleteHeader = "Transfer-Complete"
)
+55
View File
@@ -0,0 +1,55 @@
package icapclient
import (
"io"
"log"
"os"
"github.com/davecgh/go-spew/spew"
)
// the debug mode determiner & the writer to the write the debug output to
var (
DEBUG = false
debugWriter io.Writer
logger *log.Logger
)
const (
debugPrefix = "icap-client says: "
)
// SetDebugMode sets the debug mode for the entire package depending on the bool
func SetDebugMode(debug bool) {
DEBUG = debug
if DEBUG { // setting os.Stdout as the default debug writer if debug mode is enabled & also the debug prefix
debugWriter = os.Stdout
logger = log.New(debugWriter, debugPrefix, log.LstdFlags)
}
}
// SetDebugOutput sets writer to write the debug outputs (default: os.Stdout)
func SetDebugOutput(w io.Writer) {
debugWriter = w
logger.SetOutput(debugWriter)
}
func logDebug(a ...interface{}) {
if DEBUG {
logger.Println(a...)
}
}
func logfDebug(s string, a ...interface{}) {
if DEBUG {
logger.Printf(s, a...)
}
}
func dumpDebug(a ...interface{}) {
if DEBUG {
spew.Fdump(debugWriter, a...)
}
}
+73
View File
@@ -0,0 +1,73 @@
//Package icapclient is a client package for the ICAP protocol
//
// Here is a basic example:
// package main
//
// import (
// "fmt"
// "log"
// "net/http"
// "time"
//
// ic "github.com/egirna/icap-client"
// )
//
// func main() {
// /* preparing the http request required for the RESPMOD */
// httpReq, err := http.NewRequest(http.MethodGet, "http://localhost:8000/sample.pdf", nil)
//
// if err != nil {
// log.Fatal(err)
// }
//
// /* making the http client & making the request call to get the response needed for the icap RESPMOD call */
// httpClient := &http.Client{}
//
// httpResp, err := httpClient.Do(httpReq)
//
// if err != nil {
// log.Fatal(err)
// }
//
// /* making a icap request with OPTIONS method */
// optReq, err := ic.NewRequest(ic.MethodOPTIONS, "icap://127.0.0.1:1344/respmod", nil, nil)
//
// if err != nil {
// log.Fatal(err)
// return
// }
//
// /* making the icap client responsible for making the requests */
// client := &ic.Client{
// Timeout: 5 * time.Second,
// }
//
// /* making the OPTIONS request call */
// optResp, err := client.Do(optReq)
//
// if err != nil {
// log.Fatal(err)
// return
// }
//
// /* making a icap request with RESPMOD method */
// req, err := ic.NewRequest(ic.MethodRESPMOD, "icap://127.0.0.1:1344/respmod", httpReq, httpResp)
//
// if err != nil {
// log.Fatal(err)
// }
//
// req.SetPreview(optResp.PreviewBytes) // setting the preview bytes obtained from the OPTIONS call
//
// /* making the RESPMOD request call */
// resp, err := client.Do(req)
//
// if err != nil {
// log.Fatal(err)
// }
//
// fmt.Println(resp.StatusCode)
//
// }
// See https://github.com/egirna/icap-client/examples.
package icapclient
+99
View File
@@ -0,0 +1,99 @@
package icapclient
import (
"bufio"
"context"
"errors"
"fmt"
"strings"
"time"
)
// Driver os the one responsible for driving the transport layer operations
type Driver struct {
Host string
Port int
DialerTimeout time.Duration
ReadTimeout time.Duration
WriteTimeout time.Duration
tcp *transport
}
// NewDriver is the factory function for Driver
func NewDriver(host string, port int) *Driver {
return &Driver{
Host: host,
Port: port,
}
}
// Connect fires up a tcp socket connection with the icap server
func (d *Driver) Connect() error {
d.tcp = &transport{
network: "tcp",
addr: fmt.Sprintf("%s:%d", d.Host, d.Port),
timeout: d.DialerTimeout,
readTimeout: d.ReadTimeout,
writeTimeout: d.WriteTimeout,
}
return d.tcp.dial()
}
// ConnectWithContext connects to the server satisfying the context
func (d *Driver) ConnectWithContext(ctx context.Context) error {
d.tcp = &transport{
network: "tcp",
addr: fmt.Sprintf("%s:%d", d.Host, d.Port),
timeout: d.DialerTimeout,
readTimeout: d.ReadTimeout,
writeTimeout: d.WriteTimeout,
}
return d.tcp.dialWithContext(ctx)
}
// Close closes the socket connection
func (d *Driver) Close() error {
if d.tcp == nil {
return errors.New(ErrConnectionNotOpen)
}
return d.tcp.close()
}
// Send sends a request to the icap server
func (d *Driver) Send(data []byte) error {
_, err := d.tcp.write(data)
if err != nil {
return err
}
return nil
}
// Receive returns the respone from the tcp socket connection
func (d *Driver) Receive() (*Response, error) {
msg, err := d.tcp.read()
if err != nil {
return nil, err
}
resp, err := ReadResponse(bufio.NewReader(strings.NewReader(msg)))
if err != nil {
return nil, err
}
logDebug("The final *ic.Response from tcp messages...")
dumpDebug(resp)
return resp, nil
}
+124
View File
@@ -0,0 +1,124 @@
package icapclient
import (
"bytes"
"io/ioutil"
"net/http"
"os"
"strconv"
)
// SetPreview sets the preview bytes in the icap header
func (r *Request) SetPreview(maxBytes int) error {
bodyBytes := []byte{}
previewBytes := 0
// receiving the body bites to determine the preview bytes depending on the request ICAP method
if r.Method == MethodREQMOD {
if r.HTTPRequest == nil {
return nil
}
if r.HTTPRequest.Body != nil {
var err error
bodyBytes, err = ioutil.ReadAll(r.HTTPRequest.Body)
if err != nil {
return err
}
defer r.HTTPRequest.Body.Close()
}
}
if r.Method == MethodRESPMOD {
if r.HTTPResponse == nil {
return nil
}
if r.HTTPResponse.Body != nil {
var err error
bodyBytes, err = ioutil.ReadAll(r.HTTPResponse.Body)
if err != nil {
return err
}
defer r.HTTPResponse.Body.Close()
}
}
previewBytes = len(bodyBytes)
if previewBytes > 0 { // if the preview byte is 0 or less, there is no question of the body fitting insides
r.bodyFittedInPreview = true
}
if previewBytes > maxBytes { // if the preview bytes is greater than what was mentioned by the ICAP Server(did not fit in the body)
previewBytes = maxBytes
r.bodyFittedInPreview = false
r.remainingPreviewBytes = bodyBytes[maxBytes:] // storing the rest of the body byte which were not sent as preview for further operations
}
// returning the body back to the http message depending on the request method
if r.Method == MethodREQMOD {
r.HTTPRequest.Body = ioutil.NopCloser(bytes.NewReader(bodyBytes))
}
if r.Method == MethodRESPMOD {
r.HTTPResponse.Body = ioutil.NopCloser(bytes.NewReader(bodyBytes))
}
// finally assinging the preview informations including setting the header
r.Header.Set("Preview", strconv.Itoa(previewBytes))
r.PreviewBytes = previewBytes
r.previewSet = true
return nil
}
// SetDefaultRequestHeaders assigns some of the headers with its default value if they are not set already
func (r *Request) SetDefaultRequestHeaders() {
if _, exists := r.Header["Allow"]; !exists {
r.Header.Add("Allow", "204") // assigning 204 by default if Allow not provided
}
if _, exists := r.Header["Host"]; !exists {
hostName, _ := os.Hostname()
r.Header.Add("Host", hostName)
}
}
// ExtendHeader extends the current ICAP Request header with a new header
func (r *Request) ExtendHeader(hdr http.Header) error {
for header, values := range hdr {
if header == PreviewHeader && r.previewSet {
continue
}
if header == EncapsulatedHeader {
continue
}
for _, value := range values {
if header == PreviewHeader {
pb, err := strconv.Atoi(value)
if err != nil {
return err
}
if err := r.SetPreview(pb); err != nil {
return err
}
continue
}
r.Header.Add(header, value)
}
}
return nil
}
+9
View File
@@ -0,0 +1,9 @@
package icapclient
var (
registeredMethods = map[string]bool{
MethodOPTIONS: true,
MethodRESPMOD: true,
MethodREQMOD: true,
}
)
+179
View File
@@ -0,0 +1,179 @@
package icapclient
import (
"fmt"
"regexp"
"strconv"
"strings"
)
// getStatusWithCode prepares the status code and status text from two given strings
func getStatusWithCode(str1, str2 string) (int, string, error) {
statusCode, err := strconv.Atoi(str1)
if err != nil {
return 0, "", err
}
status := strings.TrimSpace(str2)
return statusCode, status, nil
}
// getHeaderVal parses the header and its value from a tcp message string
func getHeaderVal(str string) (string, string) {
headerVals := strings.SplitN(str, ":", 2)
header := headerVals[0]
val := ""
if len(headerVals) >= 2 {
val = strings.TrimSpace(headerVals[1])
}
return header, val
}
// isRequestLine determines if the tcp message string is a request line, i.e the first line of the message or not
func isRequestLine(str string) bool {
return strings.Contains(str, ICAPVersion) || strings.Contains(str, HTTPVersion)
}
// setEncapsulatedHeaderValue generates the Encapsulated values and assigns to the ICAP request string
func setEncapsulatedHeaderValue(icapReqStr *string, httpReqStr, httpRespStr string) {
encpVal := " "
if strings.HasPrefix(*icapReqStr, MethodOPTIONS) { // if the request method is OPTIONS
if httpReqStr == "" && httpRespStr == "" { // the most common case for OPTIONS method, no Encapsulated body
encpVal += "null-body=0"
} else {
encpVal += "opt-body=0" // if there is an Encapsulated body
}
}
if strings.HasPrefix(*icapReqStr, MethodREQMOD) || strings.HasPrefix(*icapReqStr, MethodRESPMOD) { // if the request method is RESPMOD or REQMOD
re := regexp.MustCompile(DoubleCRLF) // looking for the match of the string \r\n\r\n, as that is the expression that seperates each blocks, i.e headers and bodies
reqIndices := re.FindAllStringIndex(httpReqStr, -1) // getting the offsets of the matches, tells us the starting/ending point of headers and bodies
reqEndsAt := 0 // this is needed to calculate the response headers by adding the last offset of the request block
if reqIndices != nil {
encpVal += "req-hdr=0"
reqEndsAt = reqIndices[0][1]
if len(reqIndices) > 1 { // indicating there is a body present for the request block, as length would have been 1 for a single match of \r\n\r\n
encpVal += fmt.Sprintf(", req-body=%d", reqIndices[0][1]) // assigning the starting point of the body
reqEndsAt = reqIndices[1][1]
} else if httpRespStr == "" {
encpVal += fmt.Sprintf(", null-body=%d", reqIndices[0][1])
}
if httpRespStr != "" {
encpVal += ", "
}
}
respIndices := re.FindAllStringIndex(httpRespStr, -1)
if respIndices != nil {
encpVal += fmt.Sprintf("res-hdr=%d", reqEndsAt)
if len(respIndices) > 1 {
encpVal += fmt.Sprintf(", res-body=%d", reqEndsAt+respIndices[0][1])
} else {
encpVal += fmt.Sprintf(", null-body=%d", reqEndsAt+respIndices[0][1])
}
}
}
*icapReqStr = fmt.Sprintf(*icapReqStr, encpVal) // formatting the ICAP request Encapsulated header with the value
}
// replaceRequestURIWithActualURL replaces the just the escaped portion of the url with the entire URL in the dumped request message
func replaceRequestURIWithActualURL(str *string, uri, url string) {
if uri == "" {
uri = "/"
}
*str = strings.Replace(*str, uri, url, 1)
}
// addFullBodyInPreviewIndicator adds 0; ieof\r\n\r\n which indicates the entire body fitted in preview
func addFullBodyInPreviewIndicator(str *string) {
*str = strings.TrimSuffix(*str, DoubleCRLF)
*str += fullBodyEndIndicatorPreviewMode
}
// splitBodyAndHeader separates header and body from a http message
func splitBodyAndHeader(str string) (string, string, bool) {
ss := strings.SplitN(str, DoubleCRLF, 2)
if len(ss) < 2 || ss[1] == "" {
return "", "", false
}
headerStr := ss[0]
bodyStr := ss[1]
return headerStr, bodyStr, true
}
// bodyAlreadyChunked determines if the http body is already chunked from the origin server or not
func bodyAlreadyChunked(str string) bool {
_, bodyStr, ok := splitBodyAndHeader(str)
if !ok {
return false
}
r := regexp.MustCompile("\\r\\n0(\\r\\n)+$")
return r.MatchString(bodyStr)
}
// parsePreviewBodyBytes parses the preview portion of the body and only keeps that in the message
func parsePreviewBodyBytes(str *string, pb int) {
headerStr, bodyStr, ok := splitBodyAndHeader(*str)
if !ok {
return
}
bodyStr = bodyStr[:pb]
*str = headerStr + DoubleCRLF + bodyStr
}
// addHexaBodyByteNotations adds the hexadecimal byte notaions in the messages
// for example: Hello World, becomes
// b
// Hello World
// 0
func addHexaBodyByteNotations(bodyStr *string) {
bodyBytes := []byte(*bodyStr)
*bodyStr = fmt.Sprintf("%x%s%s%s", len(bodyBytes), CRLF, *bodyStr, bodyEndIndicator)
}
// mergeHeaderAndBody merges the header and body of the http message togather
func mergeHeaderAndBody(src *string, headerStr, bodyStr string) {
*src = headerStr + DoubleCRLF + bodyStr
}
func chunkBodyByBytes(bdyByte []byte, cl int) []byte {
newBytes := []byte{}
for i := 0; i < len(bdyByte); i += cl {
end := i + cl
if end > len(bdyByte) {
end = len(bdyByte)
}
newBytes = append(newBytes, []byte(fmt.Sprintf("%x\r\n", len(bdyByte[i:end]))+string(bdyByte[i:end]))...)
}
newBytes = append(newBytes, []byte(bodyEndIndicator)...)
return newBytes
}
+160
View File
@@ -0,0 +1,160 @@
package icapclient
import (
"context"
"fmt"
"net/http"
"net/http/httputil"
"net/url"
"strings"
)
// Request represents the icap client request data
type Request struct {
Method string
URL *url.URL
Header http.Header
HTTPRequest *http.Request
HTTPResponse *http.Response
ChunkLength int
PreviewBytes int
ctx *context.Context
previewSet bool
bodyFittedInPreview bool
remainingPreviewBytes []byte
}
// NewRequest is the factory function for Request
func NewRequest(method, urlStr string, httpReq *http.Request, httpResp *http.Response) (*Request, error) {
method = strings.ToUpper(method)
u, err := url.Parse(urlStr)
if err != nil {
return nil, err
}
req := &Request{
Method: method,
URL: u,
Header: make(map[string][]string),
HTTPRequest: httpReq,
HTTPResponse: httpResp,
}
if err := req.Validate(); err != nil {
return nil, err
}
return req, nil
}
// DumpRequest returns the given request in its ICAP/1.x wire
// representation.
func DumpRequest(req *Request) ([]byte, error) {
// Making the ICAP message block
reqStr := fmt.Sprintf("%s %s %s%s", req.Method, req.URL.String(), ICAPVersion, CRLF)
for headerName, vals := range req.Header {
for _, val := range vals {
reqStr += fmt.Sprintf("%s: %s%s", headerName, val, CRLF)
}
}
reqStr += "Encapsulated: %s" + CRLF // will populate the Encapsulated header value after making the http Request & Response messages
reqStr += CRLF
// Making the HTTP Request message block
httpReqStr := ""
if req.HTTPRequest != nil {
b, err := httputil.DumpRequestOut(req.HTTPRequest, true)
if err != nil {
return nil, err
}
httpReqStr += string(b)
replaceRequestURIWithActualURL(&httpReqStr, req.HTTPRequest.URL.EscapedPath(), req.HTTPRequest.URL.String())
if req.Method == MethodREQMOD {
if req.previewSet {
parsePreviewBodyBytes(&httpReqStr, req.PreviewBytes)
}
if !bodyAlreadyChunked(httpReqStr) {
headerStr, bodyStr, ok := splitBodyAndHeader(httpReqStr)
if ok {
addHexaBodyByteNotations(&bodyStr)
mergeHeaderAndBody(&httpReqStr, headerStr, bodyStr)
}
}
}
if httpReqStr != "" { // if the HTTP Request message block doesn't end with a \r\n\r\n, then going to add one by force for better calculation of byte offsets
for !strings.HasSuffix(httpReqStr, DoubleCRLF) {
httpReqStr += CRLF
}
}
}
// Making the HTTP Response message block
httpRespStr := ""
if req.HTTPResponse != nil {
b, err := httputil.DumpResponse(req.HTTPResponse, true)
if err != nil {
return nil, err
}
httpRespStr += string(b)
if req.previewSet {
parsePreviewBodyBytes(&httpRespStr, req.PreviewBytes)
}
if !bodyAlreadyChunked(httpRespStr) {
headerStr, bodyStr, ok := splitBodyAndHeader(httpRespStr)
if ok {
addHexaBodyByteNotations(&bodyStr)
mergeHeaderAndBody(&httpRespStr, headerStr, bodyStr)
}
}
if httpRespStr != "" && !strings.HasSuffix(httpRespStr, DoubleCRLF) { // if the HTTP Response message block doesn't end with a \r\n\r\n, then going to add one by force for better calculation of byte offsets
httpRespStr += CRLF
}
}
if encpVal := req.Header.Get(EncapsulatedHeader); encpVal != "" {
reqStr = fmt.Sprintf(reqStr, encpVal)
} else {
//populating the Encapsulated header of the ICAP message portion
setEncapsulatedHeaderValue(&reqStr, httpReqStr, httpRespStr)
}
// determining if the http message needs the full body fitted in the preview portion indicator or not
if httpRespStr != "" && req.previewSet && req.bodyFittedInPreview {
addFullBodyInPreviewIndicator(&httpRespStr)
}
if req.Method == MethodREQMOD && req.previewSet && req.bodyFittedInPreview {
addFullBodyInPreviewIndicator(&httpReqStr)
}
data := []byte(reqStr + httpReqStr + httpRespStr)
return data, nil
}
// SetContext sets a context for the ICAP request
func (r *Request) SetContext(ctx context.Context) { // TODO: make context take control over the whole operation
r.ctx = &ctx
}
+123
View File
@@ -0,0 +1,123 @@
package icapclient
import (
"bufio"
"errors"
"net/http"
"strconv"
"strings"
)
// Response represents the icap server response data
type Response struct {
StatusCode int
Status string
PreviewBytes int
Header http.Header
ContentRequest *http.Request
ContentResponse *http.Response
}
var (
optionValues = map[string]bool{
PreviewHeader: true,
MethodsHeader: true,
AllowHeader: true,
TransferPreviewHeader: true,
ServiceHeader: true,
ISTagHeader: true,
OptBodyTypeHeader: true,
MaxConnectionsHeader: true,
OptionsTTLHeader: true,
ServiceIDHeader: true,
TransferIgnoreHeader: true,
TransferCompleteHeader: true,
}
)
// ReadResponse converts a Reader to a icapclient Response
func ReadResponse(b *bufio.Reader) (*Response, error) {
resp := &Response{
Header: make(map[string][]string),
}
scheme := ""
httpMsg := ""
for currentMsg, err := b.ReadString('\n'); err == nil || currentMsg != ""; currentMsg, err = b.ReadString('\n') { // keep reading the buffer message which is the http response message
if isRequestLine(currentMsg) { // if the current message line if the first line of the message portion(request line)
ss := strings.Split(currentMsg, " ")
if len(ss) < 3 { // must contain 3 words, for example: "ICAP/1.0 200 OK" or "GET /something HTTP/1.1"
return nil, errors.New(ErrInvalidTCPMsg + ":" + currentMsg)
}
// preparing the scheme below
if ss[0] == ICAPVersion {
scheme = SchemeICAP
resp.StatusCode, resp.Status, err = getStatusWithCode(ss[1], strings.Join(ss[2:], " "))
if err != nil {
return nil, err
}
continue
}
if ss[0] == HTTPVersion {
scheme = SchemeHTTPResp
httpMsg = ""
}
if strings.TrimSpace(ss[2]) == HTTPVersion { // for a http request message if the scheme version is always at last, for example: GET /something HTTP/1.1
scheme = SchemeHTTPReq
httpMsg = ""
}
}
// preparing the header for ICAP & contents for HTTP messages below
if scheme == SchemeICAP {
if currentMsg == LF || currentMsg == CRLF { // don't want to count the Line Feed as header
continue
}
header, val := getHeaderVal(currentMsg)
if header == PreviewHeader {
pb, _ := strconv.Atoi(val)
resp.PreviewBytes = pb
}
resp.Header.Add(header, val)
}
if scheme == SchemeHTTPReq {
httpMsg += strings.TrimSpace(currentMsg) + CRLF
bufferEmpty := b.Buffered() == 0
if currentMsg == CRLF || bufferEmpty { // a CRLF indicates the end of a http message and the buffer check is just in case the buffer eneded with one last message instead of a CRLF
var erR error
resp.ContentRequest, erR = http.ReadRequest(bufio.NewReader(strings.NewReader(httpMsg)))
if erR != nil {
return nil, erR
}
continue
}
}
if scheme == SchemeHTTPResp {
httpMsg += strings.TrimSpace(currentMsg) + CRLF
bufferEmpty := b.Buffered() == 0
if currentMsg == CRLF || bufferEmpty {
var erR error
resp.ContentResponse, erR = http.ReadResponse(bufio.NewReader(strings.NewReader(httpMsg)), resp.ContentRequest)
if erR != nil {
return nil, erR
}
continue
}
}
}
return resp, nil
}
+152
View File
@@ -0,0 +1,152 @@
package icapclient
import (
"bytes"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
"github.com/egirna/icap"
)
var (
stop = make(chan os.Signal, 1)
port = 1344
)
const (
previewBytes = 24
goodFileDetectStr = "GOOD FILE"
badFileDetectStr = "BAD FILE"
goodURL = "http://goodifle.com"
badURL = "http://badfile.com"
)
func startTestServer() {
icap.HandleFunc("/respmod", respmodHandler)
icap.HandleFunc("/reqmod", reqmodHandler)
log.Println("Starting ICAP test server...")
signal.Notify(stop, syscall.SIGKILL, syscall.SIGINT, syscall.SIGQUIT)
go func() {
if err := icap.ListenAndServe(fmt.Sprintf(":%d", port), nil); err != nil {
log.Println("Failed to start ICAP test server: ", err.Error())
return
}
}()
time.Sleep(5 * time.Millisecond)
log.Printf("ICAP test server is running on localhost:%d\n...\n", port)
<-stop
log.Println("ICAP test server is shut down!")
}
func stopTestServer() {
stop <- syscall.SIGKILL
}
func respmodHandler(w icap.ResponseWriter, req *icap.Request) {
h := w.Header()
h.Set("ISTag", "ICAP-TEST")
h.Set("Service", "ICAP-TEST-SERVICE")
switch req.Method {
case "OPTIONS":
h.Set("Methods", "RESPMOD")
h.Set("Allow", "204")
if previewBytes > 0 {
h.Set("Preview", strconv.Itoa(previewBytes))
}
h.Set("Transfer-Preview", "*")
w.WriteHeader(http.StatusOK, nil, false)
case "RESPMOD":
defer req.Response.Body.Close()
if val, exist := req.Header["Allow"]; !exist || (len(val) > 0 && val[0] != "204") {
w.WriteHeader(http.StatusNoContent, nil, false)
return
}
// log.Println("The preview data: ", string(req.Preview))
buf := &bytes.Buffer{}
if _, err := io.Copy(buf, req.Response.Body); err != nil {
log.Println("Failed to copy the response body to buffer: ", err.Error())
w.WriteHeader(http.StatusNoContent, nil, false)
return
}
status := 0
if strings.Contains(buf.String(), goodFileDetectStr) {
status = http.StatusNoContent
}
if strings.Contains(buf.String(), badFileDetectStr) {
status = http.StatusOK
}
w.WriteHeader(status, nil, false)
}
}
func reqmodHandler(w icap.ResponseWriter, req *icap.Request) {
h := w.Header()
h.Set("ISTag", "ICAP-TEST")
h.Set("Service", "ICAP-TEST-SERVICE")
switch req.Method {
case "OPTIONS":
h.Set("Methods", "REQMOD")
h.Set("Allow", "204")
if previewBytes > 0 {
h.Set("Preview", strconv.Itoa(previewBytes))
}
h.Set("Transfer-Preview", "*")
w.WriteHeader(http.StatusOK, nil, false)
case "REQMOD":
if val, exist := req.Header["Allow"]; !exist || (len(val) > 0 && val[0] != "204") {
w.WriteHeader(http.StatusNoContent, nil, false)
return
}
// log.Println("The preview data: ", string(req.Preview))
fileURL := req.Request.RequestURI
status := 0
if fileURL == goodURL {
status = http.StatusNoContent
}
if fileURL == badURL {
status = http.StatusOK
}
w.WriteHeader(status, nil, false)
}
}
func testServerRunning() bool {
lstnr, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
return true
}
lstnr.Close()
return false
}
+123
View File
@@ -0,0 +1,123 @@
package icapclient
import (
"context"
"io"
"net"
"strings"
"time"
)
// transport represents the transport layer data
type transport struct {
network string
addr string
timeout time.Duration
readTimeout time.Duration
writeTimeout time.Duration
sckt net.Conn
}
// dial fires up a tcp socket
func (t *transport) dial() error {
sckt, err := net.DialTimeout(t.network, t.addr, t.timeout)
if err != nil {
return err
}
if err := sckt.SetReadDeadline(time.Now().UTC().Add(t.readTimeout)); err != nil {
return err
}
if err := sckt.SetWriteDeadline(time.Now().UTC().Add(t.writeTimeout)); err != nil {
return err
}
t.sckt = sckt
return nil
}
// dialWithContext fires up a tcp socket
func (t *transport) dialWithContext(ctx context.Context) error {
sckt, err := (&net.Dialer{
Timeout: t.timeout,
}).DialContext(ctx, t.network, t.addr)
if err != nil {
return err
}
if err := sckt.SetReadDeadline(time.Now().UTC().Add(t.readTimeout)); err != nil {
return err
}
if err := sckt.SetWriteDeadline(time.Now().UTC().Add(t.writeTimeout)); err != nil {
return err
}
t.sckt = sckt
return nil
}
// Write writes data to the server
func (t *transport) write(data []byte) (int, error) {
logDebug("Dumping the message being sent to the server...")
dumpDebug(string(data))
return t.sckt.Write(data)
}
// Read reads data from server
func (t *transport) read() (string, error) {
data := make([]byte, 0)
logDebug("Dumping messages received from the server...")
for {
tmp := make([]byte, 1096)
n, err := t.sckt.Read(tmp)
if err != nil {
if err == io.EOF {
logDebug("End of file detected from EOF error")
break
}
return "", err
}
if n == 0 {
logDebug("End of file detected by 0 bytes")
break
}
data = append(data, tmp[:n]...)
if string(data) == icap100ContinueMsg { // explicitly breaking because the Read blocks for 100 continue message // TODO: find out why
logDebug("Stopping because got 100 Continue from the server")
break
}
if strings.HasSuffix(string(data), "0\r\n\r\n") {
logDebug("End of the file detected by 0 Double CRLF indicator")
break
}
if strings.Contains(string(data), icap204NoModsMsg) {
logDebug("End of file detected by 204 no modifications and Double CRLF at the end")
break
}
dumpDebug(string(tmp))
}
return string(data), nil
}
// close closes the tcp connection
func (t *transport) close() error {
return t.sckt.Close()
}
+63
View File
@@ -0,0 +1,63 @@
package icapclient
import (
"errors"
"net/http"
"net/url"
)
// validMethod validates the ICAP method
func validMethod(method string) (bool, error) {
if _, registered := registeredMethods[method]; !registered {
return false, errors.New(ErrMethodNotRegistered)
}
return true, nil
}
// validURL validates the Server URL provided
func validURL(url *url.URL) (bool, error) {
if url.Scheme != SchemeICAP {
return false, errors.New(ErrInvalidScheme)
}
if url.Host == "" {
return false, errors.New(ErrInvalidHost)
}
return true, nil
}
// validMethodWithHTTP validates if the ICAP request method and the http messages are alligned or not
func validMethodWithHTTP(httpReq *http.Request, httpResp *http.Response, method string) (bool, error) {
if method == MethodREQMOD && httpReq == nil {
return false, errors.New(ErrREQMODWithNoReq)
}
if method == MethodREQMOD && httpResp != nil {
return false, errors.New(ErrREQMODWithResp)
}
if method == MethodRESPMOD && httpResp == nil {
return false, errors.New(ErrRESPMODWithNoResp)
}
return true, nil
}
// Validate validates the ICAP request
func (r *Request) Validate() error {
if valid, err := validMethod(r.Method); !valid {
return err
}
if valid, err := validURL(r.URL); !valid {
return err
}
if valid, err := validMethodWithHTTP(r.HTTPRequest, r.HTTPResponse, r.Method); !valid {
return err
}
return nil
}
+7
View File
@@ -0,0 +1,7 @@
~$
\.swp$
\.[568]$
\.out$
^_
\.orig$
example/example
+27
View File
@@ -0,0 +1,27 @@
Copyright (c) 2018, Eliezer Croitoru NgTech LTD
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* 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.
* Neither the name of go-icap nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
+77
View File
@@ -0,0 +1,77 @@
// Copyright 2011 Andy Balholm. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// A bridge between ICAP and HTTP.
// It allows answering a REQMOD request with an HTTP response generated locally.
package icap
import (
"log"
"net/http"
"time"
)
type bridgedRespWriter struct {
irw ResponseWriter // the underlying icap.ResponseWriter
header http.Header // the headers for the HTTP response
wroteHeader bool // Have the headers been written yet?
}
func (w *bridgedRespWriter) Header() http.Header {
return w.header
}
func (w *bridgedRespWriter) Write(p []byte) (n int, err error) {
if !w.wroteHeader {
w.WriteHeader(http.StatusOK)
}
return w.irw.Write(p)
}
func (w *bridgedRespWriter) WriteHeader(code int) {
if w.wroteHeader {
log.Print("http: multiple response.WriteHeader calls")
return
}
w.wroteHeader = true
// Default output is HTML encoded in UTF-8.
if w.header.Get("Content-Type") == "" {
w.header.Set("Content-Type", "text/html; charset=utf-8")
}
if _, ok := w.header["Date"]; !ok {
w.Header().Set("Date", time.Now().UTC().Format(http.TimeFormat))
}
resp := new(http.Response)
resp.StatusCode = code
resp.Header = w.header
w.irw.WriteHeader(200, resp, true)
}
// NewBridgedResponseWriter Create an http.ResponseWriter that encapsulates its response in an ICAP response.
func NewBridgedResponseWriter(w ResponseWriter) http.ResponseWriter {
rw := new(bridgedRespWriter)
rw.header = make(http.Header)
rw.irw = w
return rw
}
// ServeLocally Pass use the local HTTP server to generate a response for an ICAP request.
func ServeLocally(w ResponseWriter, req *Request) {
brw := NewBridgedResponseWriter(w)
http.DefaultServeMux.ServeHTTP(brw, req.Request)
}
// ServeLocallyFromHandler ---
func ServeLocallyFromHandler(w ResponseWriter, req *Request, mux http.Handler) {
brw := NewBridgedResponseWriter(w)
mux.ServeHTTP(brw, req.Request)
}
+181
View File
@@ -0,0 +1,181 @@
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The wire protocol for HTTP's "chunked" Transfer-Encoding.
// This code is derived from the standard library's http/httputil/chunked.go,
package icap
import (
"bufio"
"errors"
"fmt"
"io"
)
const maxLineLength = 4096 // assumed <= bufio.defaultBufSize
var errLineTooLong = errors.New("header line too long")
// NewChunkedReader returns a new chunkedReader that translates the data read from r
// out of HTTP "chunked" format before returning it.
// The chunkedReader returns io.EOF when the final 0-length chunk is read.
//
// NewChunkedReader is not needed by normal applications. The http package
// automatically decodes chunking when reading response bodies.
func newChunkedReader(r io.Reader) io.Reader {
br, ok := r.(*bufio.Reader)
if !ok {
br = bufio.NewReader(r)
}
return &chunkedReader{r: br}
}
type chunkedReader struct {
r *bufio.Reader
n uint64 // unread bytes in chunk
err error
buf [2]byte
}
func (cr *chunkedReader) beginChunk() {
// chunk-size CRLF
var line []byte
line, cr.err = readLine(cr.r)
if cr.err != nil {
return
}
cr.n, cr.err = parseHexUint(line)
if cr.err != nil {
return
}
if cr.n == 0 {
cr.err = io.EOF
}
}
func (cr *chunkedReader) Read(b []uint8) (n int, err error) {
if cr.err != nil {
return 0, cr.err
}
if cr.n == 0 {
cr.beginChunk()
if cr.err != nil {
return 0, cr.err
}
}
if uint64(len(b)) > cr.n {
b = b[0:cr.n]
}
n, cr.err = cr.r.Read(b)
cr.n -= uint64(n)
if cr.n == 0 && cr.err == nil {
// end of chunk (CRLF)
if _, cr.err = io.ReadFull(cr.r, cr.buf[:]); cr.err == nil {
if cr.buf[0] != '\r' || cr.buf[1] != '\n' {
cr.err = errors.New("malformed chunked encoding")
}
}
}
return n, cr.err
}
// Read a line of bytes (up to \n) from b.
// Give up if the line exceeds maxLineLength.
// The returned bytes are a pointer into storage in
// the bufio, so they are only valid until the next bufio read.
func readLine(b *bufio.Reader) (p []byte, err error) {
if p, err = b.ReadSlice('\n'); err != nil {
// We always know when EOF is coming.
// If the caller asked for a line, there should be a line.
if err == io.EOF {
err = io.ErrUnexpectedEOF
} else if err == bufio.ErrBufferFull {
err = errLineTooLong
}
return nil, err
}
if len(p) >= maxLineLength {
return nil, errLineTooLong
}
return trimTrailingWhitespace(p), nil
}
func trimTrailingWhitespace(b []byte) []byte {
for len(b) > 0 && isASCIISpace(b[len(b)-1]) {
b = b[:len(b)-1]
}
return b
}
func isASCIISpace(b byte) bool {
return b == ' ' || b == '\t' || b == '\n' || b == '\r'
}
// NewChunkedWriter returns a new chunkedWriter that translates writes into HTTP
// "chunked" format before writing them to w. Closing the returned chunkedWriter
// sends the final 0-length chunk that marks the end of the stream.
//
// NewChunkedWriter is not needed by normal applications. The http
// package adds chunking automatically if handlers don't set a
// Content-Length header. Using NewChunkedWriter inside a handler
// would result in double chunking or chunking with a Content-Length
// length, both of which are wrong.
func NewChunkedWriter(w io.Writer) io.WriteCloser {
return &chunkedWriter{w}
}
// Writing to chunkedWriter translates to writing in HTTP chunked Transfer
// Encoding wire format to the underlying Wire chunkedWriter.
type chunkedWriter struct {
Wire io.Writer
}
// Write the contents of data as one chunk to Wire.
// NOTE: Note that the corresponding chunk-writing procedure in Conn.Write has
// a bug since it does not check for success of io.WriteString
func (cw *chunkedWriter) Write(data []byte) (n int, err error) {
// Don't send 0-length data. It looks like EOF for chunked encoding.
if len(data) == 0 {
return 0, nil
}
if _, err = fmt.Fprintf(cw.Wire, "%x\r\n", len(data)); err != nil {
return 0, err
}
if n, err = cw.Wire.Write(data); err != nil {
return
}
if n != len(data) {
err = io.ErrShortWrite
return
}
_, err = io.WriteString(cw.Wire, "\r\n")
return
}
func (cw *chunkedWriter) Close() error {
_, err := io.WriteString(cw.Wire, "0\r\n")
return err
}
func parseHexUint(v []byte) (n uint64, err error) {
for _, b := range v {
n <<= 4
switch {
case '0' <= b && b <= '9':
b = b - '0'
case 'a' <= b && b <= 'f':
b = b - 'a' + 10
case 'A' <= b && b <= 'F':
b = b - 'A' + 10
default:
return 0, fmt.Errorf("invalid chunk length: '%s'", v)
}
n |= uint64(b)
}
return
}
+193
View File
@@ -0,0 +1,193 @@
// Copyright 2011 Andy Balholm. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package icap
import (
"net/http"
"net/url"
"path"
"strings"
)
// ServeMux is an ICAP request multiplexer.
// It matches the URL of each incoming request against a list of registered
// patterns and calls the handler for the pattern that
// most closely matches the URL.
//
// For more details, see the documentation for http.ServeMux
type ServeMux struct {
m map[string]Handler
}
// NewServeMux allocates and returns a new ServeMux.
func NewServeMux() *ServeMux { return &ServeMux{make(map[string]Handler)} }
// DefaultServeMux is the default ServeMux used by Serve.
var DefaultServeMux = NewServeMux()
// Does path match pattern?
func pathMatch(pattern, path string) bool {
if len(pattern) == 0 {
// should not happen
return false
}
n := len(pattern)
if pattern[n-1] != '/' {
return pattern == path
}
return len(path) >= n && path[0:n] == pattern
}
// Return the canonical path for p, eliminating . and .. elements.
func cleanPath(p string) string {
if p == "" {
return "/"
}
if p[0] != '/' {
p = "/" + p
}
np := path.Clean(p)
// path.Clean removes trailing slash except for root;
// put the trailing slash back if necessary.
if p[len(p)-1] == '/' && np != "/" {
np += "/"
}
return np
}
// Find a handler on a handler map given a path string
// Most-specific (longest) pattern wins
func (mux *ServeMux) match(path string) Handler {
var h Handler
var n = 0
for k, v := range mux.m {
if !pathMatch(k, path) {
continue
}
if h == nil || len(k) > n {
n = len(k)
h = v
}
}
return h
}
// ServeICAP dispatches the request to the handler whose
// pattern most closely matches the request URL.
func (mux *ServeMux) ServeICAP(w ResponseWriter, r *Request) {
// Clean path to canonical form and redirect.
if p := cleanPath(r.URL.Path); p != r.URL.Path {
w.Header().Set("Location", p)
w.WriteHeader(http.StatusMovedPermanently, nil, false)
return
}
// Host-specific pattern takes precedence over generic ones
h := mux.match(r.URL.Host + r.URL.Path)
if h == nil {
h = mux.match(r.URL.Path)
}
if h == nil {
h = NotFoundHandler()
}
h.ServeICAP(w, r)
}
// Handle registers the handler for the given pattern.
func (mux *ServeMux) Handle(pattern string, handler Handler) {
if pattern == "" {
panic("icap: invalid pattern " + pattern)
}
mux.m[pattern] = handler
// Helpful behavior:
// If pattern is /tree/, insert permanent redirect for /tree.
n := len(pattern)
if n > 0 && pattern[n-1] == '/' {
mux.m[pattern[0:n-1]] = RedirectHandler(pattern, http.StatusMovedPermanently)
}
}
// HandleFunc registers the handler function for the given pattern.
func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
mux.Handle(pattern, HandlerFunc(handler))
}
// Handle registers the handler for the given pattern
// in the DefaultServeMux.
// The documentation for ServeMux explains how patterns are matched.
func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }
// HandleFunc registers the handler function for the given pattern
// in the DefaultServeMux.
// The documentation for ServeMux explains how patterns are matched.
func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
DefaultServeMux.HandleFunc(pattern, handler)
}
// NotFound replies to the request with an HTTP 404 not found error.
func NotFound(w ResponseWriter, r *Request) {
w.WriteHeader(http.StatusNotFound, nil, false)
}
// NotFoundHandler returns a simple request handler
// that replies to each request with a ``404 page not found'' reply.
func NotFoundHandler() Handler { return HandlerFunc(NotFound) }
// Redirect to a fixed URL
type redirectHandler struct {
url string
code int
}
func (rh *redirectHandler) ServeICAP(w ResponseWriter, r *Request) {
Redirect(w, r, rh.url, rh.code)
}
// RedirectHandler returns a request handler that redirects
// each request it receives to the given url using the given
// status code.
func RedirectHandler(redirectURL string, code int) Handler {
return &redirectHandler{redirectURL, code}
}
// Redirect replies to the request with a redirect to url,
// which may be a path relative to the request path.
func Redirect(w ResponseWriter, r *Request, redirectURL string, code int) {
if u, err := url.Parse(redirectURL); err == nil {
// If url was relative, make absolute by
// combining with request path.
// The browser would probably do this for us,
// but doing it ourselves is more reliable.
oldpath := r.URL.Path
if oldpath == "" { // should not happen, but avoid a crash if it does
oldpath = "/"
}
if u.Scheme == "" {
// no leading icap://server
if redirectURL == "" || redirectURL[0] != '/' {
// make relative path absolute
olddir, _ := path.Split(oldpath)
redirectURL = olddir + redirectURL
}
var query string
if i := strings.Index(redirectURL, "?"); i != -1 {
redirectURL, query = redirectURL[:i], redirectURL[i:]
}
// clean up but preserve trailing slash
trailing := redirectURL[len(redirectURL)-1] == '/'
redirectURL = path.Clean(redirectURL)
if trailing && redirectURL[len(redirectURL)-1] != '/' {
redirectURL += "/"
}
redirectURL += query
}
}
w.Header().Set("Location", redirectURL)
w.WriteHeader(code, nil, false)
}
+253
View File
@@ -0,0 +1,253 @@
// Copyright 2011 Andy Balholm. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Reading and parsing of ICAP requests.
// Package icap provides an extensible ICAP server.
package icap
import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/textproto"
"net/url"
"strconv"
"strings"
)
type badStringError struct {
what string
str string
}
func (e *badStringError) Error() string { return fmt.Sprintf("%s %q", e.what, e.str) }
// A Request represents a parsed ICAP request.
type Request struct {
Method string // REQMOD, RESPMOD, OPTIONS, etc.
RawURL string // The URL given in the request.
URL *url.URL // Parsed URL.
Proto string // The protocol version.
Header textproto.MIMEHeader // The ICAP header
RemoteAddr string // the address of the computer sending the request
Preview []byte // the body data for an ICAP preview
// The HTTP messages.
Request *http.Request
Response *http.Response
}
// ReadRequest reads and parses a request from b.
func ReadRequest(b *bufio.ReadWriter) (req *Request, err error) {
tp := textproto.NewReader(b.Reader)
req = new(Request)
// Read first line.
var s string
s, err = tp.ReadLine()
if err != nil {
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return nil, err
}
f := strings.SplitN(s, " ", 3)
if len(f) < 3 {
return nil, &badStringError{"malformed ICAP request", s}
}
req.Method, req.RawURL, req.Proto = f[0], f[1], f[2]
req.URL, err = url.ParseRequestURI(req.RawURL)
if err != nil {
return nil, err
}
req.Header, err = tp.ReadMIMEHeader()
if err != nil {
return nil, err
}
s = req.Header.Get("Encapsulated")
if s == "" {
return req, nil // No HTTP headers or body.
}
eList := strings.Split(s, ", ")
var initialOffset, reqHdrLen, respHdrLen int
var hasBody bool
var prevKey string
var prevValue int
for _, item := range eList {
eq := strings.Index(item, "=")
if eq == -1 {
return nil, &badStringError{"malformed Encapsulated: header", s}
}
key := item[:eq]
value, err := strconv.Atoi(item[eq+1:])
if err != nil {
return nil, &badStringError{"malformed Encapsulated: header", s}
}
// Calculate the length of the previous section.
switch prevKey {
case "":
initialOffset = value
case "req-hdr":
reqHdrLen = value - prevValue
case "res-hdr":
respHdrLen = value - prevValue
case "req-body", "opt-body", "res-body", "null-body":
return nil, fmt.Errorf("%s must be the last section", prevKey)
}
switch key {
case "req-hdr", "res-hdr", "null-body":
case "req-body", "res-body", "opt-body":
hasBody = true
default:
return nil, &badStringError{"invalid key for Encapsulated: header", key}
}
prevValue = value
prevKey = key
}
// Read the HTTP headers.
var rawReqHdr, rawRespHdr []byte
if initialOffset > 0 {
junk := make([]byte, initialOffset)
_, err = io.ReadFull(b, junk)
if err != nil {
return nil, err
}
}
if reqHdrLen > 0 {
rawReqHdr = make([]byte, reqHdrLen)
_, err = io.ReadFull(b, rawReqHdr)
if err != nil {
return nil, err
}
}
if respHdrLen > 0 {
rawRespHdr = make([]byte, respHdrLen)
_, err = io.ReadFull(b, rawRespHdr)
if err != nil {
return nil, err
}
}
var bodyReader io.ReadCloser = emptyReader(0)
if hasBody {
if p := req.Header.Get("Preview"); p != "" {
moreBody := true
req.Preview, err = ioutil.ReadAll(newChunkedReader(b))
if err != nil {
if strings.Contains(err.Error(), "ieof") {
// The data ended with "0; ieof", which the HTTP chunked reader doesn't understand.
moreBody = false
err = nil
} else {
return nil, err
}
}
var r io.Reader = bytes.NewBuffer(req.Preview)
if moreBody {
r = io.MultiReader(r, &continueReader{buf: b})
}
bodyReader = ioutil.NopCloser(r)
} else {
bodyReader = ioutil.NopCloser(newChunkedReader(b))
}
}
// Construct the http.Request.
if rawReqHdr != nil {
invalidURLEscapeFixed := false
req.Request, err = http.ReadRequest(bufio.NewReader(bytes.NewBuffer(rawReqHdr)))
if err != nil && strings.Contains(err.Error(), "invalid URL escape") {
//Fix the request url
// Convert the rawReqHdr to string
// find the url\path start and end(sould be in the status line
// convert the percents into %25
// Then reparse the whole request
rawReqHdrStr := string(rawReqHdr)
result := strings.Split(rawReqHdrStr, "\n")
result[0] = strings.Replace(result[0], "%", "%25", -1)
// The next is a compromise since when adding "\r\n" it causes the request parsing to fail
newReq := strings.Join(result, "\n")
req.Request, err = http.ReadRequest(bufio.NewReader(bytes.NewBuffer([]byte(newReq))))
if err != nil {
return req, fmt.Errorf("error while parsing HTTP request: %v", err)
}
invalidURLEscapeFixed = true
}
if err != nil && !invalidURLEscapeFixed {
return req, fmt.Errorf("error while parsing HTTP request: %v", err)
}
if req.Method == "REQMOD" {
req.Request.Body = bodyReader
} else {
req.Request.Body = emptyReader(0)
}
}
// Construct the http.Response.
if rawRespHdr != nil {
request := req.Request
if request == nil {
request, _ = http.NewRequest("GET", "/", nil)
}
req.Response, err = http.ReadResponse(bufio.NewReader(bytes.NewBuffer(rawRespHdr)), request)
if err != nil {
return req, fmt.Errorf("error while parsing HTTP response: %v", err)
}
if req.Method == "RESPMOD" {
req.Response.Body = bodyReader
} else {
req.Response.Body = emptyReader(0)
}
}
return
}
// An emptyReader is an io.ReadCloser that always returns os.EOF.
type emptyReader byte
func (emptyReader) Read(p []byte) (n int, err error) {
return 0, io.EOF
}
func (emptyReader) Close() error {
return nil
}
// A continueReader sends a "100 Continue" message the first time Read
// is called, creates a ChunkedReader, and reads from that.
type continueReader struct {
buf *bufio.ReadWriter // the underlying connection
cr io.Reader // the ChunkedReader
}
func (c *continueReader) Read(p []byte) (n int, err error) {
if c.cr == nil {
_, err := c.buf.WriteString("ICAP/1.0 100 Continue\r\n\r\n")
if err != nil {
return 0, err
}
err = c.buf.Flush()
if err != nil {
return 0, err
}
c.cr = newChunkedReader(c.buf)
}
return c.cr.Read(p)
}
+229
View File
@@ -0,0 +1,229 @@
// Copyright 2011 Andy Balholm. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Responding to ICAP requests.
package icap
import (
"bytes"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/http/httputil"
"strconv"
"strings"
"time"
)
// ResponseWriter ---
type ResponseWriter interface {
// Header returns the header map that will be sent by WriteHeader.
// Changing the header after a call to WriteHeader (or Write) has
// no effect.
Header() http.Header
// Write writes the data to the connection as part of an ICAP reply.
// If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK, nil)
// before writing the data.
Write([]byte) (int, error)
// Write raw data to the connection.
WriteRaw(string)
// WriteHeader sends an ICAP response header with status code.
// Then it sends an HTTP header if httpMessage is not nil.
// httpMessage may be an *http.Request or an *http.Response.
// hasBody should be true if there will be calls to Write(), generating a message body.
WriteHeader(code int, httpMessage interface{}, hasBody bool)
}
type respWriter struct {
conn *conn // information on the connection
req *Request // the request that is being responded to
header http.Header // the ICAP header to write for the response
wroteHeader bool // true if the headers have already been written
wroteRaw bool // true if raw data was written to the connection
cw io.WriteCloser // the chunked writer used to write the body
}
func (w *respWriter) Header() http.Header {
return w.header
}
func (w *respWriter) Write(p []byte) (n int, err error) {
if !w.wroteHeader {
w.WriteHeader(http.StatusOK, nil, true)
}
if w.cw == nil {
return 0, errors.New("called Write() on an icap.ResponseWriter that should not have a body")
}
return w.cw.Write(p)
}
func (w *respWriter) WriteRaw(p string) {
bw := w.conn.buf.Writer
io.WriteString(bw, p)
w.wroteRaw = true
}
func (w *respWriter) WriteHeader(code int, httpMessage interface{}, hasBody bool) {
if w.wroteHeader {
log.Println("Called WriteHeader twice on the same connection")
return
}
// Make the HTTP header and the Encapsulated: header.
var header []byte
var encap string
var err error
switch msg := httpMessage.(type) {
case *http.Request:
header, err = httpRequestHeader(msg)
if err != nil {
break
}
if hasBody {
encap = fmt.Sprintf("req-hdr=0, req-body=%d", len(header))
} else {
encap = fmt.Sprintf("req-hdr=0, null-body=%d", len(header))
}
case *http.Response:
header, err = httpResponseHeader(msg)
if err != nil {
break
}
if hasBody {
encap = fmt.Sprintf("res-hdr=0, res-body=%d", len(header))
} else {
encap = fmt.Sprintf("res-hdr=0, null-body=%d", len(header))
}
}
if encap == "" {
if hasBody {
method := w.req.Method
if len(method) > 3 {
method = method[0:3]
}
method = strings.ToLower(method)
encap = fmt.Sprintf("%s-body=0", method)
} else {
encap = "null-body=0"
}
}
w.header.Set("Encapsulated", encap)
if _, ok := w.header["Date"]; !ok {
w.Header().Set("Date", time.Now().UTC().Format(http.TimeFormat))
}
w.header.Set("Connection", "close")
bw := w.conn.buf.Writer
status := StatusText(code)
if status == "" {
status = fmt.Sprintf("status code %d", code)
}
fmt.Fprintf(bw, "ICAP/1.0 %d %s\r\n", code, status)
w.header.Write(bw)
io.WriteString(bw, "\r\n")
if header != nil {
bw.Write(header)
}
w.wroteHeader = true
if hasBody {
w.cw = httputil.NewChunkedWriter(w.conn.buf.Writer)
}
}
func (w *respWriter) finishRequest() {
if !w.wroteHeader {
w.WriteHeader(http.StatusOK, nil, false)
}
if w.cw != nil && !w.wroteRaw {
w.cw.Close()
w.cw = nil
io.WriteString(w.conn.buf, "\r\n")
}
w.conn.buf.Flush()
}
// httpRequestHeader returns the headers for an HTTP request
// as a slice of bytes in a form suitable for including in an ICAP message.
func httpRequestHeader(req *http.Request) (hdr []byte, err error) {
buf := new(bytes.Buffer)
if req.URL == nil {
if err != nil {
return nil, errors.New("icap: httpRequestHeader called on Request with no URL")
}
}
host := req.URL.Host
if host == "" {
host = req.Host
}
req.Header.Set("Host", host)
uri := req.URL.String()
fmt.Fprintf(buf, "%s %s %s\r\n", valueOrDefault(req.Method, "GET"), uri, valueOrDefault(req.Proto, "HTTP/1.1"))
req.Header.WriteSubset(buf, map[string]bool{
"Transfer-Encoding": true,
"Content-Length": true,
})
io.WriteString(buf, "\r\n")
return buf.Bytes(), nil
}
// httpResponseHeader returns the headers for an HTTP response
// as a slice of bytes.
func httpResponseHeader(resp *http.Response) (hdr []byte, err error) {
buf := new(bytes.Buffer)
// Status line
text := resp.Status
if text == "" {
text = http.StatusText(resp.StatusCode)
if text == "" {
text = "status code " + strconv.Itoa(resp.StatusCode)
}
}
proto := resp.Proto
if proto == "" {
proto = "HTTP/1.1"
}
fmt.Fprintf(buf, "%s %d %s\r\n", proto, resp.StatusCode, text)
if _, xIcap206Exists := resp.Header["X-Icap-206"]; xIcap206Exists {
resp.Header.Write(buf)
} else {
resp.Header.WriteSubset(buf, map[string]bool{
"Transfer-Encoding": true,
"Content-Length": false,
})
}
io.WriteString(buf, "\r\n")
return buf.Bytes(), nil
}
// Return value if nonempty, def otherwise.
func valueOrDefault(value, def string) string {
if value != "" {
return value
}
return def
}
+244
View File
@@ -0,0 +1,244 @@
// Copyright 2011 Andy Balholm. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Network connections and request dispatch for the ICAP server.
package icap
import (
"bufio"
"bytes"
"crypto/tls"
"fmt"
"log"
"net"
"net/http"
"net/textproto"
"net/url"
"runtime/debug"
"time"
)
// Handler Objects implementing the Handler interface can be registered
// to serve ICAP requests.
//
// ServeICAP should write reply headers and data to the ResponseWriter
// and then return.
type Handler interface {
ServeICAP(ResponseWriter, *Request)
}
// The HandlerFunc type is an adapter to allow the use of
// ordinary functions as ICAP handlers. If f is a function
// with the appropriate signature, HandlerFunc(f) is a
// Handler object that calls f.
type HandlerFunc func(ResponseWriter, *Request)
// ServeICAP calls f(w, r).
func (f HandlerFunc) ServeICAP(w ResponseWriter, r *Request) {
f(w, r)
}
// A conn represents the server side of an ICAP connection.
type conn struct {
remoteAddr string // network address of remote side
handler Handler // request handler
rwc net.Conn // i/o connection
buf *bufio.ReadWriter // buffered rwc
}
// Create new connection from rwc.
func newConn(rwc net.Conn, handler Handler) (c *conn, err error) {
c = new(conn)
c.remoteAddr = rwc.RemoteAddr().String()
c.handler = handler
c.rwc = rwc
br := bufio.NewReader(rwc)
bw := bufio.NewWriter(rwc)
c.buf = bufio.NewReadWriter(br, bw)
return c, nil
}
// Read next request from connection.
func (c *conn) readRequest() (w *respWriter, err error) {
var req *Request
if req, err = ReadRequest(c.buf); err != nil {
//return req, err
}
if req == nil {
req = new(Request)
} else {
req.RemoteAddr = c.remoteAddr
}
w = new(respWriter)
w.conn = c
w.req = req
w.header = make(http.Header)
return w, err
}
// Close the connection.
func (c *conn) close() {
if c.buf != nil {
c.buf.Flush()
c.buf = nil
}
if c.rwc != nil {
c.rwc.Close()
c.rwc = nil
}
}
// Serve a new connection.
func (c *conn) serve(debugLevel int) {
defer func() {
err := recover()
if err == nil {
return
}
c.rwc.Close()
var buf bytes.Buffer
fmt.Fprintf(&buf, "icap: panic serving %v: %v\n", c.remoteAddr, err)
buf.Write(debug.Stack())
log.Print(buf.String())
}()
var w *respWriter
w, err := c.readRequest()
// In a case of parsing error there should be an option to handle a dummy request to not fail the whole service.
if err != nil {
if debugLevel > 0 {
log.Println("error while reading request:", err)
log.Println("error while reading request:", w)
log.Println("error while reading request:", w.conn)
log.Println("error while reading request:", w.req)
log.Println("error while reading request:", w.header)
}
// c.rwc.Close()
// return
if w == nil {
w = new(respWriter)
}
w.conn = c
w.req = new(Request)
w.req.Method = "ERRDUMMY"
w.req.RawURL = "/"
w.req.Proto = "ICAP/1.0"
w.req.URL, _ = url.ParseRequestURI("icap://localhost/")
w.req.Header = textproto.MIMEHeader{
"Connection": {"close"},
// "Error:": {err.Error()},
}
}
c.handler.ServeICAP(w, w.req)
w.finishRequest()
c.close()
}
// A Server defines parameters for running an ICAP server.
type Server struct {
Addr string // TCP address to listen on, ":1344" if empty
Handler Handler // handler to invoke
ReadTimeout time.Duration
WriteTimeout time.Duration
DebugLevel int
}
// ListenAndServe listens on the TCP network address srv.Addr and then
// calls Serve to handle requests on incoming connections. If
// srv.Addr is blank, ":1344" is used.
func (srv *Server) ListenAndServe() error {
addr := srv.Addr
if addr == "" {
addr = ":1344"
}
l, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return srv.Serve(l)
}
// ListenAndServeTLS ---
func (srv *Server) ListenAndServeTLS(cert, key string) error {
cer, err := tls.LoadX509KeyPair(cert, key)
if err != nil {
return err
}
addr := srv.Addr
if addr == "" {
addr = ":1344"
}
config := &tls.Config{Certificates: []tls.Certificate{cer}}
l, err := tls.Listen("tcp", addr, config)
if err != nil {
return err
}
return srv.Serve(l)
}
// Serve accepts incoming connections on the Listener l, creating a
// new service thread for each. The service threads read requests and
// then call srv.Handler to reply to them.
func (srv *Server) Serve(l net.Listener) error {
defer l.Close()
handler := srv.Handler
if handler == nil {
handler = DefaultServeMux
}
for {
rw, err := l.Accept()
if err != nil {
if ne, ok := err.(net.Error); ok && ne.Temporary() {
log.Printf("icap: Accept error: %v", err)
continue
}
return err
}
if srv.ReadTimeout != 0 {
rw.SetReadDeadline(time.Now().Add(srv.ReadTimeout))
}
if srv.WriteTimeout != 0 {
rw.SetWriteDeadline(time.Now().Add(srv.WriteTimeout))
}
c, err := newConn(rw, handler)
if err != nil {
continue
}
go c.serve(srv.DebugLevel)
}
// The next line is only there to see one specific edge case whichc should never happen.
panic("Shuold never be reached")
}
// Serve accepts incoming ICAP connections on the listener l,
// creating a new service thread for each. The service threads
// read requests and then call handler to reply to them.
func Serve(l net.Listener, handler Handler) error {
srv := &Server{Handler: handler}
return srv.Serve(l)
}
// ListenAndServe listens on the TCP network address addr
// and then calls Serve with handler to handle requests
// on incoming connections.
func ListenAndServe(addr string, handler Handler) error {
server := &Server{Addr: addr, Handler: handler}
return server.ListenAndServe()
}
// ListenAndServeTLS --
func ListenAndServeTLS(addr, cert, key string, handler Handler) error {
server := &Server{Addr: addr, Handler: handler}
return server.ListenAndServeTLS(cert, key)
}
+34
View File
@@ -0,0 +1,34 @@
// Copyright 2011 Andy Balholm. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// ICAP status codes.
package icap
import (
"net/http"
)
var statusText = map[int]string{
100: "Continue",
204: "No Modifications",
400: "Bad Request",
404: "ICAP Service Not Found",
405: "Method Not Allowed",
408: "Request Timeout",
500: "Server Error",
501: "Method Not Implemented",
502: "Bad Gateway",
503: "Service Overloaded",
505: "ICAP Version Not Supported",
}
// StatusText returns a text for the ICAP status code. It returns the empty string if the code is unknown.
func StatusText(code int) string {
text, ok := statusText[code]
if ok {
return text
}
return http.StatusText(code)
}