root/src/modules-lua/noit/module/http.lua

Revision f291bb5ab0ef376b5f15b11df991efb2cdaeabc1, 22.6 kB (checked in by Philip Maddox <pmaddox@circonus.com>, 3 years ago)

Added vastly improved cookie support and fixed some bugs with redirect when the given URI is not an absolute path

  • Property mode set to 100644
Line 
1 -- Copyright (c) 2008, OmniTI Computer Consulting, Inc.
2 -- All rights reserved.
3 --
4 -- Redistribution and use in source and binary forms, with or without
5 -- modification, are permitted provided that the following conditions are
6 -- met:
7 --
8 --     * Redistributions of source code must retain the above copyright
9 --       notice, this list of conditions and the following disclaimer.
10 --     * Redistributions in binary form must reproduce the above
11 --       copyright notice, this list of conditions and the following
12 --       disclaimer in the documentation and/or other materials provided
13 --       with the distribution.
14 --     * Neither the name OmniTI Computer Consulting, Inc. nor the names
15 --       of its contributors may be used to endorse or promote products
16 --       derived from this software without specific prior written
17 --       permission.
18 --
19 -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 -- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31 module(..., package.seeall)
32
33 function onload(image)
34   image.xml_description([=[
35 <module>
36   <name>http</name>
37   <description><para>The http module performs GET requests over either HTTP or HTTPS and checks the return code and optionally the body.</para>
38   </description>
39   <loader>lua</loader>
40   <object>noit.module.http</object>
41   <checkconfig>
42     <parameter name="url"
43                required="required"
44                allowed=".+">The URL including schema and hostname (as you would type into a browser's location bar).</parameter>
45     <parameter name="header_(\S+)"
46                required="optional"
47                allowed=".+">Allows the setting of arbitrary HTTP headers in the request.</parameter>
48     <parameter name="method"
49                required="optional"
50                allowed="\S+"
51                default="GET">The HTTP method to use.</parameter>
52     <parameter name="payload"
53                required="optional"
54                allowed=".*">The information transferred as the payload of an HTTP request.</parameter>
55     <parameter name="auth_method"
56                required="optional"
57                allowed="^(?:Basic|Digest|Auto)$">HTTP Authentication method to use.</parameter>
58     <parameter name="auth_user"
59                required="optional"
60                allowed="[^:]*">The user to authenticate as.</parameter>
61     <parameter name="auth_password"
62                required="optional"
63                allowed=".*">The password to use during authentication.</parameter>
64     <parameter name="ca_chain"
65                required="optional"
66                allowed=".+">A path to a file containing all the certificate authorities that should be loaded to validate the remote certificate (for SSL checks).</parameter>
67     <parameter name="certificate_file"
68                required="optional"
69                allowed=".+">A path to a file containing the client certificate that will be presented to the remote server (for SSL checks).</parameter>
70     <parameter name="key_file"
71                required="optional"
72                allowed=".+">A path to a file containing key to be used in conjunction with the cilent certificate (for SSL checks).</parameter>
73     <parameter name="ciphers"
74                required="optional"
75                allowed=".+">A list of ciphers to be used in the SSL protocol (for SSL checks).</parameter>
76     <parameter name="code"
77                required="optional"
78                default="^200$"
79                allowed=".+">The HTTP code that is expected.  If the code received does not match this regular expression, the check is marked as "bad."</parameter>
80     <parameter name="redirects"
81                required="optional"
82                default="0"
83                allowed="\d+">The maximum number of Location header redirects to follow.</parameter>
84     <parameter name="body"
85                required="optional"
86                allowed=".+">This regular expression is matched against the body of the response. If a match is not found, the check will be marked as "bad."</parameter>
87     <parameter name="body_match_*"
88                required="optional"
89                allowed=".+">This regular expression is matched against the body of the response. If a match is found it is captured and added as a metric. For example, if setting is named 'body_match_foo_bar' and a match is found new metric called 'foo_bar' will be added.</parameter>
90     <parameter name="extract"
91                required="optional"
92                allowed=".+">This regular expression is matched against the body of the response globally.  The first capturing match is the key and the second capturing match is the value.  Each key/value extracted is registered as a metric for the check.</parameter>
93     <parameter name="pcre_match_limit"
94                required="optional"
95                default="10000"
96                allowed="\d+">This sets the PCRE internal match limit (see pcreapi documentation).</parameter>
97     <parameter name="include_body"
98                required="optional"
99                allowed="^(?:true|false|on|off)$"
100                default="false">Include whole response body as a metric with the key 'body'.</parameter>
101     <parameter name="read_limit"
102                required="optional"
103                default="0"
104                allowed="\d+">Sets an approximate limit on the data read (0 means no limit).</parameter>
105   </checkconfig>
106   <examples>
107     <example>
108       <title>Checking an HTTP and HTTPS URL.</title>
109       <para>This example checks the OmniTI Labs website over both HTTP and HTTPS.</para>
110       <programlisting><![CDATA[
111       <noit>
112         <modules>
113           <loader image="lua" name="lua">
114             <config><directory>/opt/reconnoiter/libexec/modules-lua/?.lua</directory></config>
115           </loader>
116           <module loader="lua" name="http" object="noit.module.http" />
117         </modules>
118         <checks>
119           <labs target="8.8.38.5" module="http">
120             <check uuid="fe3e984c-7895-11dd-90c1-c74c31b431f0" name="http">
121               <config><url>http://labs.omniti.com/</url></config>
122             </check>
123             <check uuid="1ecd887a-7896-11dd-b28d-0b4216877f83" name="https">
124               <config><url>https://labs.omniti.com/</url></config>
125             </check>
126           </labs>
127         </checks>
128       </noit>
129     ]]></programlisting>
130     </example>
131   </examples>
132 </module>
133 ]=]);
134   return 0
135 end
136
137 function init(module)
138   return 0
139 end
140
141 function config(module, options)
142   return 0
143 end
144
145 local HttpClient = require 'noit.HttpClient'
146
147 local BODY_MATCHES_PREFIX = 'body_match_'
148
149 function elapsed(check, name, starttime, endtime)
150     local elapsedtime = endtime - starttime
151     local seconds = string.format('%.3f', noit.timeval.seconds(elapsedtime))
152     check.metric_uint32(name, math.floor(seconds * 1000 + 0.5))
153     return seconds
154 end
155
156 function populate_cookie_jar(cookies, host, hdr)
157     local path = nil
158     if hdr ~= nil then
159         local name, value, trailer =
160             string.match(hdr, "([^=]+)=([^;]+);?%s*(.*)")
161         if name ~= nil then
162             local jar = { }
163             local fields = noit.extras.split(trailer, ";")
164             if fields ~= nil then
165                 for k, v in pairs(fields) do
166                     local pair = noit.extras.split(v, "=", 1);
167                     if pair ~= nil and pair[1] ~= nil and pair[2] ~= nil then
168                         local name = (string.gsub(pair[1], "^%s*(.-)%s*$", "%1"));
169                         local setting = (string.gsub(pair[2], "^%s*(.-)%s*$", "%1"));
170                         if name == "path" then
171                             path = setting
172                         end
173                     end
174                 end
175             end
176             if string.sub(name, 1, 1) ~= ";" and string.sub(value, 1, 1) ~= ";" then
177                 if path == nil then path = "/" end
178                 if cookies[host] == nil then cookies[host] = { } end
179                 if cookies[host][path] == nil then cookies[host][path] = { } end
180                 jar.name = name
181                 jar.value = value
182                 table.insert(cookies[host][path], jar)
183             end
184         end
185     end
186 end
187
188 function has_host(pat, host)
189     if pat == host then return true end
190     if pat:sub(1,1) ~= "." then return false end
191     local revpat = pat:sub(2):reverse()
192     local revhost = host:reverse()
193     if revpat == revhost then return true end
194     if revpat == revhost:sub(1, revpat:len()) then
195         if revhost:sub(pat:len(), pat:len()) == "." then return true end
196     end
197     return false
198 end
199
200 function apply_cookies(headers, cookies, host, uri)
201     local use_cookies = { }
202     for h, paths in pairs(cookies) do
203         if has_host(h, host) then
204             local split_uri = noit.extras.split(uri, "/")
205             if split_uri ~= nil then
206                 local path = ""
207                 for i, val in pairs(split_uri) do
208                     local append = true
209                     if val == nil then val = "" end
210                     if #split_uri == i and string.find(val, "%.") ~= nil then append = false end
211                     if append == true then
212                         path = path .. "/" .. val
213                         if string.len(path) >= 2 and string.sub(path, 1, 2) == "//" then
214                             path = string.sub(path, 2)
215                         end
216                     end
217                     if path == "" then path = "/" end
218                     local rindex = string.match(path, '.*()'..'%?')
219                     if rindex ~= nil then
220                         path = string.sub(path, 1, rindex-1)
221                     end
222                     if path ~= "/" then
223                         while string.find(path, "/", -1) ~= nil do
224                             path = string.sub(path, 1, -2)
225                         end
226                     end
227                     if paths[path] ~= nil then
228                         local jars = paths[path]
229                         for index, jar in ipairs(jars) do
230                             use_cookies[jar.name] = jar.value
231                         end
232                     end
233                 end
234             end
235         end
236     end
237     for name, value in pairs(use_cookies) do
238         if headers["Cookie"] == nil then
239             headers["Cookie"] = name .. "=" .. value
240         else
241             headers["Cookie"] = headers["Cookie"] .. "; " .. name .. "=" .. value
242         end
243     end
244 end
245
246 function get_new_uri(old_uri, new_uri)
247     if new_uri == nil then return "/" end
248     if new_uri == "/" then return new_uri end
249     local toReturn = old_uri
250     while string.find(toReturn, "/", -1) ~= nil do
251         toReturn = string.sub(toReturn, 1, -2)
252     end
253     if string.sub(new_uri, 1, 1) == '?' then
254         local rindex = string.match(toReturn, '.*()'.."/")
255         toReturn = string.sub(toReturn, 1, rindex-1)
256         toReturn = toReturn .. new_uri
257     elseif string.sub(new_uri, 1, 1) ~= "." then
258         toReturn = new_uri
259     else
260         toReturn = string.gsub(toReturn, "%/%?", "?")
261         while string.sub(new_uri, 1, 1) == "." do
262             if string.find(new_uri, "%./") == 1 then
263                 new_uri = string.gsub("%./", "", 1)
264             elseif string.find(new_uri, "%.%./") == 1 then
265                 --strip out last bit from toReturn
266                 local rindex = string.match(toReturn, '.*()'.."/")
267                 toReturn = string.sub(toReturn, 1, rindex-1)
268                 new_uri = string.gsub(new_uri, "../", "", 1)
269             else
270                 -- bad URI... just return /
271                 return "/"
272             end
273         end
274         toReturn = toReturn .. "/" .. new_uri
275     end
276     return toReturn
277 end
278
279 function get_absolute_path(uri)
280     if uri == nil then return "/" end
281     local toReturn = uri
282     local go_back = string.find(toReturn, "%.%./")
283     while go_back ~= nil do
284         local tojoin = go_back + 3
285         go_back = go_back - 2
286         local back_substring = string.sub(toReturn, 1, go_back)
287         local forward_substring = string.sub(toReturn, tojoin)
288         local rindex = string.match(back_substring, '.*()' .. "/")
289         if rindex ~= nil then
290             toReturn = string.sub(toReturn, 1, rindex) .. forward_substring
291         end
292         go_back = string.find(toReturn, "%.%./")
293     end
294     toReturn = string.gsub(toReturn, "%./", "")
295     return toReturn
296 end
297
298 function initiate(module, check)
299     local url = check.config.url or 'http:///'
300     local schema, host, port, uri = string.match(url, "^(https?)://([^:/]*):?([0-9]*)(/?.*)$");
301     local use_ssl = false
302     local codere = noit.pcre(check.config.code or '^200$')
303     local good = false
304     local starttime = noit.timeval.now()
305     local method = check.config.method or "GET"
306     local max_len = 80
307     local pcre_match_limit = check.config.pcre_match_limit or 10000
308     local redirects = check.config.redirects or 0
309     local include_body = false
310     local read_limit = tonumber(check.config.read_limit) or nil
311
312     -- expect the worst
313     check.bad()
314     check.unavailable()
315
316     if host == nil then host = check.target end
317     if schema == nil then
318         schema = 'http'
319         uri = '/'
320     end
321     if uri == '' then
322         uri = '/'
323     end
324     if port == '' or port == nil then
325         if schema == 'http' then
326             port = check.config.port or 80
327         elseif schema == 'https' then
328             port = check.config.port or 443
329         else
330             error(schema .. " not supported")
331         end
332     end
333     if schema == 'https' then
334         use_ssl = true
335     end
336
337     -- Include body as a metric
338     if check.config.include_body == "true" or check.config.include_body == "on" then
339         include_body = true
340     end
341
342     local output = ''
343     local connecttime, firstbytetime
344     local next_location
345     local cookies = { }
346     local setfirstbyte = 1
347
348     -- callbacks from the HttpClient
349     local callbacks = { }
350     callbacks.consume = function (str)
351         if setfirstbyte == 1 then
352             firstbytetime = noit.timeval.now()
353             setfirstbyte = 0
354         end
355         output = output .. (str or '')
356     end
357     callbacks.headers = function (hdrs, setcookies)
358         next_location = hdrs.location
359         for key, value in pairs(setcookies) do
360             populate_cookie_jar(cookies, host, value)
361         end
362     end
363
364     callbacks.connected = function () connecttime = noit.timeval.now() end
365
366     -- setup SSL info
367     local default_ca_chain =
368         noit.conf_get_string("/noit/eventer/config/default_ca_chain")
369     callbacks.certfile = function () return check.config.certificate_file end
370     callbacks.keyfile = function () return check.config.key_file end
371     callbacks.cachain = function ()
372         return check.config.ca_chain and check.config.ca_chain
373                                       or default_ca_chain
374     end
375     callbacks.ciphers = function () return check.config.ciphers end
376
377     -- set the stage
378     local headers = {}
379     headers.Host = host
380     for header, value in pairs(check.config) do
381         hdr = string.match(header, '^header_(.+)$')
382         if hdr ~= nil then
383           headers[hdr] = value
384         end
385     end
386     if check.config.auth_method == "Basic" then
387         local user = check.config.auth_user or ''
388         local password = check.config.auth_password or ''
389         local encoded = noit.base64_encode(user .. ':' .. password)
390         headers["Authorization"] = "Basic " .. encoded
391     elseif check.config.auth_method == "Digest" or
392            check.config.auth_method == "Auto" then
393         -- this is handled later as we need our challenge.
394         local client = HttpClient:new()
395         local rv, err = client:connect(check.target_ip, port, use_ssl)
396         if rv ~= 0 then
397             check.status(str or "unknown error")
398             return
399         end
400         local headers_firstpass = {}
401         for k,v in pairs(headers) do
402             headers_firstpass[k] = v
403         end
404         client:do_request(method, uri, headers_firstpass)
405         client:get_response(read_limit)
406         if client.code ~= 401 or
407            client.headers["www-authenticate"] == nil then
408             check.status("expected digest challenge, got " .. client.code)
409             return
410         end
411         local user = check.config.auth_user or ''
412         local password = check.config.auth_password or ''
413         local ameth, challenge =
414             string.match(client.headers["www-authenticate"], '^(%S+)%s+(.+)$')
415         if check.config.auth_method == "Auto" and ameth == "Basic" then
416             local encoded = noit.base64_encode(user .. ':' .. password)
417             headers["Authorization"] = "Basic " .. encoded
418         elseif ameth == "Digest" then
419             headers["Authorization"] =
420                 "Digest " .. client:auth_digest(method, uri,
421                                          user, password, challenge)
422         else
423             check.status("Unexpected auth '" .. ameth .. "' in challenge")
424             return
425         end
426     elseif check.config.auth_method ~= nil then
427       check.status("Unknown auth method: " .. check.config.auth_method)
428       return
429     end
430
431     -- perform the request
432     local client
433     local dns = noit.dns()
434     local target = check.target_ip
435     local payload = check.config.payload
436     -- artificially increase redirects as the initial request counts
437     redirects = redirects + 1
438     starttime = noit.timeval.now()
439     repeat
440         local optclient = HttpClient:new(callbacks)
441         local rv, err = optclient:connect(target, port, use_ssl)
442
443         if rv ~= 0 then
444             check.status(err or "unknown error")
445             return
446         end
447         optclient:do_request(method, uri, headers, payload)
448         optclient:get_response(read_limit)
449         setfirstbyte = 1
450
451         redirects = redirects - 1
452         client = optclient
453
454         if next_location ~= nil then
455             -- reset some stuff for the redirect
456             local prev_port = port
457             local prev_host = host
458             local prev_uri = uri
459             method = 'GET'
460             payload = nil
461             schema, host, port, uri =
462                 string.match(next_location,
463                              "^(https?)://([^:/]*):?([0-9]*)(/?.*)$")
464             if schema == nil then
465                 port = prev_port
466                 host = prev_host
467                 uri = get_new_uri(prev_uri, next_location)
468             elseif schema == 'http' then
469                 use_ssl = false
470                 if port == "" then port = 80 end
471             elseif schema == 'https' then
472                 use_ssl = true
473                 if port == "" then port = 443 end
474             end
475             uri = get_absolute_path(uri)
476             if host ~= nil then
477                 headers.Host = host
478                 local r = dns:lookup(host)
479                 if not r or r.a == nil then
480                     check.status("failed to resolve " .. host)
481                     return
482                 end
483                 target = r.a
484             end
485             while string.find(host, "/", -1) ~= nil do
486                 host = string.sub(host, 1, -2)
487             end
488             headers["Cookie"] = check.config["header_Cookie"]
489             apply_cookies(headers, cookies, host, uri)
490         end
491     until redirects <= 0 or next_location == nil
492
493     local endtime = noit.timeval.now()
494     check.available()
495
496     local status = ''
497     -- setup the code
498     check.metric_string("code", client.code)
499     status = status .. 'code=' .. client.code
500     if codere ~= nil and codere(client.code) then
501       good = true
502     end
503
504     -- truncated response
505     check.metric_uint32("truncated", client.truncated and 1 or 0)
506
507     -- turnaround time
508     local seconds = elapsed(check, "duration", starttime, endtime)
509     status = status .. ',rt=' .. seconds .. 's'
510     elapsed(check, "tt_connect", starttime, connecttime)
511
512     if firstbytetime ~= nil then
513       elapsed(check, "tt_firstbyte", starttime, firstbytetime)
514     end
515
516     -- size
517     status = status .. ',bytes=' .. client.content_bytes
518     check.metric_int32("bytes", client.content_bytes)
519
520     if check.config.extract ~= nil then
521       local exre = noit.pcre(check.config.extract)
522       local rv = true
523       local m = nil
524       while rv and m ~= '' do
525         rv, m, key, value = exre(output or '', { limit = pcre_match_limit })
526         if rv and key ~= nil then
527           check.metric(key, value)
528         end
529       end
530     end
531
532     -- check body
533     if check.config.body ~= nil then
534       local bodyre = noit.pcre(check.config.body)
535       local rv, m, m1 = bodyre(output or '')
536       if rv then
537         m = m1 or m or output
538         if string.len(m) > max_len then
539           m = string.sub(m,1,max_len)
540         end
541         status = status .. ',body=matched'
542         check.metric_string('body_match', m)
543       else
544         status = status .. ',body=failed'
545         check.metric_string('body_match', nil)
546         good = false
547       end
548     end
549
550     -- check body matches
551     local matches = 0
552     has_body_matches = false
553     for key, value in pairs(check.config) do
554       m = string.find(key, BODY_MATCHES_PREFIX)
555
556       if m == 1 then
557         has_body_matches = true
558         key = string.gsub(key, BODY_MATCHES_PREFIX, '')
559
560         local bodyre = noit.pcre(value)
561         local rv, m, m1 = bodyre(output or '')
562
563         if rv then
564           matches = matches + 1
565           m = m1 or m or output
566           if string.len(m) > max_len then
567             m = string.sub(m,1,max_len)
568           end
569           check.metric_string('body_match_' .. key, m)
570         else
571           check.metric_string('body_match_' .. key, nil)
572         end
573       end
574     end
575
576     if has_body_matches then
577       status = status .. ',body_matches=' .. tostring(matches) .. ' matches'
578     end
579
580     -- Include body
581     if include_body then
582         check.metric_string('body', output or '')
583     end
584
585     -- ssl ctx
586     local ssl_ctx = client:ssl_ctx()
587     if ssl_ctx ~= nil then
588       if ssl_ctx.error ~= nil then status = status .. ',sslerror' end
589       check.metric_string("cert_error", ssl_ctx.error)
590       check.metric_string("cert_issuer", ssl_ctx.issuer)
591       check.metric_string("cert_subject", ssl_ctx.subject)
592       check.metric_uint32("cert_start", ssl_ctx.start_time)
593       check.metric_uint32("cert_end", ssl_ctx.end_time)
594       check.metric_int32("cert_end_in", ssl_ctx.end_time - os.time())
595       if noit.timeval.seconds(starttime) > ssl_ctx.end_time then
596         good = false
597         status = status .. ',ssl=expired'
598       end
599     end
600
601     if good then check.good() else check.bad() end
602     check.status(status)
603 end
604
Note: See TracBrowser for help on using the browser.