Class and Method

Takuma Kume edited this page Jan 25, 2017 · 57 revisions

Class for mod_mruby

Default

Extra(commented out in build_config.rb)

Kernel Class

get_server_class

Server = get_server_class

Server.echo "hello world"

server_name

get server software name.

if server_name == "NGINX"
  Server = Nginx
elsif server_name == "Apache" 
  Server = Apache
end
Server.echo "hello world"

Apache Class

Method

Apache.rputs

/path/to/hello.rb

r = Apache::Request.new

r.content_type = "text/plain"
Apache.rputs "hello world!¥n"

httpd.conf

<Location /hello>
    mrubyHandlerMiddle /path/to/hello.rb
</Location>

run curl

$ curl http://127.0.0.1/hello
hello world!

Apache.echo

create response text which is terminated with a newline

Apache.echo "hello world!"

is equal to

Apache.rputs "hello world!¥n"

Apache.return

return Apache status code

return Apache::HTTP_SERVICE_UNAVAILABLE

Apache.errlogger

logging to error_log with log priority

Apache.errlogger Apache::APLOG_ERR, "mod_mruby error!"

error.log example

[Wed Mar 05 20:14:50.760152 2014] [:error] [pid 63231:tid 139940989998848] mod_mruby error!

Apache.log

aliase Apache.errlogger

Apache.syslogger

logging to syslog with log priority

Apache.syslogger Apache::LOG_ERR, "error occured!"

Apache.syslog

aliase Apache.syslogger

Apache.module_name

Apache.echo Apache.module_name # => mod_mruby

Apache.module_version

Apache.echo Apache.module_version # => 0.9.5

Apache.server_version

Apache.echo Apache.server_version # => Apache/2.4.6 (Unix)

Apache.server_build

Apache.echo Apache.server_build # => Nov  7 2013 10:56:11

Apache.remove_global_variable

$a = 1
Apache.echo global_variables #=> [:$stdout, :$$, :$/, :$stdin, :$?, :$a, :$stderr, :$1, :$2, :$3, :$4, :$5, :$6, :$7, :$8, :$9]
Apache.remove_global_variable :$a
Apache.echo global_variables #=> [:$stdout, :$$, :$/, :$stdin, :$?, :$stderr, :$1, :$2, :$3, :$4, :$5, :$6, :$7, :$8, :$9]

Const

Const for log

Const Value
Apache::APLOG_EMERG 0
Apache::APLOG_ALERT 1
Apache::APLOG_CRIT 2
Apache::APLOG_ERR 3
Apache::APLOG_WARNING 4
Apache::APLOG_NOTICE 5
Apache::APLOG_INFO 6
Apache::APLOG_DEBUG 7

Const for syslog

Const Value
Apache::LOG_EMERG depend on OS
Apache::LOG_ALERT depend on OS
Apache::LOG_CRIT depend on OS
Apache::LOG_ERR depend on OS
Apache::LOG_WARNING depend on OS
Apache::LOG_NOTICE depend on OS
Apache::LOG_INFO depend on OS
Apache::LOG_DEBUG depend on OS

Const for Apache status

Const Value
Apache::OK 0
Apache::DECLINED -1
Apache::HTTP_CONTINUE 100
Apache::HTTP_SWITCHING_PROTOCOLS 101
Apache::HTTP_PROCESSING 102
Apache::HTTP_OK 200
Apache::HTTP_CREATED 201
Apache::HTTP_ACCEPTED 202
Apache::HTTP_NON_AUTHORITATIVE 203
Apache::HTTP_NO_CONTENT 204
Apache::HTTP_RESET_CONTENT 205
Apache::HTTP_PARTIAL_CONTENT 206
Apache::HTTP_MULTI_STATUS 207
Apache::HTTP_MULTIPLE_CHOICES 300
Apache::HTTP_MOVED_PERMANENTLY 301
Apache::HTTP_MOVED_TEMPORARILY 302
Apache::HTTP_SEE_OTHER 303
Apache::HTTP_NOT_MODIFIED 304
Apache::HTTP_USE_PROXY 305
Apache::HTTP_TEMPORARY_REDIRECT 307
Apache::HTTP_BAD_REQUEST 400
Apache::HTTP_UNAUTHORIZED 401
Apache::HTTP_PAYMENT_REQUIRED 402
Apache::HTTP_FORBIDDEN 403
Apache::HTTP_NOT_FOUND 404
Apache::HTTP_METHOD_NOT_ALLOWED 405
Apache::HTTP_NOT_ACCEPTABLE 406
Apache::HTTP_PROXY_AUTHENTICATION_REQUIRED 407
Apache::HTTP_REQUEST_TIME_OUT 408
Apache::HTTP_CONFLICT 409
Apache::HTTP_GONE 410
Apache::HTTP_LENGTH_REQUIRED 411
Apache::HTTP_PRECONDITION_FAILED 412
Apache::HTTP_REQUEST_ENTITY_TOO_LARGE 413
Apache::HTTP_REQUEST_URI_TOO_LARGE 414
Apache::HTTP_UNSUPPORTED_MEDIA_TYPE 415
Apache::HTTP_RANGE_NOT_SATISFIABLE 416
Apache::HTTP_EXPECTATION_FAILED 417
Apache::HTTP_UNPROCESSABLE_ENTITY 422
Apache::HTTP_LOCKED 423
Apache::HTTP_NOT_EXTENDED 510
Apache::HTTP_INTERNAL_SERVER_ERROR 500
Apache::HTTP_NOT_IMPLEMENTED 501
Apache::HTTP_BAD_GATEWAY 502
Apache::HTTP_SERVICE_UNAVAILABLE 503
Apache::HTTP_VARIANT_ALSO_VARIES 506

