Статус Microsoft Small Business Specialist

Microsoft Licensing Partner

Контактная информация (495) 987 32 16 Техническая поддержка

Обзор архитектуры Postfix

Версия для печати

Обзор архитектуры Postfix


Введение

Этот документ содержит обзор архитектуры Postfix. Здесь Вы найдете ссылки на каждую команду или демон Postfix-а. В тексте описывается общий контекст, в котором используются та или иная команда или серверная программа, а также приводятся ссылки на документы, содержащие дополнительную информацию и примеры.

Темы, охваченные в данном докумените:

Как Postfix принимает почту

Когда письмо попадает в почтовую систему Postfix, оно делает первую остановку в очереди входящих сообщений (incoming queue). На диаграмме ниже отображены основные процессы, которые вовлечены в работу с поступившей почтой. Имена с последующим номером - это команды или демоны Postfix, а имена без номеров на затененном фоне - это очереди Postfix.

trivial-
rewrite(8)
Сеть -> smtpd(8)
^
|
|
v
\
Сеть -> qmqpd(8) -> cleanup(8) -> incoming
/
pickup(8) <- maildrop
^
|
Локальная машина -> sendmail(1) -> postdrop(1)
  • Почта из сети поступает в Postfix через демон smtpd(8) или qmqpd(8). Эти процессы удаляют инкапсуляцию протоколов SMTP или QMQP, выполняют некоторые проверки корректности для защиты Postfix и передают адреса отправителя и получателя а также содержимое письма демону cleanup(8). Сервер smtpd(8) может быть настроен таким образом, чтобы блокировать нежелательную почту, как это описано в файле SMTPD_ACCESS_README.

  • Локальные поступления почты принимаются командой sendmail(1) (которая является sendmail совместимой) и помещаются в очередь maildrop (maildrop queue) с помощью привилегированной команды postdrop(1). Эта схема поступления локальной почты работает даже при остановленной системе Postfix. Локальный сервер pickup(8) "подбирает" почту из очереди maildrop (maildrop queue), проводит некоторые проверки для защиты Postfix и передает адреса отправителя и получателя а также содержимое письма демону cleanup(8).

  • Письма от внутренних источников передаются напрямую серверу cleanup(8). Эти источники не показаны на диаграмме и включают в себя: почту, которая пересылается локальным агентом доставки (local(8)), сообщения, которые возвращаются отправителю сервером bounce(8) и письма для postmaster-а о проблемах почтовой системы.

  • Демон cleanup(8) производит завершающую обработку почты перед помещением ее в очередь. Он добавляет отсутствующий "From:" и другие заголовки сообщения, трантсформирует адреса, как это описано в документе ADDRESS_REWRITING_README. Опционально, демон cleanup(8) может быть настроен на выполнение нетребовательной к ресурсам (light-weight) проверки контента с использованием регулярных выражений, как это описано в файле BUILTIN_FILTER_README. Сервер cleanup(8) помещает результат в виде отдельного файла в очередь входящих сообщений (incoming queue) и сообщает менеджеру очереди (смотрите следующий раздел) о поступлении нового сообщения.

  • Демон trivial-rewrite(8) модифицырует адреса, преобразуя их к стандартному виду "[email protected]", как это описано в документе ADDRESS_REWRITING_README. Postfix на данный момент не предоставляет язык преобразования (rewriting language), но многое может быть реализовано с использованием табличного поиска и, если необходимо, регулярных выражений.

Как Postfix доставляет почту

Как только сообщение попадает в очередь входящих сообщений (incoming queue), наступает следующий этап его обработки - доставка. На диаграмме ниже отображены основные процессы Postfix, которые занимаются доставкой почты. Имена с последующим номером - это команды или демоны Postfix, а имена без номеров на затененном фоне - это очереди Postfix.

