imap.rb 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. require 'net/imap'
  3. class Channel::Driver::Imap < Channel::EmailParser
  4. FETCH_METADATA_TIMEOUT = 2.minutes
  5. FETCH_MSG_TIMEOUT = 4.minutes
  6. EXPUNGE_TIMEOUT = 16.minutes
  7. DEFAULT_TIMEOUT = 45.seconds
  8. CHECK_ONLY_TIMEOUT = 8.seconds
  9. def fetchable?(_channel)
  10. true
  11. end
  12. =begin
  13. fetch emails from IMAP account
  14. instance = Channel::Driver::Imap.new
  15. result = instance.fetch(params[:inbound][:options], channel, 'verify', subject_looking_for)
  16. returns
  17. {
  18. result: 'ok',
  19. fetched: 123,
  20. notice: 'e. g. message about to big emails in mailbox',
  21. }
  22. check if connect to IMAP account is possible, return count of mails in mailbox
  23. instance = Channel::Driver::Imap.new
  24. result = instance.fetch(params[:inbound][:options], channel, 'check')
  25. returns
  26. {
  27. result: 'ok',
  28. content_messages: 123,
  29. }
  30. verify IMAP account, check if search email is in there
  31. instance = Channel::Driver::Imap.new
  32. result = instance.fetch(params[:inbound][:options], channel, 'verify', subject_looking_for)
  33. returns
  34. {
  35. result: 'ok', # 'verify not ok'
  36. }
  37. example
  38. params = {
  39. host: 'outlook.office365.com',
  40. user: 'xxx@zammad.onmicrosoft.com',
  41. password: 'xxx',
  42. keep_on_server: true,
  43. }
  44. OR
  45. params = {
  46. host: 'imap.gmail.com',
  47. user: 'xxx@gmail.com',
  48. password: 'xxx',
  49. keep_on_server: true,
  50. auth_type: 'XOAUTH2'
  51. }
  52. channel = Channel.last
  53. instance = Channel::Driver::Imap.new
  54. result = instance.fetch(params, channel, 'verify')
  55. =end
  56. def fetch(options, channel, check_type = '', verify_string = '')
  57. ssl = true
  58. ssl_verify = options.fetch(:ssl_verify, true)
  59. starttls = false
  60. port = 993
  61. keep_on_server = false
  62. folder = 'INBOX'
  63. if options[:keep_on_server] == true || options[:keep_on_server] == 'true'
  64. keep_on_server = true
  65. end
  66. case options[:ssl]
  67. when 'off'
  68. ssl = false
  69. when 'starttls'
  70. ssl = false
  71. starttls = true
  72. end
  73. port = if options.key?(:port) && options[:port].present?
  74. options[:port].to_i
  75. elsif ssl == true
  76. 993
  77. else
  78. 143
  79. end
  80. if options[:folder].present?
  81. folder = options[:folder]
  82. end
  83. Rails.logger.info "fetching imap (#{options[:host]}/#{options[:user]} port=#{port},ssl=#{ssl},starttls=#{starttls},folder=#{folder},keep_on_server=#{keep_on_server},auth_type=#{options.fetch(:auth_type, 'LOGIN')})"
  84. # on check, reduce open_timeout to have faster probing
  85. check_type_timeout = check_type == 'check' ? CHECK_ONLY_TIMEOUT : DEFAULT_TIMEOUT
  86. Certificate::ApplySSLCertificates.ensure_fresh_ssl_context if ssl || starttls
  87. timeout(check_type_timeout) do
  88. ssl_settings = false
  89. ssl_settings = (ssl_verify ? true : { verify_mode: OpenSSL::SSL::VERIFY_NONE }) if ssl
  90. @imap = ::Net::IMAP.new(options[:host], port: port, ssl: ssl_settings)
  91. if starttls
  92. @imap.starttls(nil, ssl_verify)
  93. end
  94. end
  95. timeout(check_type_timeout) do
  96. if options[:auth_type].present?
  97. @imap.authenticate(options[:auth_type], options[:user], options[:password])
  98. else
  99. @imap.login(options[:user], options[:password].dup&.force_encoding('ascii-8bit'))
  100. end
  101. end
  102. timeout(check_type_timeout) do
  103. # select folder
  104. @imap.select(folder)
  105. end
  106. message_ids = timeout(6.minutes) do
  107. if keep_on_server && check_type != 'check' && check_type != 'verify'
  108. fetch_unread_message_ids
  109. else
  110. fetch_all_message_ids
  111. end
  112. end
  113. # check mode only
  114. if check_type == 'check'
  115. Rails.logger.info 'check only mode, fetch no emails'
  116. content_max_check = 2
  117. content_messages = 0
  118. # check messages
  119. message_ids.each do |message_id|
  120. message_meta = nil
  121. timeout(1.minute) do
  122. message_meta = @imap.fetch(message_id, ['RFC822.HEADER'])[0]
  123. end
  124. # check how many content messages we have, for notice used
  125. headers = self.class.extract_rfc822_headers(message_meta)
  126. next if messages_is_verify_message?(headers)
  127. next if messages_is_ignore_message?(headers)
  128. content_messages += 1
  129. break if content_max_check < content_messages
  130. end
  131. if content_messages >= content_max_check
  132. content_messages = message_ids.count
  133. end
  134. archive_possible = false
  135. archive_check = 0
  136. archive_max_check = 500
  137. archive_days_range = 14
  138. archive_week_range = archive_days_range / 7
  139. message_ids.reverse_each do |message_id|
  140. message_meta = nil
  141. timeout(1.minute) do
  142. message_meta = @imap.fetch(message_id, ['RFC822.HEADER'])[0]
  143. end
  144. headers = self.class.extract_rfc822_headers(message_meta)
  145. next if messages_is_verify_message?(headers)
  146. next if messages_is_ignore_message?(headers)
  147. next if headers['Date'].blank?
  148. archive_check += 1
  149. break if archive_check >= archive_max_check
  150. begin
  151. date = Time.zone.parse(headers['Date'])
  152. rescue => e
  153. Rails.logger.error e
  154. next
  155. end
  156. break if date >= Time.zone.now - archive_days_range.days
  157. archive_possible = true
  158. break
  159. end
  160. disconnect
  161. return {
  162. result: 'ok',
  163. content_messages: content_messages,
  164. archive_possible: archive_possible,
  165. archive_week_range: archive_week_range,
  166. }
  167. end
  168. # reverse message order to increase performance
  169. if check_type == 'verify'
  170. Rails.logger.info "verify mode, fetch no emails #{verify_string}"
  171. # check for verify message
  172. message_ids.reverse_each do |message_id|
  173. message_meta = nil
  174. timeout(FETCH_METADATA_TIMEOUT) do
  175. message_meta = @imap.fetch(message_id, ['RFC822.HEADER'])[0]
  176. end
  177. # check if verify message exists
  178. headers = self.class.extract_rfc822_headers(message_meta)
  179. subject = headers['Subject']
  180. next if !subject
  181. next if !subject.match?(%r{#{verify_string}})
  182. Rails.logger.info " - verify email #{verify_string} found"
  183. timeout(600) do
  184. @imap.store(message_id, '+FLAGS', [:Deleted])
  185. @imap.expunge
  186. end
  187. disconnect
  188. return {
  189. result: 'ok',
  190. }
  191. end
  192. disconnect
  193. return {
  194. result: 'verify not ok',
  195. }
  196. end
  197. # fetch regular messages
  198. count_all = message_ids.count
  199. count = 0
  200. count_fetched = 0
  201. count_max = 5000
  202. too_large_messages = []
  203. active_check_interval = 20
  204. result = 'ok'
  205. notice = ''
  206. message_ids.each do |message_id|
  207. count += 1
  208. break if (count % active_check_interval).zero? && channel_has_changed?(channel)
  209. break if max_process_count_has_reached?(channel, count, count_max)
  210. Rails.logger.info " - message #{count}/#{count_all}"
  211. message_meta = nil
  212. timeout(FETCH_METADATA_TIMEOUT) do
  213. message_meta = @imap.fetch(message_id, ['RFC822.SIZE', 'FLAGS', 'INTERNALDATE', 'RFC822.HEADER'])[0]
  214. rescue Net::IMAP::ResponseParseError => e
  215. raise if e.message.exclude?('unknown token')
  216. result = 'error'
  217. notice += <<~NOTICE
  218. One of your incoming emails could not be imported (#{e.message}).
  219. Please remove it from your inbox directly
  220. to prevent Zammad from trying to import it again.
  221. NOTICE
  222. Rails.logger.error "Net::IMAP failed to parse message #{message_id}: #{e.message} (#{e.class})"
  223. Rails.logger.error '(See https://github.com/zammad/zammad/issues/2754 for more details)'
  224. end
  225. next if message_meta.nil?
  226. # ignore verify messages
  227. next if !messages_is_too_old_verify?(message_meta, count, count_all)
  228. # ignore deleted messages
  229. next if deleted?(message_meta, count, count_all)
  230. # ignore already imported
  231. next if already_imported?(message_id, message_meta, count, count_all, keep_on_server, channel)
  232. # delete email from server after article was created
  233. msg = nil
  234. begin
  235. timeout(FETCH_MSG_TIMEOUT) do
  236. # https://github.com/zammad/zammad/issues/4589
  237. key = options['host'] == 'imap.mail.me.com' ? 'BODY[]' : 'RFC822'
  238. msg = @imap.fetch(message_id, key)[0].attr[key]
  239. end
  240. rescue Timeout::Error => e
  241. Rails.logger.error "Unable to fetch email from #{count}/#{count_all} from server (#{options[:host]}/#{options[:user]}): #{e.inspect}"
  242. raise e
  243. end
  244. next if !msg
  245. # do not process too big messages, instead download & send postmaster reply
  246. too_large_info = too_large?(message_meta)
  247. if too_large_info
  248. if Setting.get('postmaster_send_reject_if_mail_too_large') == true
  249. info = " - download message #{count}/#{count_all} - ignore message because it's too large (is:#{too_large_info[0]} MB/max:#{too_large_info[1]} MB)"
  250. Rails.logger.info info
  251. notice += "#{info}\n"
  252. process_oversized_mail(channel, msg)
  253. else
  254. info = " - ignore message #{count}/#{count_all} - because message is too large (is:#{too_large_info[0]} MB/max:#{too_large_info[1]} MB)"
  255. Rails.logger.info info
  256. notice += "#{info}\n"
  257. too_large_messages.push info
  258. next
  259. end
  260. else
  261. process(channel, msg, false)
  262. end
  263. begin
  264. timeout(FETCH_MSG_TIMEOUT) do
  265. if keep_on_server
  266. @imap.store(message_id, '+FLAGS', [:Seen])
  267. else
  268. @imap.store(message_id, '+FLAGS', [:Deleted])
  269. end
  270. end
  271. rescue Timeout::Error => e
  272. Rails.logger.error "Unable to set +FLAGS for email #{count}/#{count_all} on server (#{options[:host]}/#{options[:user]}): #{e.inspect}"
  273. raise e
  274. end
  275. count_fetched += 1
  276. end
  277. if !keep_on_server
  278. begin
  279. timeout(EXPUNGE_TIMEOUT) do
  280. @imap.expunge
  281. end
  282. rescue Timeout::Error => e
  283. Rails.logger.error "Unable to expunge server (#{options[:host]}/#{options[:user]}): #{e.inspect}"
  284. raise e
  285. end
  286. end
  287. disconnect
  288. if count.zero?
  289. Rails.logger.info ' - no message'
  290. end
  291. if too_large_messages.present?
  292. raise too_large_messages.join("\n")
  293. end
  294. {
  295. result: result,
  296. fetched: count_fetched,
  297. notice: notice,
  298. }
  299. end
  300. def fetch_all_message_ids
  301. fetch_message_ids %w[ALL]
  302. end
  303. def fetch_unread_message_ids
  304. fetch_message_ids %w[NOT SEEN]
  305. rescue
  306. fetch_message_ids %w[UNSEEN]
  307. end
  308. def fetch_message_ids(filter)
  309. @imap.sort(['DATE'], filter, 'US-ASCII')
  310. rescue
  311. @imap.search(filter)
  312. end
  313. def disconnect
  314. return if !@imap
  315. timeout(1.minute) do
  316. @imap.disconnect
  317. end
  318. end
  319. =begin
  320. Channel::Driver::Imap.streamable?
  321. returns
  322. true|false
  323. =end
  324. def self.streamable?
  325. false
  326. end
  327. # Parses RFC822 header
  328. # @param [String] RFC822 header text blob
  329. # @return [Hash<String=>String>]
  330. def self.parse_rfc822_headers(string)
  331. array = string
  332. .gsub("\r\n\t", ' ') # Some servers (e.g. microsoft365) may put attribute value on a separate line and tab it
  333. .lines(chomp: true)
  334. .map { |line| line.split(%r{:\s*}, 2).map(&:strip) }
  335. array.each { |elem| elem.append(nil) if elem.one? }
  336. Hash[*array.flatten]
  337. end
  338. # Parses RFC822 header
  339. # @param [Net::IMAP::FetchData] fetched message
  340. # @return [Hash<String=>String>]
  341. def self.extract_rfc822_headers(message_meta)
  342. blob = message_meta&.attr&.dig 'RFC822.HEADER'
  343. return if !blob
  344. parse_rfc822_headers blob
  345. end
  346. private
  347. def messages_is_too_old_verify?(message_meta, count, count_all)
  348. headers = self.class.extract_rfc822_headers(message_meta)
  349. return true if !messages_is_verify_message?(headers)
  350. return true if headers['X-Zammad-Verify-Time'].blank?
  351. begin
  352. verify_time = Time.zone.parse(headers['X-Zammad-Verify-Time'])
  353. rescue => e
  354. Rails.logger.error e
  355. return true
  356. end
  357. return true if verify_time < 30.minutes.ago
  358. Rails.logger.info " - ignore message #{count}/#{count_all} - because message has a verify message"
  359. false
  360. end
  361. def messages_is_verify_message?(headers)
  362. return true if headers['X-Zammad-Verify'] == 'true'
  363. false
  364. end
  365. def messages_is_ignore_message?(headers)
  366. return true if headers['X-Zammad-Ignore'] == 'true'
  367. false
  368. end
  369. =begin
  370. check if email is already impoted
  371. Channel::Driver::IMAP.already_imported?(message_id, message_meta, count, count_all, keep_on_server, channel)
  372. returns
  373. true|false
  374. =end
  375. # rubocop:disable Metrics/ParameterLists
  376. def already_imported?(message_id, message_meta, count, count_all, keep_on_server, channel)
  377. # rubocop:enable Metrics/ParameterLists
  378. return false if !keep_on_server
  379. headers = self.class.extract_rfc822_headers(message_meta)
  380. retrurn false if !headers
  381. local_message_id = headers['Message-ID']
  382. return false if local_message_id.blank?
  383. local_message_id_md5 = Digest::MD5.hexdigest(local_message_id)
  384. article = Ticket::Article.where(message_id_md5: local_message_id_md5).reorder('created_at DESC, id DESC').limit(1).first
  385. return false if !article
  386. # verify if message is already imported via same channel, if not, import it again
  387. ticket = article.ticket
  388. return false if ticket&.preferences && ticket.preferences[:channel_id].present? && channel.present? && ticket.preferences[:channel_id] != channel[:id]
  389. timeout(1.minute) do
  390. @imap.store(message_id, '+FLAGS', [:Seen])
  391. end
  392. Rails.logger.info " - ignore message #{count}/#{count_all} - because message message id already imported"
  393. true
  394. end
  395. =begin
  396. check if email is already marked as deleted
  397. Channel::Driver::IMAP.deleted?(message_meta, count, count_all)
  398. returns
  399. true|false
  400. =end
  401. def deleted?(message_meta, count, count_all)
  402. return false if message_meta.attr['FLAGS'].exclude?(:Deleted)
  403. Rails.logger.info " - ignore message #{count}/#{count_all} - because message has already delete flag"
  404. true
  405. end
  406. =begin
  407. check if email is to big
  408. Channel::Driver::IMAP.too_large?(message_meta, count, count_all)
  409. returns
  410. true|false
  411. =end
  412. def too_large?(message_meta)
  413. max_message_size = Setting.get('postmaster_max_size').to_f
  414. real_message_size = message_meta.attr['RFC822.SIZE'].to_f / 1024 / 1024
  415. if real_message_size > max_message_size
  416. return [real_message_size, max_message_size]
  417. end
  418. false
  419. end
  420. =begin
  421. check if channel config has changed
  422. Channel::Driver::IMAP.channel_has_changed?(channel)
  423. returns
  424. true|false
  425. =end
  426. def channel_has_changed?(channel)
  427. current_channel = Channel.find_by(id: channel.id)
  428. if !current_channel
  429. Rails.logger.info "Channel with id #{channel.id} is deleted in the meantime. Stop fetching."
  430. return true
  431. end
  432. return false if channel.updated_at == current_channel.updated_at
  433. Rails.logger.info "Channel with id #{channel.id} has changed. Stop fetching."
  434. true
  435. end
  436. =begin
  437. check if maximal fetching email count has reached
  438. Channel::Driver::IMAP.max_process_count_has_reached?(channel, count, count_max)
  439. returns
  440. true|false
  441. =end
  442. def max_process_count_has_reached?(channel, count, count_max)
  443. return false if count < count_max
  444. Rails.logger.info "Maximal fetched emails (#{count_max}) reached for this interval for Channel with id #{channel.id}."
  445. true
  446. end
  447. def timeout(seconds, &)
  448. Timeout.timeout(seconds, &)
  449. end
  450. end