Class: DomainRedirects::Parser

Inherits:
Object
  • Object
show all
Defined in:
modules/wmflib/lib/puppet/functions/wmflib/compile_redirects.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source, web_server = 'apache') ⇒ Parser

Returns a new instance of Parser.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'modules/wmflib/lib/puppet/functions/wmflib/compile_redirects.rb', line 19

def initialize(source, web_server = 'apache')
  @lines = source.lines.map(&:rstrip)
  @web_server = web_server
  if @web_server == 'apache'
    @original_request = '$0'
    @group_dest = '%1'
  else
    @original_request = '$request_uri'
    @group_dest = '$1'
  end
  @rules = {
    :wildcard           => [],
    :plain              => [],
    :wildcard_override  => [],
    :plain_override     => [],
  }
end

Instance Attribute Details

#line_numObject

Returns the value of attribute line_num.



17
18
19
# File 'modules/wmflib/lib/puppet/functions/wmflib/compile_redirects.rb', line 17

def line_num
  @line_num
end

Instance Method Details

#check_loopsObject

Check for double or infinite redirects and raise an error if any are found.



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
# File 'modules/wmflib/lib/puppet/functions/wmflib/compile_redirects.rb', line 241

def check_loops
  flat_rules = @rules.values.flatten
  flat_rules.each do |outbound_rule|
    flat_rules.each do |inbound_rule|
      outbound_domain = outbound_rule[:dest_domain]
      inbound_domain = inbound_rule[:domain]
      inbound_regex = inbound_rule[:domain_regex]
      if outbound_domain =~ /#{@group_dest.sub('$', '\$')}/
        if inbound_domain.end_with? $'
          error("double redirect: rule has destination domain #{outbound_domain} "\
                "which matches relevant suffix of source domain '#{inbound_domain}' "\
                "from line #{inbound_rule[:line_num]}", outbound_rule[:line_num])
        end
      elsif inbound_regex[0] == '='
        if inbound_domain == outbound_domain
          error("double redirect: rule has destination domain #{outbound_domain} "\
                "from line #{inbound_rule[:line_num]}", outbound_rule[:line_num])
        end
      elsif outbound_domain =~ /#{inbound_regex}/
        error("double redirect: rule has destination domain #{outbound_domain} "\
              "which matches wildcard #{inbound_domain} from line #{inbound_rule[:line_num]}",
              outbound_rule[:line_num])
      end
    end
  end
end

#check_orphan_overridesObject

Check to see if any override rules were given which didn't have an associated funnel or rewrite, and raise an error if any are found.



229
230
231
232
233
234
235
236
237
238
# File 'modules/wmflib/lib/puppet/functions/wmflib/compile_redirects.rb', line 229

def check_orphan_overrides
  servers = @rules.values_at(:wildcard, :plain).flatten
  aliases = servers.map { |rule| rule[:alias] }
  overrides = @rules.values_at(:wildcard_override, :plain_override).flatten
  overrides.each do |rule|
    unless aliases.include? rule[:alias]
      error("override must have an associated funnel or rewrite", rule[:line_num])
    end
  end
end

#error(msg, line_num = @line_num) ⇒ Object



60
61
62
# File 'modules/wmflib/lib/puppet/functions/wmflib/compile_redirects.rb', line 60

def error(msg, line_num = @line_num)
  raise DomainRedirects::ParserError.new(msg, line_num)
end

#funnel(domain, dest) ⇒ Object

Process a funnel command at the current input position



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
# File 'modules/wmflib/lib/puppet/functions/wmflib/compile_redirects.rb', line 65

def funnel(domain, dest)
  dest_info = interpret_dest(dest)
  if domain.include? '*'
    wildcard_list = interpret_wildcard(domain)
    wildcard_list.each do |wildcard|
      domain_regex = wildcard[:domain_regex]
      if domain_regex.include? '('
        wildcard_dest = dest_info[:dest].gsub('*', @group_dest)
      else
        wildcard_dest = dest_info[:dest]
      end

      @rules[:wildcard] << {
        :domain       => domain,
        :domain_regex => domain_regex,
        :alias        => wildcard[:alias],
        :path_regex   => '.',
        :dest         => wildcard_dest,
        :dest_domain  => dest_info[:domain],
        :line_num     => @line_num,
      }
    end
  else
    @rules[:plain] << {
      :domain       => domain,
      :domain_regex => "=#{domain}",
      :alias        => domain,
      :path_regex   => '.',
      :dest         => dest_info[:dest],
      :dest_domain  => dest_info[:domain],
      :line_num     => @line_num,
    }
  end
end

#interpret_dest(dest) ⇒ Object

Interpret a <dest> token and return information about it. See the comment in redirects.dat for information about forms it can take.



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
# File 'modules/wmflib/lib/puppet/functions/wmflib/compile_redirects.rb', line 174

