aboutsummaryrefslogtreecommitdiff
path: root/bulkredirect.lua
blob: ac24e42eb1cce39e46d72c26fceb3aeac429b258 (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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
-- 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

-- Translation table for percent encoding.
local urltrans = {
   '%01', '%02', '%03', '%04', '%05', '%06', '%07', '%08',
   '%09', '%0A', '%0B', '%0C', '%0D', '%0E', '%0F', '%10',
   '%11', '%12', '%13', '%14', '%15', '%16', '%17', '%18',
   '%19', '%1A', '%1B', '%1C', '%1D', '%1E', '%1F', '%20',
   '%21', '%22', '%23', '%24', '%25', '%26', '%27', '%28',
   '%29', '%2A', '%2B', '%2C',   '-',   '.',   '/',   '0',
     '1',   '2',   '3',   '4',   '5',   '6',   '7',   '8',
     '9', '%3A', '%3B', '%3C', '%3D', '%3E', '%3F', '%40',
     'A',   'B',   'C',   'D',   'E',   'F',   'G',   'H',
     'I',   'J',   'K',   'L',   'M',   'N',   'O',   'P',
     'Q',   'R',   'S',   'T',   'U',   'V',   'W',   'X',
     'Y',   'Z', '%5B', '%5C', '%5D', '%5E',   '_', '%60',
     'a',   'b',   'c',   'd',   'e',   'f',   'g',   'h',
     'i',   'j',   'k',   'l',   'm',   'n',   'o',   'p',
     'q',   'r',   's',   't',   'u',   'v',   'w',   'x',
     'y',   'z', '%7B', '%7C', '%7D',   '~', '%7F', '%80',
   '%81', '%82', '%83', '%84', '%85', '%86', '%87', '%88',
   '%89', '%8A', '%8B', '%8C', '%8D', '%8E', '%8F', '%90',
   '%91', '%92', '%93', '%94', '%95', '%96', '%97', '%98',
   '%99', '%9A', '%9B', '%9C', '%9D', '%9E', '%9F', '%A0',
   '%A1', '%A2', '%A3', '%A4', '%A5', '%A6', '%A7', '%A8',
   '%A9', '%AA', '%AB', '%AC', '%AD', '%AE', '%AF', '%B0',
   '%B1', '%B2', '%B3', '%B4', '%B5', '%B6', '%B7', '%B8',
   '%B9', '%BA', '%BB', '%BC', '%BD', '%BE', '%BF', '%C0',
   '%C1', '%C2', '%C3', '%C4', '%C5', '%C6', '%C7', '%C8',
   '%C9', '%CA', '%CB', '%CC', '%CD', '%CE', '%CF', '%D0',
   '%D1', '%D2', '%D3', '%D4', '%D5', '%D6', '%D7', '%D8',
   '%D9', '%DA', '%DB', '%DC', '%DD', '%DE', '%DF', '%E0',
   '%E1', '%E2', '%E3', '%E4', '%E5', '%E6', '%E7', '%E8',
   '%E9', '%EA', '%EB', '%EC', '%ED', '%EE', '%EF', '%F0',
   '%F1', '%F2', '%F3', '%F4', '%F5', '%F6', '%F7', '%F8',
   '%F9', '%FA', '%FB', '%FC', '%FD', '%FE', '%FF', 
}

-- Apply percent encoding to the path part of S.
local function url_path_encode (s)
   local t = {}
   local p, q = s:match('^(.+)(?.+)')
   if p then
      t[#p+1] = q
      s = p
   end
   for i = 1, #s do
      t[i] = urltrans[s:byte(i)]
   end
   return table.concat(t)
end

function constant(t)
   return setmetatable({}, {
     __index = t,
     __newindex = function(table, key, value)
                     core.Alert("Attempt to modify read-only table")
                  end,
     __metatable = false
   });
end

RTFLAG = constant {
	WWW   = 0x1,  -- The rules for a hostname "X" apply also to
                      -- hostname "www.X"
	EXACT = 0x2,  -- Skip prefix search: the redirection reply
	              -- is returned only if the input path is present
	              -- in the table.
        STRIPPATH = 0x4,
	--[[  By default the path components stripped during the look
	      up process are added back to the returned location.  If
	      this flag is set, these components are dropped instead. ]]
	STRIPQUERY = 0x8,
	--[[  By default the query part (if any) is appended to the new
              location when returning the redirection reply.  Setting this
	      flag disables this ]]
	TEMPORARY = 0x10,  -- Return temporary (302) reply.
        URLENCODE = 0x20,
	--[[  Encode special characters in path parts of both source and
	      destination URLs as specified in RFC 3986 ("percent encoding").
	      By default, bulkencode assumes all URLs are already properly
	      encoded. ]]
	DEFAULT   = 0
}

--
-- 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 search is reduced to a single look up if the EXACT flag is set
       (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 flags STRIPPATH and STRIPQUERY.  If STRIPPATH is set, then
       removed pathname components are not added back to the location.
       Similarly, if STRIPQUERY is set, the query part is not appended to
       the location.

       The TEMPORARY flag controls the HTTP reply code.  The code is 301
       if it is not set (the default) and 302 otherwise.

       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].  The element 2 gives
       flag values for this redirect.
]]

