aboutsummaryrefslogtreecommitdiff
path: root/lib/mauve/pop3_server.rb
blob: b83e83936f957511b208ad14ff317bdb5e58ad1d (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
require 'thin'
require 'mauve/mauve_thread'
require 'digest/sha1'

module Mauve
  # 
  # API to control the web server
  #
  class Pop3Server < MauveThread

    include Singleton

    attr_reader :port, :ip
    
    def initialize
      super
      self.port = 1110
      self.ip = "0.0.0.0"
    end
   
    def port=(pr)
      raise ArgumentError, "port must be an integer between 0 and #{2**16-1}" unless pr.is_a?(Integer) and pr < 2**16 and pr > 0
      @port = pr
    end
    
    def ip=(i)
      raise ArgumentError, "ip must be a string" unless i.is_a?(String)
      #
      # Use ipaddr to sanitize our IP.
      #
      @ip = IPAddr.new(i)
    end

    def logger
      @logger ||= Log4r::Logger.new(self.class.to_s)
    end

    def main_loop
      unless @server and @server.running?
        @server = Mauve::Pop3Backend.new(@ip.to_s, @port)
        logger.info "Listening on #{@server.to_s}"
        @server.start
      end
    end

    def stop
      @server.stop if @server and @server.running?
      super
    end

    def join
      @server.stop! if @server and @server.running?
      super
    end

  end    

  class Pop3Backend < Thin::Backends::TcpServer

    def logger
      @logger ||= Log4r::Logger.new(self.class.to_s)
    end
        
    # Connect the server
    def connect
      @signature = EventMachine.start_server(@host, @port, Pop3Connection)
    end
        
  end


  class Pop3Connection < EventMachine::Connection

    attr_reader :user

    CRLF = "\r\n"

    def logger
      @logger ||= Log4r::Logger.new(self.class.to_s)
    end

    def post_init
      logger.info "New connection"
      send_data "+OK #{self.class.to_s} started"
      @state = :authorization
      @user  = nil
      @messages = []
      @level    = nil
    end

    def permitted_commands(state=@state)
     case @state
        when :authorization
          %w(QUIT USER PASS CAPA)
        when :transaction
          %w(QUIT STAT LIST RETR DELE NOOP RSET UIDL CAPA)
        when :update
          %w(QUIT)
      end
    end

    def capabilities(state=@state)
     case @state
        when :transaction
          %w(CAPA UIDL)
        when :authorization
          %w(CAPA UIDL USER) 
        else
          []
      end
    end

    def receive_data (data)
      data.split(CRLF).each do |d|
        break if error?

        if d =~ Regexp.new('\A('+self.permitted_commands.join("|")+')\b')
          case $1
            when "QUIT"
              do_process_quit data
            when "USER"
              do_process_user data
            when "PASS"
              do_process_pass data
            when "STAT"
              do_process_stat data
            when "LIST"
              do_process_list data
            when "RETR"
              do_process_retr data
            when "DELE"
              do_process_dele data
            when "NOOP"
              do_process_noop data
            when "RSET"
              do_process_rset data
            when "CAPA"
              do_process_capa data
            when "UIDL"
              do_process_uidl data
            else
              do_process_error data
          end
        else
          do_process_error data
        end
      end
    end
  
    def send_data(d)
      d += CRLF
      super unless error?
    end

    def do_process_capa(a)
      send_data (["+OK Capabilities follow:"] + self.capabilities + ["."]).join(CRLF)
    end

    def do_process_user(s)
      allowed_levels = Mauve::AlertGroup::LEVELS.collect{|l| l.to_s}

      if s =~ /\AUSER +(\w+)\+(#{allowed_levels.join("|")})/
        # Allow alerts to be shown by level.
        #
        @user  = $1
        @level = $2
        #
        send_data "+OK Only going to show #{@level} alerts."

     elsif s =~ /\AUSER +([\w]+)/
        @user =  $1

        send_data "+OK"
      else
        send_data "-ERR Username not understood."
      end
    end

    def do_process_pass(s)
      
      if @user and s =~ /\APASS +(\S+)/
        if Mauve::Authentication.authenticate(@user, $1)
          @state = :transaction
          send_data "+OK Welcome #{@user} (#{@level})." 
        else
          send_data "-ERR Authentication failed."
        end        
      else
        send_data "-ERR USER comes first."
      end
    end

    def do_process_error(a)
      send_data "-ERR Unknown comand."
    end

    def do_process_noop(a)
      send_data "+OK Thanks."
    end

    alias do_process_dele do_process_noop

    def do_process_quit(a)
      @state = :update

      send_data "+OK bye."

      close_connection_after_writing
    end

    def do_process_stat(a)
      send_data "+OK #{self.messages.length} #{self.messages.inject(0){|s,m| s+= m[1].length}}"
    end

    def do_process_list(a)
      d = []
      if a =~ /\ALIST +(\d+)\b/
        ind = $1.to_i
        if ind > 0 and ind <= self.messages.length
          d << "+OK #{ind} #{self.messages[ind-1].length}"
        else
          d << "-ERR Unknown message."
        end
      else
        d << "+OK #{self.messages.length} messages (#{self.messages.inject(0){|s,m| s+= m[1].length}} octets)."
        self.messages.each_with_index{|m,i| d << "#{i+1} #{m.length}"}
        d << "."
      end

      send_data d.join(CRLF)
    end

    def do_process_uidl(a)
      if a =~ /\AUIDL +(\d+)\b/
        ind = $1.to_i
        if ind > 0 and ind <= self.messages.length
          m = self.messages[ind-1][0].id
          send_data "+OK #{ind} #{m}"
        else
          send_data "-ERR Message not found."
        end
      else
        d = ["+OK "]
        self.messages.each_with_index{|m,i| d << "#{i+1} #{m[0].id}"}
        d << "."

        send_data d.join(CRLF)
      end
    end

    def do_process_retr(a)
      if a =~ /\ARETR +(\d+)\b/
        ind = $1.to_i
        if ind > 0 and ind <= self.messages.length
          alert_changed, msg = self.messages[ind-1]
          send_data ["+OK #{msg.length} octets", msg, "."].join(CRLF)
          note =  "#{alert_changed.update_type.capitalize} notification downloaded via POP3 by #{@user}" 
          logger.info note+" about #{alert_changed}."
          h = History.new(:alert_id => alert_changed.alert_id, :type => "notification", :event => note)
          logger.error "Unable to save history due to #{h.errors.inspect}" if !h.save
        else
          send_data "-ERR Message not found."
        end
      else
        send_data "-ERR Boo."
      end

    end

    #
    # These are the messages in the mailbox.
    #
    def messages
      if @messages.empty?
        @messages = []
        smtp = Mauve::Notifiers::Email::Default.new("TODO: why do I need to put this argument here?")
        alerts_seen = []

        AlertChanged.all(:person => self.user).each do |a|
          #
          # Not interested in alerts 
          #
          next unless @level.nil? or a.level.to_s == @level

          #
          # Only one message per alert.
          #
          next if alerts_seen.include?([a.alert_id, a.update_type])

          relevant = case a.update_type
            when "raised"
              a.alert.raised?
            when "acknowledged"
              a.alert.acknowledged?
            when "cleared"
              a.alert.cleared?
            else
              false
          end

          next unless relevant

          alerts_seen << [a.alert_id, a.update_type]

          @messages << [a, smtp.prepare_message(self.user, a.alert, [])]
        end
      end
      
      @messages
    end

  end

end