aboutsummaryrefslogtreecommitdiff
path: root/bulkredirect.lua
blob: 211d3352a126b351875da38969ac639016945a93 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
-- Bulk redirects for HAProxy
-- Copyright (C) 2021 Sergey Poznyakoff
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 3, or (at your option)
-- any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program.  If not, see <http://www.gnu.org/licenses/>.

local bulkredirect = {}
__ENV = bulkredirect

--[[
   Iterator factory to successively strip off the trailing pathname
   element from a path.

   On input, T is the pathname (optionally terminated by /).
   Returns iterator function that, on each call, returns the pathname
   with its trailing element removed.  Trailing element here means the
   everything past the last '/' character.
]]   
local function prevsegm (t)
   local s = t
   if not s:match("/$") then s = s .. "/" end
   return function ()
      s = s:match("(.*)/")
      return s
   end
end

--
-- Module global variables:
--

rt = {}
--[[   Redirection table.  It is indexed by the request host name
       (the value given by the HTTP Host header).  The corresponding value
       can be either a string or a table.

       A string value refers to another host name (an alias).

       A table supplies the actual mapping from an URI to another URL.
       When a request to P?Q arrives (where P denotes the pathname part and
       Q denotes query arguments), the P is looked up in the table.  If the
       entry rt[P] does not exist, the trailing pathname component is
       removed from P and the resulting string P1 (unless it is empty) is
       used as the look-up key.  The process continues until either the entry
       rt[P1] is found, or P1 is reduced to an empty string.  The latter means
       there is no redirect for the given P?Q combination.

       The lookup process is reduced to a single look up if the global
       variable 'exact' is true (see below).

       If the entry rt[P1] is found and is a string, it gives the location
       of the redirect.  Prior to returning a 301 reply, this location is
       augmented by pathname part removed from P during the look up process,
       and the query part (if any).  These modifications are controlled by
       the global variables 'strippath' and 'stripquery'.  If 'strippath' is
       true, the removed pathname components are not added back to the
       location.  Similarly, if 'stripquery' is true, the query part is not
       appended to the location.  The 301 reply code is the default.  If the
       'temporary' global variable is set to true, the code 302 will be used
       instead.

       If rt[P1] is a table, it must contain a sequence of two elements.
       The element rt[P1][1] supplies the new location if Q is not present.
       The element rt[P1][2] is an associative table, indexed by possible
       values of Q (including empty value).  Both rt[P1][1] and rt[P1][2][Q]
       can contain either a string or a table value.  The string value
       supplies the new location as described above.  The table value
       supplies the new location in the element [1].  Rest of elements
       (2 up to 5) are boolean values overriding the default global variables
       for this entry.  They are located in the following order:

        2 - exact
        3 - strippath
        4 - stripquery
        5 - temporary
]]

www = false
--[[   If set to true, the rules for a hostname "X" apply also to
       hostname "www.X"
]]

exact = false
--[[   If set to true, no path prefix search is done: the redirection reply
       is returned only if the input path is present in the table.
]]

strippath = false
--[[   By default the path components stripped during the look up process
       are added back to the returned location.  If this variable is set
       to true, these components are dropped instead.
]]

stripquery = false
--[[   By default the query part (if any) is appended to the new
       location when returning the redirection reply.  Setting this variable
       to true disables this
]]

temporary = false
--     Whether to return temporary (302) or permanent (301) reply.