trivial-
rewrite(8)
smtp(8) -> Сеть
/
^
|
|
v
- lmtp(8) -> Сеть
/
incoming -> active -> qmgr(8) --- local(8) -> Файл, команда
^
|
|
v
\
- virtual(8) -> Файл
deferred \
pipe(8) -> Команда
  • Основную координирующую роль при доставке почты выполняет менеджер очереди (queue manager, демон qmgr(8) на диаграмме). Он контактирует с smtp(8), lmtp(8), local(8), virtual(8), pipe(8), discard(8) или error(8) агентами доставки и посылает запросы на доставку для одного или большего количества адресов получателей. Агенты доставки discard(8) и error(8) специальные: они отвергают(discard) или рикошетят(bounce) всю почту и не отображены на диаграмме.

    Менеджер очереди поддерживает маленькую активную очередь (active queue) сообщений, которые он открыл для доставки. Активная очередь (active queue) представляет собой маленькое окно для работы с потенциально большими очередями incoming или deferred. Ограниченная по размерам active queue предотвращает проблему недостатка памяти для менеджера очередей, которая может возникнуть при больших нагрузках.

    Менеджер очередей поддерживает отдельную очередь отложенных сообщений (deferred queue) для почты, которая не может быть доставлена. Таким образом большой багаж "проблемной" почты выделен в отдельную очередь и не мешает нормальной работе с другими очередями. О стратегии, которой пользуется менеджер для доставки отложенных сообщений, можно почитать в файлах QSHAPE_README и TUNING_README.

  • The trivial-rewrite(8) server resolves each recipient address according to its local and remote address class, as defined in the ADDRESS_CLASS_README document. Additional routing information can be specified with the optional transport(5) table. The trivial-rewrite(8) server optionally queries the relocated(5) table for recipients whose address has changed; mail for such recipients is returned to the sender with an explanation.

  • The smtp(8) client looks up a list of mail exchangers for the destination host, sorts the list by preference, and tries each server in turn until it finds a server that responds. It then encapsulates the sender, recipient and message content as required by the SMTP protocol; this includes conversion of 8-bit MIME to 7-bit encoding.

  • The lmtp(8) client speaks a protocol similar to SMTP that is optimized for delivery to mailbox servers such as Cyrus. The advantage of this setup is that one Postfix machine can feed multiple mailbox servers over LMTP. The opposite is true as well: one mailbox server can be fed over LMTP by multiple Postfix machines. The LMTP_README document gives examples of how to use the lmtp(8) client.

  • The local(8) delivery agent understands UNIX-style mailboxes, qmail-compatible maildir files, Sendmail-style system-wide aliases(5) databases, and Sendmail-style per-user .forward files. Multiple local delivery agents can be run in parallel, but parallel delivery to the same user is usually limited.

    The local(8) delivery agent has hooks for alternative forms of local delivery: you can configure it to deliver to mailbox files in user home directories, you can configure it to delegate mailbox delivery to an external command such as procmail, or you can delegate delivery to a different Postfix delivery agent.

  • The virtual(8) delivery agent is a bare-bones delivery agent that delivers to UNIX-style mailbox or qmail-style maildir files only. This delivery agent can deliver mail for multiple domains, which makes it especially suitable for hosting lots of small domains on a single machine. This is described in the VIRTUAL_README document.

  • The pipe(8) mailer is the outbound interface to other mail processing systems (the Postfix sendmail(1) command being the inbound interface). The interface is UNIX compatible: it provides information on the command line and on the standard input stream, and expects a process exit status code as defined in <sysexits.h>. Examples of delivery via the pipe(8) mailer are in the MAILDROP_README and UUCP_README documents.

Postfix behind the scenes

