imap.rb 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. # Copyright (C) 2012-2024 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. keep_on_server = false
  61. folder = 'INBOX'
  62. if options[:keep_on_server] == true || options[:keep_on_server] == 'true'
  63. keep_on_server = true
  64. end
  65. case options[:ssl]
  66. when 'off'
  67. ssl = false
  68. when 'starttls'
  69. ssl = false
  70. starttls = true
  71. end
  72. port = if options.key?(:port) && options[:port].present?
  73. options[:port].to_i
  74. elsif ssl == true
  75. 993
  76. else
  77. 143
  78. end
  79. if options[:folder].present?
  80. folder = options[:folder]
  81. end
  82. 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')})"
  83. # on check, reduce open_timeout to have faster probing
  84. check_type_timeout = check_type == 'check' ? CHECK_ONLY_TIMEOUT : DEFAULT_TIMEOUT
  85. Certificate::ApplySSLCertificates.ensure_fresh_ssl_context if ssl || starttls
  86. timeout(check_type_timeout) do
  87. ssl_settings = false
  88. ssl_settings = (ssl_verify ? true : { verify_mode: OpenSSL::SSL::VERIFY_NONE }) if ssl
  89. @imap = ::Net::IMAP.new(options[:host], port: port, ssl: ssl_settings)
  90. if starttls
  91. @imap.starttls(verify_mode: ssl_verify ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE)
  92. end
  93. end
  94. timeout(check_type_timeout) do
  95. if options[:auth_type].present?
  96. @imap.authenticate(options[:auth_type], options[:user], options[:password])
  97. else
  98. @imap.login(options[:user], options[:password].dup&.force_encoding('ascii-8bit'))
  99. end
  100. end
  101. timeout(check_type_timeout) do
  102. # select folder
  103. @imap.select(folder)
  104. end
  105. message_ids_result = timeout(6.minutes) do
  106. if keep_on_server && check_type != 'check' && check_type != 'verify'
  107. fetch_unread_message_ids
  108. else
  109. fetch_all_message_ids
  110. end
  111. end
  112. message_ids = message_ids_result[:result]
  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 || message_ids_result[:is_fallback]
  135. archive_possible_is_fallback = false || message_ids_result[:is_fallback]
  136. archive_check = 0
  137. archive_max_check = 500
  138. archive_days_range = 14
  139. archive_week_range = archive_days_range / 7
  140. # use .each only if ordered response is ascending (from older to newer)
  141. message_ids_iterator = message_ids.each
  142. # since the correct loop order could improve performance, we should check even for less than 500 available messages
  143. # starting with 5 messages, since we need 2 additional fetch requests to find the used order and it would not make sense with less messages
  144. if !message_ids_result[:is_fallback] && content_messages > 4
  145. message_0_meta = nil
  146. message_1_meta = nil
  147. timeout(1.minute) do
  148. message_0_meta = @imap.fetch(message_ids[0], ['RFC822.HEADER'])[0]
  149. message_1_meta = @imap.fetch(message_ids[1], ['RFC822.HEADER'])[0]
  150. end
  151. headers0 = self.class.extract_rfc822_headers(message_0_meta)
  152. headers1 = self.class.extract_rfc822_headers(message_1_meta)
  153. if headers0['Date'].present? && headers1['Date'].present?
  154. begin
  155. date0 = Time.zone.parse(headers0['Date'])
  156. date1 = Time.zone.parse(headers1['Date'])
  157. # change iterator to .reverse_each if order of the 2 probe messages is descending (from newer to older)
  158. message_ids_iterator = message_ids.reverse_each if date0 > date1
  159. rescue => e # rubocop:disable Metrics/BlockNesting
  160. # no easy order decision possible due to a date parsing issue, continue with default iterator
  161. end
  162. end
  163. end
  164. message_ids_iterator.each do |message_id|
  165. message_meta = nil
  166. timeout(1.minute) do
  167. message_meta = @imap.fetch(message_id, ['RFC822.HEADER'])[0]
  168. end
  169. headers = self.class.extract_rfc822_headers(message_meta)
  170. next if messages_is_verify_message?(headers)
  171. next if messages_is_ignore_message?(headers)
  172. next if headers['Date'].blank?
  173. archive_check += 1
  174. break if archive_check >= archive_max_check
  175. begin
  176. date = Time.zone.parse(headers['Date'])
  177. rescue => e
  178. Rails.logger.error e
  179. next
  180. end
  181. break if date >= Time.zone.now - archive_days_range.days
  182. archive_possible = true
  183. # even if it was fallback before, we just found a real old mail, so it's not fallback anymore
  184. archive_possible_is_fallback = false
  185. break
  186. end
  187. disconnect
  188. return {
  189. result: 'ok',
  190. content_messages: content_messages,
  191. archive_possible: archive_possible,
  192. archive_possible_is_fallback: archive_possible_is_fallback,
  193. archive_week_range: archive_week_range,
  194. }
  195. end
  196. # reverse message order to increase performance
  197. if check_type == 'verify'
  198. Rails.logger.info "verify mode, fetch no emails #{verify_string}"
  199. # check for verify message
  200. message_ids.reverse_each do |message_id|
  201. message_meta = nil
  202. timeout(FETCH_METADATA_TIMEOUT) do
  203. message_meta = @imap.fetch(message_id, ['RFC822.HEADER'])[0]
  204. end
  205. # check if verify message exists
  206. headers = self.class.extract_rfc822_headers(message_meta)
  207. subject = headers['Subject']
  208. next if !subject
  209. next if !subject.match?(%r{#{verify_string}})
  210. Rails.logger.info " - verify email #{verify_string} found"
  211. timeout(600) do
  212. @imap.store(message_id, '+FLAGS', [:Deleted])
  213. @imap.expunge
  214. end
  215. disconnect
  216. return {
  217. result: 'ok',
  218. }
  219. end
  220. disconnect
  221. return {
  222. result: 'verify not ok',
  223. }
  224. end
  225. # fetch regular messages
  226. count_all = message_ids.count
  227. count = 0
  228. count_fetched = 0
  229. count_max = 5000
  230. too_large_messages = []
  231. active_check_interval = 20
  232. result = 'ok'
  233. notice = ''
  234. message_ids.each do |message_id|
  235. count += 1
  236. break if (count % active_check_interval).zero? && channel_has_changed?(channel)
  237. break if max_process_count_has_reached?(channel, count, count_max)
  238. Rails.logger.info " - message #{count}/#{count_all}"
  239. message_meta = nil
  240. timeout(FETCH_METADATA_TIMEOUT) do
  241. message_meta = @imap.fetch(message_id, ['RFC822.SIZE', 'FLAGS', 'INTERNALDATE', 'RFC822.HEADER'])[0]
  242. rescue Net::IMAP::ResponseParseError => e
  243. raise if e.message.exclude?('unknown token')
  244. result = 'error'
  245. notice += <<~NOTICE
  246. One of your incoming emails could not be imported (#{e.message}).
  247. Please remove it from your inbox directly
  248. to prevent Zammad from trying to import it again.
  249. NOTICE
  250. Rails.logger.error "Net::IMAP failed to parse message #{message_id}: #{e.message} (#{e.class})"
  251. Rails.logger.error '(See https://github.com/zammad/zammad/issues/2754 for more details)'
  252. end
  253. next if message_meta.nil?
  254. # ignore verify messages
  255. next if !messages_is_too_old_verify?(message_meta, count, count_all)
  256. # ignore deleted messages
  257. next if deleted?(message_meta, count, count_all)
  258. # ignore already imported
  259. next if already_imported?(message_id, message_meta, count, count_all, keep_on_server, channel)
  260. # delete email from server after article was created
  261. msg = nil
  262. begin
  263. timeout(FETCH_MSG_TIMEOUT) do
  264. key = fetch_message_body_key(options)
  265. msg = @imap.fetch(message_id, key)[0].attr[key]
  266. end
  267. rescue Timeout::Error => e
  268. Rails.logger.error "Unable to fetch email from #{count}/#{count_all} from server (#{options[:host]}/#{options[:user]}): #{e.inspect}"
  269. raise e
  270. end
  271. next if !msg
  272. # do not process too big messages, instead download & send postmaster reply
  273. too_large_info = too_large?(message_meta)
  274. if too_large_info
  275. if Setting.get('postmaster_send_reject_if_mail_too_large') == true
  276. 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)"
  277. Rails.logger.info info
  278. notice += "#{info}\n"
  279. process_oversized_mail(channel, msg)
  280. else
  281. info = " - ignore message #{count}/#{count_all} - because message is too large (is:#{too_large_info[0]} MB/max:#{too_large_info[1]} MB)"
  282. Rails.logger.info info
  283. notice += "#{info}\n"
  284. too_large_messages.push info
  285. next
  286. end
  287. else
  288. process(channel, msg, false)
  289. end
  290. begin
  291. timeout(FETCH_MSG_TIMEOUT) do
  292. if keep_on_server
  293. @imap.store(message_id, '+FLAGS', [:Seen])
  294. else
  295. @imap.store(message_id, '+FLAGS', [:Deleted])
  296. end
  297. end
  298. rescue Timeout::Error => e
  299. Rails.logger.error "Unable to set +FLAGS for email #{count}/#{count_all} on server (#{options[:host]}/#{options[:user]}): #{e.inspect}"
  300. raise e
  301. end
  302. count_fetched += 1
  303. end
  304. if !keep_on_server
  305. begin
  306. timeout(EXPUNGE_TIMEOUT) do
  307. @imap.expunge
  308. end
  309. rescue Timeout::Error => e
  310. Rails.logger.error "Unable to expunge server (#{options[:host]}/#{options[:user]}): #{e.inspect}"
  311. raise e
  312. end
  313. end
  314. disconnect
  315. if count.zero?
  316. Rails.logger.info ' - no message'
  317. end
  318. if too_large_messages.present?
  319. raise too_large_messages.join("\n")
  320. end
  321. {
  322. result: result,
  323. fetched: count_fetched,
  324. notice: notice,
  325. }
  326. end
  327. def fetch_all_message_ids
  328. fetch_message_ids %w[ALL]
  329. end
  330. def fetch_unread_message_ids
  331. fetch_message_ids %w[NOT SEEN]
  332. rescue
  333. fetch_message_ids %w[UNSEEN]
  334. end
  335. def fetch_message_ids(filter)
  336. raise if @imap.capabilities.exclude?('SORT')
  337. {
  338. result: @imap.sort(['DATE'], filter, 'US-ASCII'),
  339. is_fallback: false
  340. }
  341. rescue
  342. {
  343. result: @imap.search(filter),
  344. is_fallback: true # indicates that we can not use a result ordered by date
  345. }
  346. end
  347. def fetch_message_body_key(options)
  348. # https://github.com/zammad/zammad/issues/4589
  349. options['host'] == 'imap.mail.me.com' ? 'BODY[]' : 'RFC822'
  350. end
  351. def disconnect
  352. return if !@imap
  353. timeout(1.minute) do
  354. @imap.disconnect
  355. end
  356. end
  357. =begin
  358. Channel::Driver::Imap.streamable?
  359. returns
  360. true|false
  361. =end
  362. def self.streamable?
  363. false
  364. end
  365. # Parses RFC822 header
  366. # @param [String] RFC822 header text blob
  367. # @return [Hash<String=>String>]
  368. def self.parse_rfc822_headers(string)
  369. array = string
  370. .gsub("\r\n\t", ' ') # Some servers (e.g. microsoft365) may put attribute value on a separate line and tab it
  371. .lines(chomp: true)
  372. .map { |line| line.split(%r{:\s*}, 2).map(&:strip) }
  373. array.each { |elem| elem.append(nil) if elem.one? }
  374. Hash[*array.flatten]
  375. end
  376. # Parses RFC822 header
  377. # @param [Net::IMAP::FetchData] fetched message
  378. # @return [Hash<String=>String>]
  379. def self.extract_rfc822_headers(message_meta)
  380. blob = message_meta&.attr&.dig 'RFC822.HEADER'
  381. return if !blob
  382. parse_rfc822_headers blob
  383. end
  384. private
  385. def messages_is_too_old_verify?(message_meta, count, count_all)
  386. headers = self.class.extract_rfc822_headers(message_meta)
  387. return true if !messages_is_verify_message?(headers)
  388. return true if headers['X-Zammad-Verify-Time'].blank?
  389. begin
  390. verify_time = Time.zone.parse(headers['X-Zammad-Verify-Time'])
  391. rescue => e
  392. Rails.logger.error e
  393. return true
  394. end
  395. return true if verify_time < 30.minutes.ago
  396. Rails.logger.info " - ignore message #{count}/#{count_all} - because message has a verify message"
  397. false
  398. end
  399. def messages_is_verify_message?(headers)
  400. return true if headers['X-Zammad-Verify'] == 'true'
  401. false
  402. end
  403. def messages_is_ignore_message?(headers)
  404. return true if headers['X-Zammad-Ignore'] == 'true'
  405. false
  406. end
  407. =begin
  408. check if email is already impoted
  409. Channel::Driver::IMAP.already_imported?(message_id, message_meta, count, count_all, keep_on_server, channel)
  410. returns
  411. true|false
  412. =end
  413. # rubocop:disable Metrics/ParameterLists
  414. def already_imported?(message_id, message_meta, count, count_all, keep_on_server, channel)
  415. # rubocop:enable Metrics/ParameterLists
  416. return false if !keep_on_server
  417. headers = self.class.extract_rfc822_headers(message_meta)
  418. retrurn false if !headers
  419. local_message_id = headers['Message-ID']
  420. return false if local_message_id.blank?
  421. local_message_id_md5 = Digest::MD5.hexdigest(local_message_id)
  422. article = Ticket::Article.where(message_id_md5: local_message_id_md5).reorder('created_at DESC, id DESC').limit(1).first
  423. return false if !article
  424. # verify if message is already imported via same channel, if not, import it again
  425. ticket = article.ticket
  426. return false if ticket&.preferences && ticket.preferences[:channel_id].present? && channel.present? && ticket.preferences[:channel_id] != channel[:id]
  427. timeout(1.minute) do
  428. @imap.store(message_id, '+FLAGS', [:Seen])
  429. end
  430. Rails.logger.info " - ignore message #{count}/#{count_all} - because message message id already imported"
  431. true
  432. end
  433. =begin
  434. check if email is already marked as deleted
  435. Channel::Driver::IMAP.deleted?(message_meta, count, count_all)
  436. returns
  437. true|false
  438. =end
  439. def deleted?(message_meta, count, count_all)
  440. return false if message_meta.attr['FLAGS'].exclude?(:Deleted)
  441. Rails.logger.info " - ignore message #{count}/#{count_all} - because message has already delete flag"
  442. true
  443. end
  444. =begin
  445. check if email is to big
  446. Channel::Driver::IMAP.too_large?(message_meta, count, count_all)
  447. returns
  448. true|false
  449. =end
  450. def too_large?(message_meta)
  451. max_message_size = Setting.get('postmaster_max_size').to_f
  452. real_message_size = message_meta.attr['RFC822.SIZE'].to_f / 1024 / 1024
  453. if real_message_size > max_message_size
  454. return [real_message_size, max_message_size]
  455. end
  456. false
  457. end
  458. =begin
  459. check if channel config has changed
  460. Channel::Driver::IMAP.channel_has_changed?(channel)
  461. returns
  462. true|false
  463. =end
  464. def channel_has_changed?(channel)
  465. current_channel = Channel.find_by(id: channel.id)
  466. if !current_channel
  467. Rails.logger.info "Channel with id #{channel.id} is deleted in the meantime. Stop fetching."
  468. return true
  469. end
  470. return false if channel.updated_at == current_channel.updated_at
  471. Rails.logger.info "Channel with id #{channel.id} has changed. Stop fetching."
  472. true
  473. end
  474. =begin
  475. check if maximal fetching email count has reached
  476. Channel::Driver::IMAP.max_process_count_has_reached?(channel, count, count_max)
  477. returns
  478. true|false
  479. =end
  480. def max_process_count_has_reached?(channel, count, count_max)
  481. return false if count < count_max
  482. Rails.logger.info "Maximal fetched emails (#{count_max}) reached for this interval for Channel with id #{channel.id}."
  483. true
  484. end
  485. def timeout(seconds, &)
  486. Timeout.timeout(seconds, &)
  487. end
  488. end