imap.rb 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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. 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. key = fetch_message_body_key(options)
  237. msg = @imap.fetch(message_id, key)[0].attr[key]
  238. end
  239. rescue Timeout::Error => e
  240. Rails.logger.error "Unable to fetch email from #{count}/#{count_all} from server (#{options[:host]}/#{options[:user]}): #{e.inspect}"
  241. raise e
  242. end
  243. next if !msg
  244. # do not process too big messages, instead download & send postmaster reply
  245. too_large_info = too_large?(message_meta)
  246. if too_large_info
  247. if Setting.get('postmaster_send_reject_if_mail_too_large') == true
  248. 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)"
  249. Rails.logger.info info
  250. notice += "#{info}\n"
  251. process_oversized_mail(channel, msg)
  252. else
  253. info = " - ignore message #{count}/#{count_all} - because message is too large (is:#{too_large_info[0]} MB/max:#{too_large_info[1]} MB)"
  254. Rails.logger.info info
  255. notice += "#{info}\n"
  256. too_large_messages.push info
  257. next
  258. end
  259. else
  260. process(channel, msg, false)
  261. end
  262. begin
  263. timeout(FETCH_MSG_TIMEOUT) do
  264. if keep_on_server
  265. @imap.store(message_id, '+FLAGS', [:Seen])
  266. else
  267. @imap.store(message_id, '+FLAGS', [:Deleted])
  268. end
  269. end
  270. rescue Timeout::Error => e
  271. Rails.logger.error "Unable to set +FLAGS for email #{count}/#{count_all} on server (#{options[:host]}/#{options[:user]}): #{e.inspect}"
  272. raise e
  273. end
  274. count_fetched += 1
  275. end
  276. if !keep_on_server
  277. begin
  278. timeout(EXPUNGE_TIMEOUT) do
  279. @imap.expunge
  280. end
  281. rescue Timeout::Error => e
  282. Rails.logger.error "Unable to expunge server (#{options[:host]}/#{options[:user]}): #{e.inspect}"
  283. raise e
  284. end
  285. end
  286. disconnect
  287. if count.zero?
  288. Rails.logger.info ' - no message'
  289. end
  290. if too_large_messages.present?
  291. raise too_large_messages.join("\n")
  292. end
  293. {
  294. result: result,
  295. fetched: count_fetched,
  296. notice: notice,
  297. }
  298. end
  299. def fetch_all_message_ids
  300. fetch_message_ids %w[ALL]
  301. end
  302. def fetch_unread_message_ids
  303. fetch_message_ids %w[NOT SEEN]
  304. rescue
  305. fetch_message_ids %w[UNSEEN]
  306. end
  307. def fetch_message_ids(filter)
  308. @imap.sort(['DATE'], filter, 'US-ASCII')
  309. rescue
  310. @imap.search(filter)
  311. end
  312. def fetch_message_body_key(options)
  313. # https://github.com/zammad/zammad/issues/4589
  314. options['host'] == 'imap.mail.me.com' ? 'BODY[]' : 'RFC822'
  315. end
  316. def disconnect
  317. return if !@imap
  318. timeout(1.minute) do
  319. @imap.disconnect
  320. end
  321. end
  322. =begin
  323. Channel::Driver::Imap.streamable?
  324. returns
  325. true|false
  326. =end
  327. def self.streamable?
  328. false
  329. end
  330. # Parses RFC822 header
  331. # @param [String] RFC822 header text blob
  332. # @return [Hash<String=>String>]
  333. def self.parse_rfc822_headers(string)
  334. array = string
  335. .gsub("\r\n\t", ' ') # Some servers (e.g. microsoft365) may put attribute value on a separate line and tab it
  336. .lines(chomp: true)
  337. .map { |line| line.split(%r{:\s*}, 2).map(&:strip) }
  338. array.each { |elem| elem.append(nil) if elem.one? }
  339. Hash[*array.flatten]
  340. end
  341. # Parses RFC822 header
  342. # @param [Net::IMAP::FetchData] fetched message
  343. # @return [Hash<String=>String>]
  344. def self.extract_rfc822_headers(message_meta)
  345. blob = message_meta&.attr&.dig 'RFC822.HEADER'
  346. return if !blob
  347. parse_rfc822_headers blob
  348. end
  349. private
  350. def messages_is_too_old_verify?(message_meta, count, count_all)
  351. headers = self.class.extract_rfc822_headers(message_meta)
  352. return true if !messages_is_verify_message?(headers)
  353. return true if headers['X-Zammad-Verify-Time'].blank?
  354. begin
  355. verify_time = Time.zone.parse(headers['X-Zammad-Verify-Time'])
  356. rescue => e
  357. Rails.logger.error e
  358. return true
  359. end
  360. return true if verify_time < 30.minutes.ago
  361. Rails.logger.info " - ignore message #{count}/#{count_all} - because message has a verify message"
  362. false
  363. end
  364. def messages_is_verify_message?(headers)
  365. return true if headers['X-Zammad-Verify'] == 'true'
  366. false
  367. end
  368. def messages_is_ignore_message?(headers)
  369. return true if headers['X-Zammad-Ignore'] == 'true'
  370. false
  371. end
  372. =begin
  373. check if email is already impoted
  374. Channel::Driver::IMAP.already_imported?(message_id, message_meta, count, count_all, keep_on_server, channel)
  375. returns
  376. true|false
  377. =end
  378. # rubocop:disable Metrics/ParameterLists
  379. def already_imported?(message_id, message_meta, count, count_all, keep_on_server, channel)
  380. # rubocop:enable Metrics/ParameterLists
  381. return false if !keep_on_server
  382. headers = self.class.extract_rfc822_headers(message_meta)
  383. retrurn false if !headers
  384. local_message_id = headers['Message-ID']
  385. return false if local_message_id.blank?
  386. local_message_id_md5 = Digest::MD5.hexdigest(local_message_id)
  387. article = Ticket::Article.where(message_id_md5: local_message_id_md5).reorder('created_at DESC, id DESC').limit(1).first
  388. return false if !article
  389. # verify if message is already imported via same channel, if not, import it again
  390. ticket = article.ticket
  391. return false if ticket&.preferences && ticket.preferences[:channel_id].present? && channel.present? && ticket.preferences[:channel_id] != channel[:id]
  392. timeout(1.minute) do
  393. @imap.store(message_id, '+FLAGS', [:Seen])
  394. end
  395. Rails.logger.info " - ignore message #{count}/#{count_all} - because message message id already imported"
  396. true
  397. end
  398. =begin
  399. check if email is already marked as deleted
  400. Channel::Driver::IMAP.deleted?(message_meta, count, count_all)
  401. returns
  402. true|false
  403. =end
  404. def deleted?(message_meta, count, count_all)
  405. return false if message_meta.attr['FLAGS'].exclude?(:Deleted)
  406. Rails.logger.info " - ignore message #{count}/#{count_all} - because message has already delete flag"
  407. true
  408. end
  409. =begin
  410. check if email is to big
  411. Channel::Driver::IMAP.too_large?(message_meta, count, count_all)
  412. returns
  413. true|false
  414. =end
  415. def too_large?(message_meta)
  416. max_message_size = Setting.get('postmaster_max_size').to_f
  417. real_message_size = message_meta.attr['RFC822.SIZE'].to_f / 1024 / 1024
  418. if real_message_size > max_message_size
  419. return [real_message_size, max_message_size]
  420. end
  421. false
  422. end
  423. =begin
  424. check if channel config has changed
  425. Channel::Driver::IMAP.channel_has_changed?(channel)
  426. returns
  427. true|false
  428. =end
  429. def channel_has_changed?(channel)
  430. current_channel = Channel.find_by(id: channel.id)
  431. if !current_channel
  432. Rails.logger.info "Channel with id #{channel.id} is deleted in the meantime. Stop fetching."
  433. return true
  434. end
  435. return false if channel.updated_at == current_channel.updated_at
  436. Rails.logger.info "Channel with id #{channel.id} has changed. Stop fetching."
  437. true
  438. end
  439. =begin
  440. check if maximal fetching email count has reached
  441. Channel::Driver::IMAP.max_process_count_has_reached?(channel, count, count_max)
  442. returns
  443. true|false
  444. =end
  445. def max_process_count_has_reached?(channel, count, count_max)
  446. return false if count < count_max
  447. Rails.logger.info "Maximal fetched emails (#{count_max}) reached for this interval for Channel with id #{channel.id}."
  448. true
  449. end
  450. def timeout(seconds, &)
  451. Timeout.timeout(seconds, &)
  452. end
  453. end