def interpret_dest(dest)
  if @web_server == 'apache'
    escape_char = '\\%'
    same_proto_redirect = '%{ENV:RW_PROTO}:'
  else
    escape_char = '%'
    same_proto_redirect = '$scheme:'
  end
  dest = dest.gsub(/[^\p{ASCII}]/) do |c|
    escape_char + c.unpack('H2' * c.bytesize).join(escape_char).upcase
  end
  case dest
  when %r{^(https?://)([^/]*)(/.*$|$)}
    domain = Regexp.last_match[2]
    path = Regexp.last_match[3]
    dest += '/' if path.empty?
  when %r{^//([^/]*)(/.*$|$)}
    dest = same_proto_redirect + dest
    domain = Regexp.last_match[1]
    path = Regexp.last_match[2]
    dest += '/' if path.empty?
  else
    error("destination must be either a protocol-relative or a fully-specified URL")
  end
  {:dest => dest, :domain => domain}
end

#interpret_wildcard(wildcard) ⇒ Object

Interpret a source domain wildcard and return information about it.



202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'modules/wmflib/lib/puppet/functions/wmflib/compile_redirects.rb', line 202

def interpret_wildcard(wildcard)
  case wildcard
  when /^\*\.([^*]*)/
    [{
      :domain_regex => '^(.+)\.' << Regexp.quote(Regexp.last_match[1]) << '$',
      :alias        => wildcard,
    }]
  when /^\*([^*]*)/
    [{
      :domain_regex => '=' + Regexp.last_match[1],
      :alias        => Regexp.last_match[1],
    }, {
      :domain_regex => '^(.+)\.' << Regexp.quote(Regexp.last_match[1]) << '$',
      :alias        => '*.' << Regexp.last_match[1],
    }]
  when /\*/
    error("invalid use of asterisk in domain pattern")
  else
    [{
      :domain_regex => '=' + wildcard,
      :alias        => wildcard,
    }]
  end
end

#override(source, dest) ⇒ Object

Process an override command at the current input position



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
# File 'modules/wmflib/lib/puppet/functions/wmflib/compile_redirects.rb', line 134

def override(source, dest)
  dest_info = interpret_dest(dest)
  domain, path = source.split('/', 2)
  error('the source of an override must include a path component') if path.nil?
  if domain.include? '*'
    wildcard_list = interpret_wildcard(domain)
    wildcard_list.each do |wildcard|
      domain_regex = wildcard[:domain_regex]
      if domain_regex.include? '('
        wildcard_dest = dest_info[:dest].gsub('*', @group_dest)
      else
        wildcard_dest = dest_info[:dest]
      end
      @rules[:wildcard_override] << {
        :domain       => domain,
        :domain_regex => domain_regex,
        :alias        => wildcard[:alias],
        :path         => Regexp.quote(path),
        :path_regex   => '^/' + Regexp.quote(path) + '$',
        :dest         => wildcard_dest,
        :dest_domain  => dest_info[:domain],
        :line_num     => @line_num,
      }
    end
  else
    @rules[:plain_override] << {
      :domain       => domain,
      :domain_regex => "=#{domain}",
      :alias        => domain,
      :path         => Regexp.quote(path),
      :path_regex   => '^/' + Regexp.quote(path) + '$',
      :dest         => dest_info[:dest],
      :dest_domain  => dest_info[:domain],
      :line_num     => @line_num,
    }
  end
end

#parseObject



37
38
39
40
41
42
43
# File 'modules/wmflib/lib/puppet/functions/wmflib/compile_redirects.rb', line 37

def parse
  StringIO.open do |buf|
    parse_to(buf)
    buf.rewind
    buf.read
  end
end

#parse_to(dest) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'modules/wmflib/lib/puppet/functions/wmflib/compile_redirects.rb', line 45

def parse_to(dest)
  @lines.each_with_index do |line, i|
    @line_num = i + 1
    args = line.gsub(/#.*/, '').strip.split
    send(*args) unless args.empty?
  end
  check_orphan_overrides
  check_loops
  if @web_server == 'apache'
    write_apache_conf(dest)
  else
    write_nginx_conf(dest)
  end
end

#rewrite(domain, dest) ⇒ Object

Process a rewrite command at the current input position



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
# File 'modules/wmflib/lib/puppet/functions/wmflib/compile_redirects.rb', line 101

def rewrite(domain, dest)
  dest_info = interpret_dest(dest)
  dest_info[:dest].sub!(%r{/$}, '')
  if domain.include? '*'
    wildcard_list = interpret_wildcard(domain)
    wildcard_list.each do |wildcard|
      domain_regex = wildcard[:domain_regex]
      wildcard_dest = dest_info[:dest]
      wildcard_dest.gsub!('*', @group_dest) if domain_regex.include? '('
      @rules[:wildcard] << {
        :domain       => domain,
        :domain_regex => domain_regex,
        :alias        => wildcard[:alias],
        :path_regex   => '^[^\x00-\x1F]*',
        :dest         => "#{wildcard_dest}#{@original_request}",
        :dest_domain  => dest_info[:domain],
        :line_num     => @line_num,
      }
    end
  else
    @rules[:plain] << {
      :domain       => domain,
      :domain_regex => "=#{domain}",
      :alias        => domain,
      :path_regex   => '^[^\x00-\x1F]*',
      :dest         => dest_info[:dest] + @original_request,
      :dest_domain  => dest_info[:domain],
      :line_num     => @line_num,
    }
  end
end

#write_apache_conf(dest) ⇒ Object

Write the collected rules to the output file.



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
# File 'modules/wmflib/lib/puppet/functions/wmflib/compile_redirects.rb', line 302

def write_apache_conf(dest)
  dest.puts <<-eos.gsub(/^ {8}/, '')
    # This file is generated automatically by Puppet
    # Do not edit it manually!

    <VirtualHost *:80>
    \tServerName redirector

  eos

  servers = @rules.values_at(:wildcard, :plain).flatten.map { |rule| rule[:alias] }
  servers.uniq.each { |server| dest.puts "\tServerAlias #{server}\n" }

  dest.puts <<-eos.gsub(/^ {8}/, "\t")

    # allow caching for redirects
    <IfModule mod_headers.c>
    \tHeader set Cache-control "s-maxage=86000, max-age=0, must-revalidate"
    </IfModule>
    <IfModule mod_expires.c>
    \tExpiresActive On
    \tExpiresByType image/gif A2592000
    \tExpiresByType image/png A2592000
    \tExpiresByType image/jpeg A2592000
    \tExpiresByType text/css A2592000
    \tExpiresByType text/javascript A2592000
    \tExpiresByType application/x-javascript A2592000
    \tExpiresByType text/html A2592000
    </IfModule>

    DocumentRoot /srv/mediawiki/docroot/default

    RewriteEngine On

    RewriteRule . - [E=RW_PROTO:%{HTTP:X-Forwarded-Proto}]
    RewriteCond %{ENV:RW_PROTO} !=https
    RewriteRule . - [E=RW_PROTO:http]
  eos

  # Write more specific rules first, followed by less specific rules
  [:plain_override, :wildcard_override, :plain, :wildcard].each do |type|
    lower_camel_name = type.to_s.gsub(/_(\w)/) { Regexp.last_match[1].upcase }
    dest.puts "\n\t# Type: #{lower_camel_name}\n"
    @rules[type].each do |rule|
      dest.puts <<-eos.gsub(/^ {12}/, "\t")
        # #{@lines[rule[:line_num] - 1]}
        RewriteCond %{HTTP_HOST} #{rule[:domain_regex]}
        RewriteRule #{rule[:path_regex]} #{rule[:dest]} [R=301,L,NE]
      eos
    end
  end

  dest.puts <<-eos.gsub(/^ {8}/, '')
    </VirtualHost>
    # vim: sts=4 sw=4 autoindent syn=apache
  eos
  dest
end

#write_nginx_conf(dest) ⇒ Object



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
# File 'modules/wmflib/lib/puppet/functions/wmflib/compile_redirects.rb', line 268

def write_nginx_conf(dest)
  dest.puts "map $host $rewrite {\n\thostnames;\n"
  [:plain, :wildcard].each do |type|
    lower_camel_name = type.to_s.gsub(/_(\w)/) { Regexp.last_match[1].upcase }
    dest.puts "\n\t# Type: #{lower_camel_name}\n"
    @rules[type].each do |rule|
      dest.puts "\t# #{@lines[rule[:line_num] - 1]}"
      if rule[:dest] =~ /#{@group_dest.sub('$', '\$')}/
        dest.puts "\t~#{rule[:domain_regex]}\t#{rule[:dest]};"
      else
        dest.puts "\t#{rule[:alias]}\t#{rule[:dest]};"
      end
    end
  end
  dest.puts "}\n"

  dest.puts "map $host$uri $override {\n\thostnames;\n"
  [:plain_override, :wildcard_override].each do |type|
    lower_camel_name = type.to_s.gsub(/_(\w)/) { Regexp.last_match[1].upcase }
    dest.puts "\n\t# Type: #{lower_camel_name}\n"
    @rules[type].each do |rule|
      dest.puts "\t# #{@lines[rule[:line_num] - 1]}"
      if rule[:dest] =~ /#{@group_dest.sub('$', '\$')}/
        dest.puts "\t~#{rule[:domain_regex]}\t#{rule[:dest]};"
      else
        dest.puts "\t#{rule[:alias]}/#{rule[:path]}\t#{rule[:dest]};"
      end
    end
  end
  dest.puts "}"
  dest
end