Const for proxy type

Const Value
Apache::PROXYREQ_NONE 0
Apache::PROXYREQ_PROXY 1
Apache::PROXYREQ_REVERSE 2
Apache::PROXYREQ_RESPONSE 3

Apache::Request Class

Method

Apache::Request#run_handler

create response. For example, fork and run script.

pid = Process.fork {
  r = Apache::Request.new
  r.run_handler
  Apache.errlogger Apache::APLOG_NOTICE, "exec for #{r.filename}."
}

Process.waitpid pid

Apache::Request#body

request body data with POST method. refs

# Log headers and a body of POST requests.
# You have to install mod_mruby first.
#
# Add a following line to httpd.conf:
#   mrubyInsertFilterFirst /var/www/request_dumper.rb
 
LOG_FILE = "/tmp/request.txt"
MAX_LEN = 1024
IN_ONE_LINE = false

def format_time(time)
  sprintf("%04d-%02d-%02d %02d:%02d:%02d",
          time.year, time.month, time.day,
          time.hour, time.min, time.sec
         )
end
 
r = Apache::Request.new
 
if r.method_number == Apache::M_POST
  File.open(LOG_FILE, "a") do |fh|
    body = r.body.to_s[0...MAX_LEN]
    if r.headers_in["Content-Type"].to_s[0,9] == "multipart"
      body = body.inspect
    end
    headers_str = r.headers_in.all.map{|k, v| "#{k}: #{v}"}.join("\n")
    record = ["[#{format_time(Time.now)}]",
      "#{r.the_request}\n#{headers_str}", "#{body}"]
    if IN_ONE_LINE
      record[1] = record[1].inspect
      fh.write(record.join(' ') + "\n")
    else
      fh.write('='*80 + "\n" + record.join("\n\n") + "\n")
    end
  end
end

logging example

================================================================================
[2014-04-04 15:18:33]
 
POST /post HTTP/1.1
Host: 192.168.3.32
Accept-Language: ja,en-us;q=0.7,en;q=0.3
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:28.0) Gecko/20100101 Firefox/28.0
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 68
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Referer: http://192.168.3.32/post
Accept-Encoding: gzip, deflate
 
text=%E3%83%86%E3%82%B9%E3%83%88%E3%81%A7%E3%81%99%E3%82%88%EF%BC%81
================================================================================

Apache::Request#error_log

r = Apache::Request.new

r.error_log Apache::APLOG_NOTICE, "r.error_log"

error_log

[Wed Mar 05 22:26:27.083434 2014] [:notice] [pid 63254:tid 139940889286400] [client 127.0.0.1:46519] r.error_log

Apache::Request#error_log_into

r = Apache::Request.new

r.error_log Apache::APLOG_NOTICE, "r.error_log"
r.error_log_into "/tmp/error_log2"

/tmp/error_log2

[Wed Mar 05 22:32:39.733478 2014] [:notice] [pid 63254:tid 139940872500992] [client 127.0.0.1:46521] r.error_log

Apache::Request#log

alias Apache::Request#error_log

Apache::Request#the_request

r = Server::Request.new
Apache.echo r.the_request # => GET /hello HTTP/1.1

Apache::Request#the_request=

r = Server::Request.new

Apache.echo r.the_request # => GET /hello HTTP/1.1
r.the_request = r.the_request.gsub /GET/, 'POST'
Apache.echo r.the_request # => POST /hello HTTP/1.1

Apache::Request#protocol

r = Server::Request.new
Apache.echo r.protocol # => HTTP/1.1

Apache::Request#protocol=

r = Server::Request.new

Apache.echo r.protocol # => HTTP/1.1
r.protocol = r.protocol.gsub /1.1/, '1.0'
Apache.echo r.protocol # => HTTP/1.0

Apache::Request#vlist_validator

variant list validator (if negotiated)

Apache::Request#vlist_validator=

update variant list validator (if negotiated)

Apache::Request#user

If an authentication check was made, this gets set to the user name.

Apache::Request#user=

If an authentication check was made, this gets set to the user name.

Apache::Request#ap_auth_type

If an authentication check was made, this gets set to the auth type.

Apache::Request#ap_auth_type=

If an authentication check was made, this gets set to the auth type.

Apache::Request#unparsed_uri

r = Apache::Request.new

# curl -v http://127.0.0.1/hello?a=1
Apache.echo r.unparsed_uri # => /hello?a=1