rtflags = RTFLAG.DEFAULT

--
-- 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):gsub('%%%x%x', string.upper)
   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 rtflags = rtflags

	 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

               if type(dt) == 'string' then
		  dt = { dt }
	       end
	       
  	       location = dt[1]
	       if dt[2] ~= nil then
		  rtflags = dt[2]
	       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 (rtflags & RTFLAG.EXACT) == 0 or i == path or i..'/' == path then
	       if (rtflags & RTFLAG.STRIPPATH) == 0 then
		  location = location .. path:sub(i:len() + 1)
	       end
	       if (rtflags & RTFLAG.STRIPQUERY) == 0 and txn.f:query() then
		  location = location .. '?' .. txn.f:query()
	       end

	       core.Debug("REDIRECT " .. host .. txn.f:path() .. " to " .. location)
	       if (rtflags & RTFLAG.TEMPORARY) ~= 0 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, flags, loc)
   local valid = {
      ['www'] = RTFLAG.WWW,
      ['exact'] = RTFLAG.EXACT,
      ['strippath'] = RTFLAG.STRIPPATH,
      ['stripquery'] = RTFLAG.STRIPQUERY,
      ['temporary'] = RTFLAG.TEMPORARY,
      ['urlencode'] = RTFLAG.URLENCODE
   }

   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   

   for opt in options(s, loc) do
      local neg = opt:match("^no(%w+)$")

      if neg then
	 opt = neg
      end
      if valid[opt] then
	 if neg then
	    flags = flags & ~valid[opt]
	 else
	    flags = flags | valid[opt]
	 end
      else
	 error(loc .. ': invalid option ' .. opt, 0)
      end
   end
   return flags
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
      core.Info(require('inspect')(dt[path]))
      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
	    if not crt[compl] then crt[compl] = {} end
	    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 = 0

   local rt = {}
   local domain_flags = rtflags

   local parsetab = {
      { '^#', function () end },
      { '^%s*$', function () end },
      { '^option%s+(.*)',
	function (s)
	   if domain then
	      domain_flags = parseopt(s, domain_flags, filename .. ':' .. ln)
	   else
	      rtflags = parseopt(s, rtflags, filename .. ':' .. ln)
	   end	   
        end
      },
      { '^%s*%[(.+)%]%s*$',
	function (s)
	   domain = s
	   if not rt[domain] then rt[domain] = {} end
	   domain_flags = rtflags
        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 rule_flags = domain_flags
	   if optlist ~= '' then
	      rule_flags = parseopt(optlist, rule_flags, filename .. ':' .. ln)
	   end

	   if (rule_flags & RTFLAG.URLENCODE) ~= 0 then
	      src = url_path_encode(src)
	      dst = url_path_encode(dst)
	   else
	      src = src:gsub('%%%x%x', string.upper)
	   end

	   local dpath, dquery = dst:match('^(.+)?(.*)')
           if dpath then
	      if (rule_flags & RTFLAG.STRIPPATH) == 0 and ((rule_flags ~ domain_flags) & RTFLAG.STRIPPATH) ~= 0  then
		 core.Warning(filename .. ':' .. ln .. ': nostrippath ignored because of explicit query in the destination')
	      end
	      if (rule_flags & RTFLAG.STRIPQUERY) == 0 and ((rule_flags ~ domain_flags) & RTFLAG.STRIPQUERY) ~= 0 then
		 core.Warning(filename .. ':' .. ln .. ': nostripquery ignored because of explicit query in the destination')
	      end

	      rule_flags = rule_flags | RTFLAG.STRIPPATH
	      rule_flags = rule_flags | RTFLAG.STRIPQUERY
	      if dquery == '' then
		 dst = dpath
	      end
	   end

	   if ((rule_flags ~ rtflags) & ~RTFLAG.URLENCODE) ~= 0 then
 	      if type(dst) == 'string' then dst = { dst } end
	      dst[2] = rule_flags
	   end

	   if (rule_flags & RTFLAG.WWW) ~= 0 then
	      if (rtflags & RTFLAG.WWW) == 0 then
		 local s = www_complement(domain)
	         if not rt[s] then rt[s] = {} end
                 set_dst(rt[s], src, dst)
	      end
	   elseif (rtflags & RTFLAG.WWW) ~= 0 then
	      populate_www_complements(rt, true)
	      rtflags = rtflags & ~RTFLAG.WWW
	      local s = www_complement(domain)
	      if not rt[s] then rt[s] = {} end
	   end
	   set_dst(rt[domain], src, dst)
        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 (rtflags & RTFLAG.WWW) ~= 0 then
      populate_www_complements (rt, false)
      rtflags = rtflags & ~RTFLAG.WWW
   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, rtflags = 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.