--
-- Redirect the request if it matches one of the entries in the RT table.
--
function bulkredirect.request (txn)
   local headers = txn.http:req_get_headers()
   local reply = txn:reply()
   local path = txn.f:path():sub(2)
   local host = headers["host"][0]

   -- Get the per-host redirection table
   local rthost = rt[host]

   -- Resolve eventual alias chain.
   while type(rthost) == 'string'
   do
      rthost = rt[rthost]
   end

   -- If no corresponding host entry found, start from the default
   -- entry.
   if not rthost then
      rthost = rt["*"]
   end
   
   if rthost then
      local location

      -- Successively strip the trailing element off the path and look up
      -- the remaining part in the table.
      for i in prevsegm(path) do
	 local exact, strippath, stripquery, temporary = exact, strippath, stripquery, temporary

	 if rthost[i] then
	    -- If the entry is found, it is either a table or a string
	    if type(rthost[i]) == 'table' then
	       local dt = rthost[i]
	       local query = txn.f:query()
	       if query then
		  if dt[2] then
		     dt = dt[2][query]
		  else
		     dt = dt[1]
		  end
	       else
		  dt = dt[1]
	       end

  	       location = dt[1]
	       if dt[2] ~= nil then
		  exact = dt[2]
	       end
	       if dt[3] ~= nil then
		  strippath = dt[3]
	       end
	       if dt[4] ~= nil then
		  stripquery = dt[4]
	       end
	       if dt[5] ~= nil then
		  temporary = dt[5]
	       end
	    else
	       location = rthost[i]
	    end
         end

	 if location then
	    if not (location:match('^http://') or location:match('^https://')
		    or location:match('^/')) then
	       location = '/'..location
	    end
	    
	    if not exact or i == path or i..'/' == path then
	       if not strippath then
		  location = location .. path:sub(i:len() + 1)
	       end
	       if not stripquery and txn.f:query() then
		  location = location .. '?' .. txn.f:query()
	       end

	       core.Debug("REDIRECT " .. host .. txn.f:path() .. " to " .. location)
	       if temporary then
		  reply:set_status(302, "Moved Temporarily")
	       else
		  reply:set_status(301, "Moved Permanently")
	       end
               reply:add_header("Location", location)
               txn:done(reply)
               break
	    end
	 end
      end
   end
end  

-- Populate the redirection table
--[[
   Syntax:

     input ::= statement | input statement
     statement ::= option | domain | redirect
     option ::= 'option' optlist [,]
     domain ::= '[' HOSTNAME ']'
     redirect ::= STRING STRING optlist [,]
     optlist ::= OPTNAME | optilist ',' OPTNAME
     OPTNAME ::= 'www' | 'exact' | 'strippath' | 'stripquery' | 'temporary'
                 <or any of these prefixed with 'no'>
     HOSTNAME ::= <any valid hostname>
]]

local function parseopt (s, t, loc)
   local valid = {
      ['www'] = true,
      ['exact'] = true,
      ['strippath'] = true,
      ['stripquery'] = true,
      ['temporary'] = true
   }

   function options (str, loc)
      local s = str
      return function ()
         if s == nil or s == "" then
	    return nil
         end
      
         local opt, rest
         opt, rest = s:match("^(%w+)%s*,%s*(.*)")
         if not opt then
	    opt = s:match("^%w+$")
	    if not opt then
	       error(loc .. ": bad option list syntax near " .. s, 0)
	    end
         end
         s = rest
         return opt
      end
   end   

   if not t then
      t = _ENV
   end
   
   for opt in options(s, loc) do
      local neg = opt:match("^no(%w+)$")
      local val = true

      if neg then
	 opt = neg
	 val = not val
      end
      if not valid[opt] then
	 error(loc .. ': invalid option ' .. opt, 0)
      end

      t[opt] = val
   end
end

local function set_dst (dt, src, dst)
   local path, query = src:match('^(.+)?(.+)')
   if path then
      if not dt[path] then
	 dt[path] = {nil, {}}
      elseif type(dt[path]) == 'string' then
	 dt[path] = { { dt[path] }, {} }
      end
      dt[path][2][query] = dst
   elseif type(dt[src]) == 'table' then
      dt[src][1] = dst
   elseif type(dst) == 'table' then
      dt[src] = { dst }
   else
      dt[src] = dst
   end
end

local function clone (orig)
   local copy
   if type(orig) == 'table' then
      copy = {}
      for k,v in pairs(orig) do
	 copy[k] = clone(v)
      end
      setmetatable(copy, clone(getmetatable(orig)))
   else
      copy = orig
   end
   return copy
end

local function www_complement (name)
   local s = name:match('^www%.(.+)')
   if not s then s = 'www.' .. name end
   return s
end

local function populate_www_complements (rt, dup)
   local crt = {}

   for d,t in pairs(rt) do
      local compl = www_complement(d)
      if rt[compl] then
	 for k,v in pairs(t) do
	    -- FIXME: Error message if rt[compl][k] exists
	    crt[compl][k] = clone(v)
	 end
      elseif dup then
	 crt[compl] = clone(t)
      else
	 crt[compl] = d
      end
   end

   for d,t in pairs(crt) do
      rt[d] = t
   end