Apache::Request#unparsed_uri=

set string to r->unparsed_uri in request_rec

Apache::Request#uri

r = Apache::Request.new

# curl -v http://127.0.0.1/hello?a=1
Apache.echo r.uri # => /hello

Apache::Request#uri=

set string to r->uri in request_rec

Apache::Request#filename

r = Apache::Request.new

# curl -v http://127.0.0.1/
r.filename # => /path/to/index.html

Apache::Request#filename=

r = Apache::Request.new

if /^.*¥.php$/ =~ r.filename
  r.filename = "/path/to/redirect.php"
end

Apache::Request#canonical_filename

The true filename, we canonicalize r.filename if these don't match.

r = Apache::Request.new

# curl -v http://127.0.0.1/
r.canonical_filename # => /path/to/index.html

Apache::Request#canonical_filename=

set string into r->canonical_filenam in request_rec

Apache::Request#path_info

The PATH_INFO extracted from this request.

Apache::Request#path_info=

set string into r->path_info in request_rec

Apache::Request#args

The QUERY_ARGS extracted from this request.

r = Apache::Request.new

# curl -v http://127.0.0.1/hello?a=1
Apache.echo r.args # => a=1

Apache::Request#args=

set string into r->args in request_rec

Apache::Request#hostname

Host, as set by full URI or Host:

r = Apache::Request.new

# curl -v http://127.0.0.1/hello?a=1
Apache.echo r.hostname # => 127.0.0.1

Apache::Request#hostname=

set string into r->hostname in request_rec

Apache::Request#document_root

r = Apache::Request.new
Apache.echo r.document_root # => /path/to/htdocs

Apache::Request#document_root=

Server = Apache
r = Server::Request.new

Server.echo "documento_root: #{r.document_root}" # => /path/to/htdocs
r.document_root = "/tmp"
Server.echo "documento_root: #{r.document_root}" # => /tmp

Apache::Request#status_line

Status line, if set by script.

Apache::Request#status_line=

set string into r->status_line in request_rec

Apache::Request#method

r = Apache::Request.new

# curl -v http://127.0.0.1/hello?a=1
Apache.echo r.method # => GET

Apache::Request#method=

set string into r->method in request_rec

Apache::Request#range

The Range: header.

Apache::Request#range=

set string into r->range in request_rec

Apache::Request#content_type

The content-type for the current request.

Apache::Request#content_type=

content_type MUST be lowercased strings. They may be pointers to static strings; they should not be modified in place.

r.content_type = "text/plain"

Apache::Request#content_length

Get the content length for this request. The "real" content length.

Apache::Request#content_length=

Set the content length for this request.

Apache::Request#response_time

# curl http://127.0.0.1/sleep_1sec.php
Apache::Request.new.response_time #=> 1.0014239549637

Apache::Request#assbackwards

Apache::Request#proxyreq

A proxy request (calculated during mrubyPostReadRequest / mrubyTranslateName) possible values Apache::PROXYREQ_NONE, Apache::PROXYREQ_PROXY, Apache::PROXYREQ_REVERSE, Apache::PROXYREQ_RESPONSE

Apache::Request#proxyreq=

# <Location /proxy>
#     mrubyTranslateNameMiddle /path/to/proxy.rb
# </Location>
backends = [
    "http://192.168.0.101:8888/",
    "http://192.168.0.102:8888/",
    "http://192.168.0.103:8888/",
    "http://192.168.0.104:8888/",
]

r = Apache::Request.new

r.handler  = "proxy-server"
r.proxyreq = Apache::PROXYREQ_REVERSE
r.filename = "proxy:" + backends[rand(backends.length)] + r.uri

