Class: Mocksmtpd

Inherits:
Object
  • Object
show all
Includes:
ERB::Util
Defined in:
lib/mocksmtpd.rb

Constant Summary collapse

VERSION =
'0.0.3'
TEMPLATE_DIR =
Pathname.new(File.dirname(__FILE__)) + "../templates"

Instance Method Summary collapse

Constructor Details

#initialize(argv) ⇒ Mocksmtpd

Returns a new instance of Mocksmtpd.



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
# File 'lib/mocksmtpd.rb', line 16

def initialize(argv)
  @opt = OptionParser.new
  @opt.banner = "Usage: #$0 [options] [start|stop|init PATH]"
  @opt.on("-f FILE", "--config=FILE", "Specify mocksmtpd.conf") do |v|
    @conf_file = v
  end

  @opt.on("--version", "Show version string `#{VERSION}'") do
    puts VERSION
    exit
  end

  @opt.parse!(argv)

  if argv.empty?
    @command = "console"
  else
    @command = argv.shift
    commands = %w(start stop init)
    unless commands.include? @command
      opterror "No such command: #{@command}"
      exit 1
    end
  end

  if @command == "init"
    @init_dir = argv.shift || "mocksmtpd"
    if test(?e, @init_dir)
      opterror("Init path already exists: #{@init_dir}")
      exit 1
    end
  end
end

Instance Method Details

#consoleObject



153
154
155
156
157
158
# File 'lib/mocksmtpd.rb', line 153

def console
  load_conf
  @logger = create_logger
  @daemon = false
  smtpd
end

#create_logger(file = nil) ⇒ Object



135
136
137
138
139
140
141
142
143
144
# File 'lib/mocksmtpd.rb', line 135

def create_logger(file = nil)
  file = file.to_s.strip
  file = nil if file.empty?
  lvstr = @conf[:LogLevel].to_s.strip
  lvstr = "INFO" unless %w{FATAL ERROR WARN INFO DEBUG}.include?(lvstr)
  level = WEBrick::BasicLog.const_get(lvstr)
  logger = WEBrick::Log.new(file, level)
  logger.debug("Logger initialized")
  return logger
end

#create_pid_fileObject



160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/mocksmtpd.rb', line 160

def create_pid_file
  if @pidfile.exist?
    pid = @pidfile.read
    @logger.warn("pid file already exists: pid=#{pid}")
    exit 1
  end
  pid = Process.pid
  open(@pidfile, "w") do |io|
    io << pid
  end
  @logger.debug("pid file saved: pid=#{pid} file=#{@pidfile}")
end

#delete_pid_fileObject



173
174
175
176
# File 'lib/mocksmtpd.rb', line 173

def delete_pid_file
  File.delete(@pidfile)
  @logger.debug("pid file deleted: file=#{@pidfile}")
end

#initObject



103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/mocksmtpd.rb', line 103

def init
  Dir.mkdir(@init_dir)
  puts "Created: #{@init_dir}/"
  path = Pathname.new(@init_dir)
  Dir.mkdir(path + "inbox")
  puts "Created: #{path + 'inbox'}/"
  Dir.mkdir(path + "log")
  puts "Created: #{path + 'log'}/"

  open(path + "mocksmtpd.conf", "w") do |io|
    io << template("mocksmtpd.conf").result(binding)
  end
  puts "Created: #{path + 'mocksmtpd.conf'}"
end

#init_permissionObject



178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/mocksmtpd.rb', line 178

def init_permission
  File.umask(@conf[:Umask]) unless @conf[:Umask].nil?
  stat = File::Stat.new(@conf_file)
  uid = stat.uid
  gid = stat.gid
  begin
    Process.egid = gid
    Process.euid = uid
  rescue NotImplementedError => e
    @logger.debug("Process.euid= not implemented.")
  rescue Errno::EPERM => e
    @logger.warn("could not change euid/egid. #{e}")
  end
end

#load_confObject



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/mocksmtpd.rb', line 55

def load_conf
  @conf_file = Pathname.new(@conf_file || "./mocksmtpd.conf")
  unless @conf_file.exist? && @conf_file.readable?
    opterror "Can't load config file: #{@conf_file}"
    exit 1
  end
  @conf_file = @conf_file.realpath

  @conf = {}
  YAML.load_file(@conf_file).each do |k,v|
    @conf[k.intern] = v
  end

  @inbox = resolve_conf_path(@conf[:InboxDir])
  @logfile = resolve_conf_path(@conf[:LogFile])
  @pidfile = resolve_conf_path(@conf[:PidFile])

  @templates = load_templates
end

#load_templatesObject



89
90
91
92
93
94
95
# File 'lib/mocksmtpd.rb', line 89

def load_templates
  result = {}
  result[:mail] = template("html/mail")
  result[:index] = template("html/index")
  result[:index_entry] = template("html/index_entry")
  return result
end

#opterror(msg) ⇒ Object



50
51
52
53
# File 'lib/mocksmtpd.rb', line 50