end

local function load_redirect_file (f, filename)
   local domain
   local ln = 1

   local rt = {}
   local domopt = {}

   local parsetab = {
      { '^#', function () end },
      { '^%s*$', function () end },
      { '^option%s+(.*)',
	function (s)
	   local t
	   if domain then
	      t = domopt
	   else
	      t = _ENV
	   end 
	   parseopt(s, t, filename .. ':' .. ln)
        end
      },
      { '^%s*%[(.+)%]%s*$',
	function (s)
	   domain = s
	   if not rt[domain] then rt[domain] = {} end
        end
      },
      { '^%s*([^%s]+)%s+([^%s]+)%s*(.*)$',
	function (src, dst, optlist)
	   if not domain then
	      error(filename .. ':' .. ln .. ': declare [domain] first', 0)
	   end
      
	   if src:match('^/') then
	      src = src:sub(2)
	   end

	   if dst:match('^/') then
	      dst = dst:sub(2)
	   end

	   local optab = domopt
	   if optlist ~= '' then
	      optab = clone(domopt)
	      parseopt(optlist, optab, filename .. ':' .. ln)
	   end

	   local dpath, dquery = dst:match('^(.+)?(.*)')
           if dpath then
	      if optab['strippath'] == false and optab['strippath'] ~= domopt['strippath'] then
		 core.Warning(filename .. ':' .. ln .. ': nostrippath ignored because of explicit query in the destination')
	      end
	      if optab['stripquery'] == false and optab['stripquery'] ~= domopt['stripquery'] then
		 core.Warning(filename .. ':' .. ln .. ': nostripquery ignored because of explicit query in the destination')
	      end
	      
	      optab['strippath'] = true
	      optab['stripquery'] = true
	      if dquery == '' then
		 dst = dpath
	      end
	   end

	   if optab['exact'] ~= exact then
 	      if type(dst) == 'string' then dst = { dst } end
	      dst[2] = optab['exact']
	   end
	   if optab['strippath'] ~= strippath then
 	      if type(dst) == 'string' then dst = { dst } end
	      dst[3] = optab['strippath']
	   end
	   if optab['stripquery'] ~= stripquery then
 	      if type(dst) == 'string' then dst = { dst } end
	      dst[4] = optab['stripquery']
	   end
	   if optab['temporary'] ~= temporary then
 	      if type(dst) == 'string' then dst = { dst } end
	      dst[5] = optab['temporary']
	   end

           if optab['www'] ~= nil then
	      if www == optab['www'] then
		 return
	      elseif www then
	         populate_www_complements (rt, true)
	         www = nil
	      end
	   end
	 
	   set_dst(rt[domain], src, dst)

	   if optab['www'] then
	      local s = www_complement(domain)
	      if not rt[s] then rt[s] = {} end
              set_dst(rt[s], src, dst)
	   end
        end
      }
   }
   
   for line in f:lines() do
      ln = ln + 1
      for i = 1, #parsetab do
	 local t = {line:match(parsetab[i][1])}
	 if t[1] then
	    parsetab[i][2](table.unpack(t))
	    goto continue
	 end
      end

      error(filename .. ':' .. ln .. ': syntax error', 0)
      ::continue::
   end

   if www then
      populate_www_complements (rt, false)
      www = nil
   end
   
   _ENV['rt'] = rt
end

local function load_redirect_table ()
   local name = os.getenv('HAPROXY_BULKREDIRECT')
   if name == nil then
      name = '/etc/haproxy/bulkredirect.rt'
   end
   if name:match('%.lua$') then
      rt, www, exact, strippath, stripquery, temporary = dofile(name)
   else		    
      local file, err = io.open(name,"r")
      if file ~= nil then
	 local status, err = pcall(load_redirect_file, file, name)
	 file:close()
         if not status then
	    core.Alert(err)
	 end
--	 print(require('inspect')(rt))
      else
         core.Alert("can't open " .. name .. ": " .. err)
      end
   end
end

-- Load redirects
load_redirect_table()

-- Register the actions with HAProxy
core.register_action("bulkredirect", {"http-req"}, bulkredirect.request, 0)

Return to:

Send suggestions and report system problems to the System administrator.