[Constants for proxyreq] (https://github.com/matsumoto-r/mod_mruby/wiki/Class-and-Method#const-for-proxy-type)

Apache::Request#reverse_proxy

This method wrap proxy handler or proxyreq method for reverse proxy.

r = Apache::Request.new()
r.reverse_proxy "http://0.0.0.0:#{port}" + r.unparsed_uri

Apache::Request#header_only

HEAD request, as opposed to GET.

r = Apache::Request.new
r.headers_out["X-HEAD-CHECK"] = r.header_only.to_s
$ curl -v http://127.0.0.1/hello?a=1
< HTTP/1.1 200 OK
< Date: Fri, 07 Mar 2014 11:33:46 GMT
< Server: Apache/2.4.6 (Unix)
< X-HEAD-CHECK: 0
$ curl -I -v http://127.0.0.1/hello?a=1
< HTTP/1.1 200 OK
< Date: Fri, 07 Mar 2014 11:35:09 GMT
< Server: Apache/2.4.6 (Unix)
< X-HEAD-CHECK: 1

Apache::Request#proto_num

Protocol version number of protocol; 1.1 = 1001.

Apache::Request#status

r = Apache::Request.new
Apache.echo r.status # => 200

Apache::Request#status=

Set fixnum into r->status in request_rec

Apache::Request#method_number

Get method number like M_GET, M_POST and so on.

r = Apache::Request.new

if r.method_number == Apache::M_POST
  # processing...
end
Const for Apache method_number
Const Value Description
Apache::M_GET 0 RFC 2616: HTTP
Apache::M_PUT 1
Apache::M_POST 2
Apache::M_DELETE 3
Apache::M_CONNECT 4
Apache::M_OPTIONS 5
Apache::M_TRACE 6 RFC 2616: HTTP
Apache::M_PATCH 7
Apache::M_PROPFIND 8 RFC 2518: WebDAV
Apache::M_PROPPATCH 9
Apache::M_MKCOL 10
Apache::M_COPY 11
Apache::M_MOVE 12
Apache::M_LOCK 13
Apache::M_UNLOCK 14 RFC 2518: WebDAV
Apache::M_VERSION_CONTROL 15 RFC 3253: WebDAV Versioning
Apache::M_CHECKOUT 16
Apache::M_UNCHECKOUT 17
Apache::M_CHECKIN 18
Apache::M_UPDATE 19
Apache::M_LABEL 20
Apache::M_REPORT 21
Apache::M_MKWORKSPACE 22
Apache::M_MKACTIVITY 23
Apache::M_BASELINE_CONTROL 24
Apache::M_MERGE 25
Apache::M_INVALID 26 no valid method

Apache::Request#chunked

sending chunked transfer-coding.

r = Apache::Request.new
Apache.echo r.chunked # => 0

Apache::Request#read_body

Method for reading the request body (eg. REQUEST_CHUNKED_ERROR, REQUEST_NO_BODY, REQUEST_CHUNKED_DECHUNK, etc...)

Apache::Request#read_chunked

reading chunked transfer-coding.

r = Apache::Request.new
Apache.echo r.read_chunked # => 0

Apache::Request#used_path_info

Flag for the handler to accept or reject path_info on the current request. All modules should respect the AP_REQ_ACCEPT_PATH_INFO and AP_REQ_REJECT_PATH_INFO values, while AP_REQ_DEFAULT_PATH_INFO indicates they may follow existing conventions. This is set to the user's preference upon HOOK_VERY_FIRST of the fixups.

Apache::Request#eos_sent

A flag to determine if the eos bucket has been sent yet.

r = Apache::Request.new
Apache.echo r.eos_sent # => 0

Apache::Request#no_cache

This response can not be cached.

r = Apache::Request.new
Apache.echo r.no_cache # => 0

Apache::Request#no_local_copy

There is no local copy of this response.

r = Apache::Request.new
Apache.echo r.no_local_copy # => 0

Apache::Request#notes

This method return Apache::Note Class instance. See Apache::Notes Class.

r = Apache::Request.new

r.notes["test"] = "ok" 
Apache.echo r.notes["test"] # => ok

Apache::Request#headers_in

This method return Apache::Headers_in Class instance. See Apache::Headers_in Class.

r = Apache::Request.new

# curl -v http://127.0.0.1/hello?a=1
r.headers_in.all.keys.each do |k|  
  Apache.echo "#{k}: #{r.headers_in[k]}"
end

# => Host: 127.0.0.1
# => User-Agent: curl/7.29.0
# => Accept: */*

Apache::Request#headers_out

This method return Apache::Headers_out Class instance. See Apache::Headers_out Class.

r = Apache::Request.new

# curl -v http://127.0.0.1/hello?a=1
r.headers_out["X-HEAD-CHECK"] = r.header_only.to_s
r.headers_out["X-SEND-CHENKED-CHECK"] = r.chunked.to_s
r.headers_out["X-READ-CHENKED-CHECK"] = r.read_chunked.to_s

r.headers_out.all.keys.each do |k|
  Apache.echo "#{k}: #{r.headers_out[k]}"
end

# => X-SEND-CHENKED-CHECK: 0
# => X-HEAD-CHECK: 0
# => X-READ-CHENKED-CHECK: 0

Apache::Request#finfo

This method return Apache::Finfo Class instance. See Apache::Finfo Class.

r = Apache::Request.new
Apache.echo r.finfo.inode

Apache::Request#{main?,prev?,next?}

r = Apache::Request.new

if r.main? # or r.sub_request?
  Apache.echo "this is subrequest"
elsif r.prev? # or r.internal_redirect?
  Apache.echo "this is an internal redirect"
elsif r.next? # or r.external_redirect?
  Apache.echo "this is an external redirect"
end

Apache::Notes Class

Apache::Notes#[]

Notes on this connection: send note from one module to another. must remain valid for all requests on this conn.

Apache::Notes#[]=

note = Apache::Notes.new
note["This_is"] = "OK"

And, other Ruby script

note = Apache::Notes.new

if note["This_is"] == "OK"
  # any implementaton...
end

Apache::Headers_in Class

Apache::Headers_in#[]

hin = Apache::Headers_in.new

# curl -v http://127.0.0.1/hello?a=1
hin.all.keys.each do |k|  
  Apache.echo "#{k}: #{hin[k]}"
end

# => Host: 127.0.0.1
# => User-Agent: curl/7.29.0
# => Accept: */*

Apache::Headers_in#[]=

hin = Apache::Headers_in.new

hin["X-INTERNAL-PROXY"] = "ON"

Apache::Headers_in#all

hin = Apache::Headers_in.new

# curl -v http://127.0.0.1/hello?a=1
hin.all.keys.each do |k|  
  Apache.echo "#{k}: #{hin[k]}"
end

# => Host: 127.0.0.1
# => User-Agent: curl/7.29.0
# => Accept: */*

Apache::Headers_out Class

Apache::Headers_out#[]

hout = Apache::Headers_out.new

# curl -v http://127.0.0.1/hello?a=1
hout["X-HEAD-CHECK"] = r.header_only.to_s
hout["X-SEND-CHENKED-CHECK"] = r.chunked.to_s
hout["X-READ-CHENKED-CHECK"] = r.read_chunked.to_s

hout.all.keys.each do |k|
  Apache.echo "#{k}: #{hout[k]}"
end

# => X-SEND-CHENKED-CHECK: 0
# => X-HEAD-CHECK: 0
# => X-READ-CHENKED-CHECK: 0

Apache::Headers_out#[]=

hout = Apache::Headers_out.new

# curl -v http://127.0.0.1/hello?a=1
hout["X-HEAD-CHECK"] = r.header_only.to_s
hout["X-SEND-CHENKED-CHECK"] = r.chunked.to_s
hout["X-READ-CHENKED-CHECK"] = r.read_chunked.to_s

hout.all.keys.each do |k|
  Apache.echo "#{k}: #{hout[k]}"
end

# => X-SEND-CHENKED-CHECK: 0
# => X-HEAD-CHECK: 0
# => X-READ-CHENKED-CHECK: 0

Apache::Headers_out#all

hout = Apache::Headers_out.new

# curl -v http://127.0.0.1/hello?a=1
hout["X-HEAD-CHECK"] = r.header_only.to_s
hout["X-SEND-CHENKED-CHECK"] = r.chunked.to_s
hout["X-READ-CHENKED-CHECK"] = r.read_chunked.to_s

hout.all.keys.each do |k|
  Apache.echo "#{k}: #{hout[k]}"
end

# => X-SEND-CHENKED-CHECK: 0
# => X-HEAD-CHECK: 0
# => X-READ-CHENKED-CHECK: 0

Apache::Finfo Class

Method

Hook script

# 
# mrubyFixupsMiddle /path/to/finfo.rb
#

r = Apache::Request.new
finfo = Apache::Finfo.new

Apache.echo "---- finfo ----"
Apache.echo "Request filename: #{r.filename}"
Apache.echo "permission: #{finfo.permission}"
Apache.echo "filetype: #{finfo.filetype}"
Apache.echo "group: #{finfo.group}"
Apache.echo "user: #{finfo.user}"
Apache.echo "device: #{finfo.device}"
Apache.echo "inode: #{finfo.inode}"
Apache.echo "nlink: #{finfo.nlink}"
Apache.echo "size: #{finfo.size}"
Apache.echo "csize: #{finfo.csize}"
Apache.echo "atime: #{Time.at(finfo.atime/1000000)}"
Apache.echo "ctime: #{Time.at(finfo.ctime/1000000)}"
Apache.echo "mtime: #{Time.at(finfo.mtime/1000000)}"
Apache.echo "---- Request File Respnse ----"

/path/to/index.html

<html><body><h1>It works!</h1></body></html>

stat information

$ stat /path/to/index.html
  File: `/path/to/index.html'
  Size: 45              Blocks: 8          IO Block: 4096   通常ファイル
Device: fd01h/64769d    Inode: 817292      Links: 1
Access: (0644/-rw-r--r--)  Uid: (  500/ UNKNOWN)   Gid: (  500/ UNKNOWN)
Access: 2014-03-07 21:18:04.165875204 +0900
Modify: 2007-06-12 03:53:14.000000000 +0900
Change: 2014-03-07 21:18:02.527905828 +0900
 Birth: -

Response

$ curl http://127.0.0.1/index.html
---- finfo ----
Request filename: /path/to/index.html
permission: 1604
filetype: 1
group: 500
user: 500
device: 64769
inode: 817292
nlink: 1
size: 45.0
csize: 4096.0
atime: Fri Mar 07 21:18:04 2014
ctime: Fri Mar 07 21:18:02 2014
mtime: Tue Jun 12 03:53:14 2007
---- Request File Respnse ----
<html><body><h1>It works!</h1></body></html>

Apache::Finfo#permission

The access permissions of the file. Mimics Unix access rights.

Apache::Finfo#filetype

The type of file. One of Apache::APR_REG, Apache::APR_DIR, Apache::APR_CHR, Apache::APR_BLK, Apache::APR_PIPE, Apache::APR_LNK or Apache::APR_SOCK. If the type is undetermined, the value is Apache::APR_NOFILE. If the type cannot be determined, the value is Apache::APR_UNKFILE. See Finfo constants.

Apache::Finfo#group

The user id that owns the file.

Apache::Finfo#user

The group id that owns the file.

Apache::Finfo#device

The id of the device the file is on.

Apache::Finfo#inode

The inode of the file.

Apache::Finfo#nlink

The number of hard links to the file.

Apache::Finfo#size

The size of the file.

Apache::Finfo#csize

The storage size consumed by the file.

Apache::Finfo#atime

The time the file was last accessed. micro seconds.

Apache::Finfo#ctime

The time the file was created, or the inode was last changed. micro seconds.

Apache::Finfo#mtime

The time the file was last modified. micro seconds.

Const

Const Value Description
Apache::Finfo::APR_NOFILE 0 no file type determined
Apache::Finfo::APR_REG 1 a regular file
Apache::Finfo::APR_DIR 2 a directory
Apache::Finfo::APR_CHR 3 a character device
Apache::Finfo::APR_BLK 4 a block device
Apache::Finfo::APR_PIPE 5 a FIFO / pipe
Apache::Finfo::APR_LNK 6 a symbolic link
Apache::Finfo::APR_SOCK 7 a [unix domain] socket
Apache::Finfo::APR_UNKFILE 127 a file of some other unknown type

Apache::Server Class

Apache::Server#error_fname

The name of the error log.

s = Apache::Server.new

Apache.echo s.error_fname # => logs/error_log

Apache::Server#error_fname=

Set sting into s->error_fname.

Apache::Server#document_root

Get document_root.

s = Apache::Server.new

Apache.echo s.document_root # => /path/to/htdocs

Apache::Server#loglevel

The log level configuration.

s = Apache::Server.new

Apache.echo s.loglevel # => 7

Apache::Server#loglevel=

Set into the log level configuration.

Apache::Server#hostname

The server hostname.

s = Apache::Server.new

Apache.echo s.hostname # => localhost.localdomain

Apache::Server#path

Pathname for ServerPath.

Apache::Server#pathlen

Length of path.

Apache::Server#admin

The admin's contact information.

Apache::Server#defn_name

The name of the server.

Apache::Server#is_virtual

true if this is the virtual server.

Apache::Server#keep_alive_max

Maximum requests per connection.

s = Apache::Server.new

Apache.echo s.keep_alive_max # => 100

Apache::Server#keep_alive

Use persistent connections.

Apache::Server#limit_req_line

limit on size of the HTTP request line.

s = Apache::Server.new

Apache.echo s.limit_req_line # => 8190

Apache::Server#limit_req_fieldsize

limit on size of any request header field.

s = Apache::Server.new

Apache.echo s.limit_req_fieldsize # => 8190

Apache::Server#limit_req_fields

limit on number of request header fields.

s = Apache::Server.new

Apache.echo s.limit_req_fields # => 100

Apache::Server#timeout

Timeout, as an apr interval, before we give up.

s = Apache::Server.new

Apache.echo s.timeout # => 60000000

Apache::Server#keep_alive_timeout

The apr interval we will wait for another request.

s = Apache::Server.new

Apache.echo s.keep_alive_timeout # => 5000000

Apache::Server#redirect_server_port

for redirects, etc.

Apache::Server#redirect_server_scheme

The server request scheme for redirect responses.

Apache::Server#defn_line_number

The line of the config file that the server was defined on.

Apache::Connection Class

Apache::Connection#remote_ip

Client's IP address; this is the end-point of the next hop, for the IP of the request creator.

c = Apache::Connection.new

# curl http://127.0.0.1/hello?a=1
Apache.echo c.remote_ip # => 127.0.0.1

Apache::Connection#remote_port

Client's Port number.

c = Apache::Connection.new

# curl http://127.0.0.1/hello?a=1
Apache.echo c.remote_port # => 46626

Apache::Connection#remote_host

Client's DNS name, if known. NULL if DNS hasn't been checked, if it has and no address was found.

Apache::Connection#remote_logname

Only ever set if doing rfc1413 lookups.

Apache::Connection#local_ip

Server's IP address.

c = Apache::Connection.new

# curl http://127.0.0.1/hello?a=1
Apache.echo c.local_ip # => 127.0.0.1

Apache::Connection#local_port

Server's Port number.

c = Apache::Connection.new

# curl http://127.0.0.1/hello?a=1
Apache.echo c.local_port # => 80

Apache::Connection#local_host

Used for ap_get_server_name when UseCanonicalName is set to DNS (ignores setting of HostnameLookups).

Apache::Connection#keepalives

How many times have we used it?

c = Apache::Connection.new

# curl http://127.0.0.1/hello?a=1
Apache.echo c.keepalives # => 0

Apache::Connection#data_in_input_filters

Is there data pending in the input filters?

c = Apache::Connection.new

# curl http://127.0.0.1/hello?a=1
Apache.echo c.data_in_input_filters # => 0

Apache::Env Class

Apache::ENV#[]

Get env in Apache httpd.

Apache::ENV#[]=

Set env in Apache httpd.

Apache::ENV#all

Get all env as hash value.

e = Apache::Env.new

# curl http://localhost/hello?a=1
Apache.echo "--- env ----"
e.all.keys.each do |key|
  Apache.echo "#{key}: #{e[key]}"
end

Response

SERVER_ADDR: ::1
GATEWAY_INTERFACE: CGI/1.1
CONTEXT_DOCUMENT_ROOT: /path/to/htdocs
CONTEXT_PREFIX:
HTTP_ACCEPT: */*
SERVER_SIGNATURE:
SCRIPT_FILENAME: /path/to/htdocs/hello
PATH: /usr/lib64/ccache:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin
REMOTE_ADDR: ::1
HTTP_HOST: localhost
REQUEST_SCHEME: http
SCRIPT_NAME: /hello
QUERY_STRING: a=1
SERVER_PROTOCOL: HTTP/1.0
REQUEST_URI: /hello?a=1
REMOTE_PORT: 48006
SERVER_SOFTWARE: Apache/2.4.6 (Unix)
SERVER_NAME: localhost
SERVER_ADMIN: you@example.com
LD_LIBRARY_PATH: /path/to/lib
SERVER_PORT: 80
REQUEST_METHOD: GET
DOCUMENT_ROOT: /path/to/htdocs
HTTP_USER_AGENT: curl/7.29.0

Apache::Filter Class

example 1

httpd.con

SetOutputFilter mruby
mrubyOutputFilter /tmp/filter.rb

filter script

f = Apache::Filter.new

# get resonse data
data = f.flatten

# cleanup original response data
f.cleanup

# insert response data in tail into output
f.insert_tail "new response data #{data * 3}"

# set eos
f.insert_eos

index.html

hello response data

curl

$ curl http://127.0.0.1/index.html
new response data hello response data
hello response data
hello response data
example 2
#
# httpd.conf
#
# SetOutputFilter mruby
# mrubyOutputFilter /usr/local/apache/htdocs/filter.rb
#
f = Apache::Filter.new

# read all body data
data = f.flatten

# cleanup old brigade
f.cleanup

# create new data
# create string
f.puts "foofoo-puts"

# modify body data
f.insert_tail data.upcase

# insert string to tail
f.insert_tail "hogehoge-tail"

# insert string to head
f.insert_head "fugafuga-head"

# insert End of String
f.insert_eos

# $ curl http://127.0.0.1/index.html
# fugafuga-headfoofoo-puts<HTML><BODY><H1>IT WORKS!</H1></BODY></HTML>
# hogehoge-tail

Apache::Filter#puts

Puts text into output filter.

Apache::Filter#insert_tail

Insert text in tail into output filter.

Apache::Filter#insert_head

Insert text in head into output filter.

Apache::Filter#insert_eos

Insert end of string in tail into output filter.

Apache::Filter#destroy

Destrop current brigade.

Apache::Filter#cleanup

Cleanup current brigade.

Apache::Filter#flatten

Get current brigade.

Apache::Filter#length

Get brigade length.

Apache::Filter#empty?

Check where brigade is empty or not.

Apache::Filter#first_bucket

Apache::FIlter#uid

Get uid of opened content file from fd.

Apache::FIlter#gid

Get gid of opened content file from fd.

Apache::Filter#error_create

Create error response from status code

uid = 1000

f = Apache::Filter.new

# get uid of opened file
if f.uid != uid
  f.error_create Apache::HTTP_SERVICE_UNAVAILABLE
end

Apache::Scoreboard Class

Get score board data in Apache httpd

Apache::Scoreboard#status

Apache::Scoreboard#counter

Apache::Scoreboard#pid

Apache::Scoreboard#cpu_load

Apache::Scoreboard#loadavg

Apache::Scoreboard#server_limit

Apache::Scoreboard#thread_limit

Apache::Scoreboard#access_counter

Apache::Scoreboard#total_kbyte

Apache::Scoreboard#total_access

Apache::Scoreboard#uptime

Apache::Scoreboard#restart_time

Apache::Scoreboard#idle_worker

Apache::Scoreboard#busy_worker

Example

def scoreboard                                                                   
  Apache.echo "## Scoreboard Class Test"                                         
  wc = Apache::Scoreboard.new()                                                  
  Apache.echo "- child pid = #{wc.pid.to_s}"                                     
  Apache.echo "- thread limit    = #{wc.thread_limit.to_s}"                      
  Apache.echo "- server limit    = #{wc.server_limit.to_s}"                      
  Apache.echo "__Cannot get below values of scoreboard because of ExtendedStatus Off__" if wc.restart_time == 0
  Apache.echo "- cpu load        = #{wc.cpu_load.to_s}"                          
  Apache.echo "- load avereage   = #{wc.loadavg.to_s}"                           
  Apache.echo "- total kbyte     = #{wc.total_kbyte.to_s}"                       
  Apache.echo "- total access    = #{wc.total_access.to_s}"                      
  Apache.echo "- restart time    = #{wc.restart_time.to_s}"                      
  Apache.echo "- idle worker     = #{wc.idle_worker.to_s}"                       
  Apache.echo "- busy worker     = #{wc.busy_worker.to_s}"                       
  Apache.echo "- uptime          = #{wc.uptime.to_s}"                            
  Apache.echo "- access counter  = #{wc.access_counter(wc.pid).to_s}"            
  Apache.echo "- scoreboard status hash size = #{wc.status.size.to_s}"           
  wc.status.each_key do |key|                                                    
      Apache.echo "- scoreboard key = #{key} val = #{wc.status[key]}"            
  end                                                                            
  Apache.echo "- scoreboard counter hash size = #{wc.counter.size.to_s}"         
  wc.counter.each_key do |key|                                                   
      Apache.echo "- scoreboard key = #{key} val = #{wc.counter[key].to_s}"      
  end                                                                            
end                                                                              

result

## Scoreboard Class Test
- child pid = 13311
- thread limit    = 64
- server limit    = 16
- cpu load        = 1.40271445606399e+14
- load avereage   = [0.0, 0.00999999977648, 0.05000000074505]
- total kbyte     = 10.0
- total access    = 3.0
- restart time    = 1.40013226824621e+15
- idle worker     = 74
- busy worker     = 1
- uptime          = 1.0
- access counter  = 0
- scoreboard status hash size = 1
- scoreboard key = ::1 val = SERVER_GRACEFUL
- scoreboard counter hash size = 11
- scoreboard key = SERVER_READY val = 74
- scoreboard key = SERVER_STARTING val = 0
- scoreboard key = SERVER_BUSY_READ val = 0
- scoreboard key = SERVER_BUSY_WRITE val = 1
- scoreboard key = SERVER_BUSY_KEEPALIVE val = 0
- scoreboard key = SERVER_BUSY_LOG val = 0
- scoreboard key = SERVER_BUSY_DNS val = 0
- scoreboard key = SERVER_CLOSING val = 0
- scoreboard key = SERVER_DEAD val = 949
- scoreboard key = SERVER_GRACEFUL val = 0
- scoreboard key = SERVER_IDLE_KILL val = 0

Apache::AuthnProvider Class

Basic Authentication Sample

# Basic Authentication Sample
#
# Apache configuration
#
# <Location /basic/>
#   AuthType basic
#   AuthName "Message for clients"
#   AuthBasicProvider mruby
#   mrubyAuthnCheckPassword /path/to/authn_basic.rb
#   require valid-user
# </Location>
#

user_list = {
  "bilbo" => "foo",
  "frodo" => "bar",
  "samwise" => "baz",
  "aragorn" => "qux",
  "legolas" => "quux",
  "gimli" => "corge",
}

anp = Apache::AuthnProvider.new

if user_list[anp.user] == anp.password
  Apache.return Apache::AuthnProvider::AUTH_GRANTED
else
  Apache.return Apache::AuthnProvider::AUTH_DENIED
end

Digest Authentication Sample

# Digest Authentication Sample
#
# Apache configuration
#
# <Location /digest/>
#   AuthType digest
#   AuthName "hobbits"
#   AuthBasicProvider mruby
#   mrubyAuthnGetRealmHash /path/to/authn_digest.rb
#   require valid-user
# </Location>
#

realm_user_list = {
  "hobbits" => {
    "bilbo" => "foo",
    "frodo" => "bar",
    "samwise" => "baz",
  },
  "humans" => {
    "aragorn" => "qux",
  },
  "elves" => {
    "legolas" => "quux",
  },
  "dwarves" => {
    "gimli" => "corge",
  },
}

anp = Apache::AuthnProvider.new

user_list = realm_user_list[anp.realm]
if user_list.nil?
  Apache.return Apache::AuthnProvider::AUTH_USER_NOT_FOUND
else
  password = user_list[anp.user]
  if password.nil?
    Apache.return Apache::AuthnProvider::AUTH_USER_NOT_FOUND
  else
    anp.rethash = Digest::MD5.hexdigest([anp.user, anp.realm, password].join(":"))
    Apache.return Apache::AuthnProvider::AUTH_USER_FOUND
  end
end

Basic Authentication with Redis

# Basic Authentication Sample
#
# Apache configuration
#
# <Location /basic/>
#   AuthType basic
#   AuthName "Message for clients"
#   AuthBasicProvider mruby
#   mrubyAuthnCheckPassword /path/to/authn_basic.rb
#   require valid-user
# </Location>
#

host = "127.0.0.1"
port = 6379
anp = Apache::AuthnProvider.new
redis = Redis.new host, port

if redis.get anp.user == anp.password
  Apache.return Apache::AuthnProvider::AUTH_GRANTED
else
  Apache.return Apache::AuthnProvider::AUTH_DENIED
end

Method

Apache::AuthnProvider#user

Apache::AuthnProvider#password

Apache::AuthnProvider#realm

Apache::AuthnProvider#rethash

Apache::AuthnProvider#rethash=

Const

Const Description
Apache::AuthnProvider::AUTH_DENIED
Apache::AuthnProvider::AUTH_GRANTED
Apache::AuthnProvider::AUTH_USER_FOUND
Apache::AuthnProvider::AUTH_USER_NOT_FOUND
Apache::AuthnProvider::AUTH_GENERAL_ERROR
Clone this wiki locally
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.