The previous sections gave an overview of how Postfix server processes send and receive mail. These server processes rely on other server processes that do things behind the scenes. The text below attempts to visualize each service in its own context. As before, names followed by a number are Postfix commands or server programs, while unnumbered names inside shaded areas represent Postfix queues.

  • The resident master(8) server is the supervisor that keeps an eye on the well-being of the Postfix mail system. It is typically started at system boot time with the "postfix start" command, and keeps running until the system goes down. The master(8) server is responsible for starting Postfix server processes to receive and deliver mail, and for restarting servers that terminate prematurely because of some problem. The master(8) server is also responsible for enforcing the server process count limits as specified in the master.cf configuration file. The picture below gives the program hierarchy when Postfix is started up. Only some of the mail handling daemon processes are shown.

    postfix(1)
    |
    |
    postfix-script(1)
    /
    /
    |
    |
    \
    \
    postsuper(1) master(8) postlog(1)
    /
    /
    |
    |
    \
    \
    smtpd(8) qmgr(8) local(8)
  • The anvil(8) server implements client connection and request rate limiting for all smtpd(8) servers. The TUNING_README document provides guidance for dealing with mis-behaving SMTP clients. The anvil(8) service is available in Postfix version 2.2 and later.

    Network ->
    smtpd(8)

    <->
    anvil(8)

  • The bounce(8), defer(8) and trace(8) servers each maintain their own queue directory trees with per-message logfiles. This information is used to send delivery or non-delivery notifications to the sender.

    The trace(8) service implements support for the Postfix "sendmail -bv" and "sendmail -v" commands which produce reports about how Postfix delivers mail, and is available with Postfix version 2.1 and later. See DEBUG_README for examples.

    cleanup(8) -> qmgr(8)
    Postfix
    queue
    -> Delivery
    agents
    ^
    |
    |
    v
    |
    v
    (Non-)
    delivery
    notice
    <- bounce(8)
    defer(8)
    trace(8)
    <- Queue id,
    recipient,
    status
    ^
    |
    |
    v
    Per-
    message
    logfiles
  • The flush(8) servers maintain per-destination logs and implement both ETRN and "sendmail -qRdestination", as described in the ETRN_README document. This moves selected queue files from the deferred queue back to the incoming queue and requests their delivery. The flush(8) service is available with Postfix version 1.0 and later.

    incoming
    ^
    deferred
    ^
    |
    smtpd(8)
    sendmail(1)
    postqueue(1)
    - Destination
    to flush
    -> flush(8) <- Deferred
    destination,
    queue id
    - Delivery
    agents,
    qmgr(8)
    ^
    |
    |
    v
    Per-dest-
    ination
    logs
  • The proxymap(8) servers provide read-only table lookup service to Postfix processes. This overcomes chroot restrictions, and reduces the number of open lookup tables by sharing one open table among multiple processes.

  • The scache(8) server maintains the connection cache for the Postfix smtp(8) client. When connection caching is enabled for selected destinations, the smtp(8) client does not disconnect immediately after a mail transaction, but gives the connection to the connection cache server which keeps the connection open for a limited amount of time. The smtp(8) client continues with some other mail delivery request. Meanwhile, any smtp(8) process can ask the scache(8) server for that cached connection and reuse it for mail delivery. As a safety measure, Postfix limits the number of times that a connection may be reused.

    When delivering mail to a destination with multiple mail servers, connection caching can help to skip over a non-responding server, and thus dramatically speed up delivery.


    smtp(8)
     
    <->
    scache(8)
     
    <->
    smtp(8)
     
  • The showq(8) servers list the Postfix queue status. This is the queue listing service that does the work for the mailq(1) and postqueue(1) commands.

    Output <- mailq(1)
    post-
    queue(1)

    <- showq(8) <- Postfix
    queue
  • The spawn(8) servers run non-Postfix commands on request, with the client connected via socket or FIFO to the command's standard input, output and error streams. You can find examples of its use in the SMTPD_POLICY_README document.

  • The tlsmgr(8) server runs when TLS (Transport Layer Security, formerly known as SSL) is turned on in the Postfix smtp(8) client or smtpd(8) server. This process has two duties:

    • Maintain the pseudo-random number generator (PRNG) that is used to seed the TLS engines in Postfix smtp(8) client or smtpd(8) server processes. The state of this PRNG is periodically saved to a file, and is read when tlsmgr(8) starts up.

    • Maintain the optional Postfix smtp(8) client or smtpd(8) server caches with TLS session keys. Saved keys can improve performance by reducing the amount of computation at the start of a TLS session.

    TLS support is available in Postfix version 2.2 and later. Information about the Postfix TLS implementation is in the TLS_README document.

    Network->
    smtpd(8)
     
    <---seed---

    <-session->

    tlsmgr(8)
     
    ---seed--->

    <-session->

    smtp(8)
     
    ->Network
    /
    /
    |
    |
    \
    \
    smtpd
    session
    cache
    PRNG
    state
    file
    smtp
    session
    cache
  • The verify(8) server verifies that a sender or recipient address is deliverable before the smtpd(8) server accepts it. The verify(8) server injects probe messages into the Postfix queue and processes status updates from delivery agents and/or queue manager. This process is described in the ADDRESS_VERIFICATION_README document. The verify(8) service is available with Postfix version 2.1 and later.

    Network -> smtpd(8) <-> verify(8) -> cleanup(8) -> qmgr(8)
    Postfix
    queue
    -> Delivery
    agents
    \
    \
    <- <- |
    v
    /
    /

Postfix support commands

The Postfix architecture overview ends with a summary of command-line utilities for day-to-day use of the Postfix mail system. Besides the Sendmail-compatible sendmail(1), mailq(1), and newaliases(1) commands, the Postfix system comes with it own collection of command-line utilities. For consistency, these are all named postsomething.

  • The postfix(1) command controls the operation of the mail system. It is the interface for starting, stopping, and restarting the mail system, as well as for some other administrative operations. This command is reserved to the super-user.

  • The postalias(1) command maintains Postfix aliases(5) type databases. This is the program that does the work for the newaliases(1) command.

  • The postcat(1) command displays the contents of Postfix queue files. This is a limited, preliminary utility. This program is likely to be superseded by something more powerful that can also edit Postfix queue files.

  • The postconf(1) command displays or updates Postfix main.cf parameters and displays system dependent information about the supported file locking methods, and the supported types of lookup tables.

  • The postdrop(1) command is the mail posting utility that is run by the Postfix sendmail(1) command in order to deposit mail into the maildrop queue directory.

  • The postkick(1) command makes some Postfix internal communication channels available for use in, for example, shell scripts.

  • The postlock(1) command provides Postfix-compatible mailbox locking for use in, for example, shell scripts.

  • The postlog(1) command provides Postfix-compatible logging for shell scripts.

  • The postmap(1) command maintains Postfix lookup tables such as canonical(5), virtual(5) and others. It is a cousin of the UNIX makemap command.

  • The postqueue(1) command is the privileged command that is run by Postfix sendmail(1) and mailq(1) in order to flush or list the mail queue.

  • The postsuper(1) command maintains the Postfix queue. It removes old temporary files, and moves queue files into the right directory after a change in the hashing depth of queue directories. This command is run at mail system startup time and when Postfix is restarted.




 
Будем благодарны за отзыв, с радостью ответим на любые вопросы!

Повторите:
Сообщение:
Контакт:
Отправить!