def opterror(msg)
  puts("Error: #{msg}")
  puts(@opt.help)
end

#parse_mail(src, sender, recipients) ⇒ Object



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
# File 'lib/mocksmtpd.rb', line 247

def parse_mail(src, sender, recipients)
  src = NKF.nkf("-wm", src)
  subject = src.match(/^Subject:\s*(.+)/i).to_a[1].to_s.strip
  date = src.match(/^Date:\s*(.+)/i).to_a[1].to_s.strip

  src = ERB::Util.h(src)
  src = src.gsub(%r{https?://[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]+},'<a href="\0">\0</a>')
  src = src.gsub(/(?:\r\n|\r|\n)/, "<br />\n")

  if date.empty?
    date = Time.now
  else
    date = Time.parse(date)
  end

  mail = {
    :source => src,
    :sender => sender,
    :recipients => recipients,
    :subject => subject,
    :date => date,
  }

  format = "%Y%m%d%H%M%S"
  fname = date.strftime(format) + ".html"
  while @inbox.join(fname).exist?
    date += 1
    fname = date.strftime(format) + ".html"
  end

  mail[:file] = fname
  mail[:path] = @inbox.join(fname)

  return mail
end

#recieve_mail(src, sender, recipients) ⇒ Object



238
239
240
241
242
243
244
245
# File 'lib/mocksmtpd.rb', line 238

def recieve_mail(src, sender, recipients)
  @logger.info "mail recieved from #{sender}"

  mail = parse_mail(src, sender, recipients)

  save_mail(mail)
  save_index(mail)
end

#resolve_conf_path(path) ⇒ Object



75
76
77
78
79
80
81
82
83
# File 'lib/mocksmtpd.rb', line 75

def resolve_conf_path(path)
  result = nil
  if path[0] == ?/
    result = Pathname.new(path)
  else
    result = @conf_file.parent + path
  end
  return result.cleanpath
end

#runObject



85
86
87
# File 'lib/mocksmtpd.rb', line 85

def run
  send(@command)
end

#save_index(mail) ⇒ Object



290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# File 'lib/mocksmtpd.rb', line 290

def save_index(mail)
  path = @inbox + "index.html"
  unless File.exist?(path)
    open(path, "w") do |io|
      io << @templates[:index].result(binding)
    end
  end

  htmlsrc = File.read(path)
  add = @templates[:index_entry].result(binding)

  htmlsrc.sub!(/<!-- ADD -->/, add)
  open(path, "w") do |io|
    io << htmlsrc
  end
  @logger.debug("index saved: #{path}")
end

#save_mail(mail) ⇒ Object



283
284
285
286
287
288
# File 'lib/mocksmtpd.rb', line 283

def save_mail(mail)
  open(mail[:path], "w") do |io|
    io << @templates[:mail].result(binding)
  end
  @logger.debug("mail saved: #{mail[:path]}")
end

#smtpdObject



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
# File 'lib/mocksmtpd.rb', line 193

def smtpd
  start_cb = Proc.new do
    @logger.info("Inbox: #{@inbox}")
    if @daemon
      @logger.debug("LogFile: #{@logfile}")
      @logger.debug("PidFile: #{@pidfile}")
    end

    begin
      init_permission
      create_pid_file if @daemon
    rescue => e
      @logger.error("Start: #{e}")
      raise e
    end
  end

  stop_cb = Proc.new do
    begin
      delete_pid_file if @daemon
    rescue => e
      @logger.error("Stop: #{e}")
      raise e
    end
  end

  data_cb = Proc.new do |src, sender, recipients|
    recieve_mail(src, sender, recipients)
  end

  @conf[:ServerType] = @daemon ? WEBrick::Daemon : nil
  @conf[:Logger] = @logger
  @conf[:StartCallback] = start_cb
  @conf[:StopCallback] = stop_cb
  @conf[:DataHook] = data_cb

  server = SMTPServer.new(@conf)

  [:INT, :TERM].each do |signal|
    Signal.trap(signal) { server.shutdown }
  end

  server.start
end

#startObject



146
147
148
149
150
151
# File 'lib/mocksmtpd.rb', line 146

def start
  load_conf
  @logger = create_logger(@logfile)
  @daemon = true
  smtpd
end

#stopObject



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/mocksmtpd.rb', line 118

def stop
  load_conf
  unless @pidfile.exist?
    puts "ERROR: pid file does not exist: #{@pidfile}"
    exit 1
  end
  unless @pidfile.readable?
    puts "ERROR: Can't read pid file: #{@pidfile}"
    exit 1
  end

  pid = File.read(@pidfile)
  print "Stopping #{pid}..."
  system "kill -TERM #{pid}"
  puts "done"
end

#template(name) ⇒ Object



97
98
99
100
101
# File 'lib/mocksmtpd.rb', line 97

def template(name)
  path = TEMPLATE_DIR + "#{name}.erb"
  src = path.read
  return ERB.new(src, nil, "%-")
end