o bMl@s~dZddlZddlZddlZddlZddlmZddlmZddl m Z ddl m Z m Z mZddlmZddlmZmZmZdd lmZmZmZdd lmZdd lmZdd lmZmZd Z GdddZ!e!ej"Z#ddZ$Gdddej%Z&e ej'GdddZ(e ej)GdddZ*Gdddej+Z,e ej-GdddZ.e ej/Gddde(Z0e e j1GdddZ2dS) z Maildir-style mailbox support. N)md5)IO) implementer)checkers credentialsportal)UnauthorizedLogin)defer interfacesreactor)mailpop3smtpdirdbm)basic)failurelogzFrom: Twisted.mail Internals Subject: An Error Occurred An internal server error has occurred. Please contact the server administrator. c@sDeZdZdZdZeZe dd ddZ ddZ d d Z d S) _MaildirNameGeneratoraK A utility class to generate a unique maildir name. @type n: L{int} @ivar n: A counter used to generate unique integers. @type p: L{int} @ivar p: The ID of the current process. @type s: L{bytes} @ivar s: A representation of the hostname. @ivar _clock: See C{clock} parameter of L{__init__}. r/z\057:z\072cC ||_dS)z @type clock: L{IReactorTime } provider @param clock: A reactor which will be used to learn the current time. N)_clock)selfclockr6/usr/lib/python3/dist-packages/twisted/mail/maildir.py__init__8 z_MaildirNameGenerator.__init__c Csb|jd|_|j}tt|}dt|t|df}|d|d|jd|jd|j S)a Generate a string which is intended to be unique across all calls to this function (across all processes, reboots, etc). Strings returned by earlier calls to this method will compare less than strings returned by later calls as long as the clock provided doesn't go backwards. @rtype: L{bytes} @return: A unique string. z%07dgcAz.MPQ.)nrsecondsstrintps)rtr$ microsecondsrrrgenerate?s  &z_MaildirNameGenerator.generateN)__name__ __module__ __qualname____doc__r#osgetpidr'socket gethostnamereplacer(rr+rrrrr$s rcCst|}tj|sAt|ddD] }ttj||dqdD]}ttj|d|dq#ttj|ddddSdS)z Create a maildir user directory if it doesn't already exist. @type dir: L{bytes} @param dir: The path name for a user directory. i)newcurtmp.Trash)r5r6r7r8 maildirfolderwN)r0fsdecodepathisdirmkdirjoinopenclose)dirsubdirrrrinitializeMaildirUs   rDc@s,eZdZdZdZddZddZddZdS) MaildirMessagez A message receiver which adds a header and delivers a message to a file whose name includes the size of the message. @type size: L{int} @ivar size: The number of octets in the message. NcOs<d|}||t||_tjj||g|Ri|dS)a @type address: L{bytes} @param address: The address of the message recipient. @type fp: file-like object @param fp: The file in which to store the message while it is being received. @type a: 2-L{tuple} of (0) L{bytes}, (1) L{bytes} @param a: Positional arguments for L{FileMessage.__init__}. @type kw: L{dict} @param kw: Keyword arguments for L{FileMessage.__init__}. zDelivered-To: %s N)writelensizer FileMessager)raddressfpakwheaderrrrrrs   zMaildirMessage.__init__cCs(tj|||jt|d7_dS)zo Write a line to the file. @type line: L{bytes} @param line: A received line. rN)r rI lineReceivedrHrG)rlinerrrrOszMaildirMessage.lineReceivedcCs|jd|j|_tj|S)aO At the end of message, rename the file holding the message to its final name concatenated with the size of the file. @rtype: L{Deferred } which successfully results in L{bytes} @return: A deferred which returns the name of the file holding the message. z,S=%d) finalNamerHr rI eomReceivedrrrrrRs zMaildirMessage.eomReceived)r,r-r.r/rHrrOrRrrrrrEgs  rEc@sZeZdZdZdZdZddZddZddZdd d Z d d Z d dZ ddZ ddZ dS)AbstractMaildirDomainz An abstract maildir-backed domain. @type alias: L{None} or L{dict} mapping L{bytes} to L{AliasBase} @ivar alias: A mapping of username to alias. @ivar root: See L{__init__}. NcCs ||_dS)z @type service: L{MailService} @param service: An email service. @type root: L{bytes} @param root: The maildir root directory. N)root)rservicerUrrrrs zAbstractMaildirDomain.__init__cCdS)z Return the maildir directory for a user. @type user: L{bytes} @param user: A username. @rtype: L{bytes} or L{None} @return: The user's mail directory for a valid user. Otherwise, L{None}. Nrruserrrr userDirectorys z#AbstractMaildirDomain.userDirectorycCr)z Set the group of defined aliases for this domain. @type alias: L{dict} mapping L{bytes} to L{IAlias} provider. @param alias: A mapping of domain name to alias. N)alias)rr[rrr setAliasGroups z#AbstractMaildirDomain.setAliasGroupcsjjdurfddSz jjj}Wn ty%tw|j|r5fddSt dt t)a Check whether a user exists in this domain or an alias of it. @type user: L{User} @param user: A user. @type memo: L{None} or L{dict} of L{AliasBase} @param memo: A record of the addresses already considered while resolving aliases. The default value should be used by all external code. @rtype: no-argument callable which returns L{IMessage } provider. @return: A function which takes no arguments and returns a message receiver for the user. @raises SMTPBadRcpt: When the given user does not exist in this domain or an alias of it. Ncs SN) startMessagerrXrrs z.AbstractMaildirDomain.exists..csSr]rr)aliasesrrr_zBad alias configuration: ) rZdestlocalr[ BaseExceptionr SMTPBadRcptresolvererrr%)rrYmemorLr)r`rrYrexistss    zAbstractMaildirDomain.existsc Cs|t|tr|dd\}}n |jj|jj}}||}t}tj |d|}t |d}t |d|||tj |d|S)z Create a maildir message for a user. @type user: L{bytes} @param user: A username. @rtype: L{MaildirMessage} @return: A message receiver for this user. @rr7r:r5) isinstancer%splitrbrcdomainrZ_generateMaildirNamer0r<r?r@rE)rrYnamermrBfnamefilenamerKrrrr^s   z"AbstractMaildirDomain.startMessagecCrW)a Check whether this domain will relay. @type user: L{Address} @param user: The destination address. @type protocol: L{SMTP} @param protocol: The protocol over which the message to be relayed is being received. @rtype: L{bool} @return: An indication of whether this domain will relay the message to the destination. Fr)rrYprotocolrrr willRelayszAbstractMaildirDomain.willRelaycCt)z Add a user to this domain. Subclasses should override this method. @type user: L{bytes} @param user: A username. @type password: L{bytes} @param password: A password. NotImplementedErrorrrYpasswordrrraddUsers zAbstractMaildirDomain.addUsercCrt)a  Return credentials checkers for this domain. Subclasses should override this method. @rtype: L{list} of L{ICredentialsChecker } provider @return: Credentials checkers for this domain. rurSrrrgetCredentialsCheckers#s z,AbstractMaildirDomain.getCredentialsCheckersr])r,r-r.r/r[rUrrZr\rir^rsryrzrrrrrTs   ! rTc@seZdZdZeejZeejZ eej Z eej Z ddZddZddZdd Zd d Zd d ZdddZddZddZdS) _MaildirMailboxAppendMessageTaska A task which adds a message to a maildir mailbox. @ivar mbox: See L{__init__}. @type defer: L{Deferred } which successfully returns L{None} @ivar defer: A deferred which fires when the task has completed. @type opencall: L{IDelayedCall } provider or L{None} @ivar opencall: A scheduled call to L{prodProducer}. @type msg: file-like object @ivar msg: The message to add. @type tmpname: L{bytes} @ivar tmpname: The pathname of the temporary file holding the message while it is being transferred. @type fh: file @ivar fh: The new maildir file. @type filesender: L{FileSender } @ivar filesender: A file sender which sends the message. @type myproducer: L{IProducer } @ivar myproducer: The registered producer. @type streaming: L{bool} @ivar streaming: Indicates whether the registered producer provides a streaming interface. cCs4||_t|_d|_t|dst|}||_dS)z @type mbox: L{MaildirMailbox} @param mbox: A maildir mailbox. @type msg: L{bytes} or file-like object @param msg: The message to add. Nread)mboxr DeferredopenCallhasattrioBytesIOmsg)rr}rrrrrYs     z)_MaildirMailboxAppendMessageTask.__init__cCs4||jdkrt|_|j|j|dSdS)z@ Start transferring the message to the mailbox. N)createTempFilefhr FileSender filesenderbeginFileTransferrrSrrrstartUphs   z(_MaildirMailboxAppendMessageTask.startUpcCs ||_||_|s|dSdS)aS Register a producer and start asking it for data if it is non-streaming. @type producer: L{IProducer } @param producer: A producer. @type streaming: L{bool} @param streaming: A flag indicating whether the producer provides a streaming interface. N) myproducer streaming prodProducer)rproducerrrrrregisterProducerqs   z1_MaildirMailboxAppendMessageTask.registerProducercCs2d|_|jdurtd|j|_|jdSdS)zK Repeatedly prod a non-streaming producer to produce data. Nr)rrr callLaterrresumeProducingrSrrrrs  z-_MaildirMailboxAppendMessageTask.prodProducercCs$d|_d|_||j|dS)zA Finish transferring the message to the mailbox. N)rroscloser moveFileToNewrSrrrunregisterProducers  z3_MaildirMailboxAppendMessageTask.unregisterProducercCs2z ||j|WdSty|YdSw)z Write data to the maildir file. @type data: L{bytes} @param data: Data to be written to the file. N)oswriterrdfail)rdatarrrrFs  z&_MaildirMailboxAppendMessageTask.writeNcCs:|durt}|jdur|j|j|d|_dS)z Fire the deferred to indicate the task completed with a failure. @type err: L{Failure } @param err: The error that occurred. N)rFailurercancelr errback)rrgrrrrs     z%_MaildirMailboxAppendMessageTask.failc Cs tj|jjdt}z ||j|Wn-tyA}z |j\}}ddl }||j kr7| d}WYd}~n WYd}~nd}~wwq|durY|jj ||jdd|_dSdS)z Place the message in the I{new/} directory, add it to the mailbox and fire the deferred to indicate that the task has completed successfully. Tr5rN)r0r<r?r}rnosrenametmpnameOSErrorargserrnoEEXISTrlistappendr callback)rnewnameergestrrrrrrs*      z._MaildirMailboxAppendMessageTask.moveFileToNewcCstjtjBtjBttddBttddB}d}d|_ tj|jjdt |_ z | |j |d|_WdSt yV|d 7}|d krT|j td |jjd|_ YdSYnwq) zY Create a temporary file to hold the message as it is being transferred. O_NOINHERITr O_NOFOLLOWrTr7iNriz Could not create tmp file for %s)r0O_RDWRO_CREATO_EXCLgetattrrr<r?r}rnrosopenrr r RuntimeError)rattrtriesrrrrs<    z/_MaildirMailboxAppendMessageTask.createTempFiler])r,r-r.r/ staticmethodr0r@rrFrrArrenamerrrrrrrrrrrrrr{0s "       r{c@sNeZdZdZeZddZdddZddZd d Z d d Z d dZ ddZ dS)MaildirMailboxa A maildir-backed mailbox. @ivar path: See L{__init__}. @type list: L{list} of L{int} or 2-L{tuple} of (0) file-like object, (1) L{bytes} @ivar list: Information about the messages in the mailbox. For undeleted messages, the file containing the message and the full path name of the file are stored. Deleted messages are indicated by 0. @type deleted: L{dict} mapping 2-L{tuple} of (0) file-like object, (1) L{bytes} to L{bytes} @type deleted: A mapping of the information about a file before it was deleted to the full path name of the deleted file in the I{.Trash/} subfolder. c Csz||_g|_i|_t|dD]}ttj||D]}|j|tj|||fqq|jdd|jD|_dS)ze @type path: L{bytes} @param path: The directory name for a maildir mailbox. )r6r5cSsg|]}|dqS)rr).0rrrr sz+MaildirMailbox.__init__..N) r<rdeletedrDr0listdirr?rsort)rr<rofilerrrrs zMaildirMailbox.__init__NcCsf|dur!g}|jD]}|r|t|tjq |dq |S|j|r1t|j|tjp2dS)al Retrieve the size of a message, or, if none is specified, the size of each message in the mailbox. @type i: L{int} or L{None} @param i: The 0-based index of a message. @rtype: L{int} or L{list} of L{int} @return: The number of octets in the specified message, or, if an index is not specified, a list of the number of octets for all messages in the mailbox. Any value which corresponds to a deleted message is set to 0. @raise IndexError: When the index does not correspond to a message in the mailbox. Nr)rrr0statST_SIZE)riretmessrrr listMessages s  $zMaildirMailbox.listMessagescCst|j|S)aR Retrieve a file-like object with the contents of a message. @type i: L{int} @param i: The 0-based index of a message. @rtype: file-like object @return: A file containing the message. @raise IndexError: When the index does not correspond to a message in the mailbox. )r@rrrrrr getMessage%s zMaildirMailbox.getMessagecCstj|j|}t|S)ar Get a unique identifier for a message. @type i: L{int} @param i: The 0-based index of a message. @rtype: L{bytes} @return: A string of printable characters uniquely identifying the message for all time. @raise IndexError: When the index does not correspond to a message in the mailbox. )r0r<basenamerr hexdigest)rrbaserrrgetUidl4s zMaildirMailbox.getUidlc CsRtj|jddtj|j|}t|j||||j|j|<d|j|<dS)aK Mark a message for deletion. Move the message to the I{.Trash/} subfolder so it can be undeleted by an administrator. @type i: L{int} @param i: The 0-based index of a message. @raise IndexError: When the index does not correspond to a message in the mailbox. r8r6rN)r0r<r?rrrr)rr trashFilerrr deleteMessageFs  zMaildirMailbox.deleteMessagec Cs|jD]H\}}zt||Wn!ty2}z|j\}}ddl}||jkr(WYd}~qd}~wwz ||j|j d<Wqt yM|j |Yqw|j dS)z Undelete all messages marked for deletion. Move each message marked for deletion from the I{.Trash/} subfolder back to its original position. rN) ritemsr0rrrrENOENTrindex ValueErrorrclear)rrealtrashrrgrrrrrundeleteMessagesZs"     zMaildirMailbox.undeleteMessagescCs|||}|j}||S)a Add a message to the mailbox. @type txt: L{bytes} or file-like object @param txt: A message to add. @rtype: L{Deferred } @return: A deferred which fires when the message has been added to the mailbox. ) AppendFactoryr r)rtxttaskresultrrr appendMessagess zMaildirMailbox.appendMessager]) r,r-r.r/r{rrrrrrrrrrrrrs  rc@sXeZdZdZddZdddZdedeefd d Z d d Z d dZ ddZ ddZ dS)StringListMailboxz An in-memory mailbox. @ivar msgs: See L{__init__}. @type _delete: L{set} of L{int} @ivar _delete: The indices of messages which have been marked for deletion. cCs||_t|_dS)zs @type msgs: L{list} of L{bytes} @param msgs: The contents of each message in the mailbox. N)msgsset_delete)rrrrrrs zStringListMailbox.__init__Ncs@|durfddttjDS|jvrdStj|S)ak Retrieve the size of a message, or, if none is specified, the size of each message in the mailbox. @type i: L{int} or L{None} @param i: The 0-based index of a message. @rtype: L{int} or L{list} of L{int} @return: The number of octets in the specified message, or, if an index is not specified, a list of the number of octets in each message in the mailbox. Any value which corresponds to a deleted message is set to 0. @raise IndexError: When the index does not correspond to a message in the mailbox. Ncsg|]}|qSr)r)rrrSrrrsz2StringListMailbox.listMessages..r)rangerGrrrrrSrrs  zStringListMailbox.listMessagesrreturncCst|j|S)a9 Return an in-memory file-like object with the contents of a message. @param i: The 0-based index of a message. @return: An in-memory file-like object containing the message. @raise IndexError: When the index does not correspond to a message in the mailbox. )rrrrrrrrs zStringListMailbox.getMessagecCst|j|S)aP Get a unique identifier for a message. @type i: L{int} @param i: The 0-based index of a message. @rtype: L{bytes} @return: A hash of the contents of the message at the given index. @raise IndexError: When the index does not correspond to a message in the mailbox. )rrrrrrrrs zStringListMailbox.getUidlcCs|j|dS)z Mark a message for deletion. @type i: L{int} @param i: The 0-based index of a message to delete. @raise IndexError: When the index does not correspond to a message in the mailbox. N)raddrrrrrs zStringListMailbox.deleteMessagecCs t|_dS)zL Undelete any messages which have been marked for deletion. N)rrrSrrrrs z"StringListMailbox.undeleteMessagescCs"|jD]}d|j|<qt|_dS)zK Discard the contents of any messages marked for deletion. N)rrr)rrrrrsyncs   zStringListMailbox.syncr])r,r-r.r/rrr&rbytesrrrrrrrrrrs   rc@sBeZdZdZdZdZdddZddZdd Zd d Z d d Z dS)MaildirDirdbmDomaina A maildir-backed domain where membership is checked with a L{DirDBM } database. The directory structure of a MaildirDirdbmDomain is: /passwd <-- a DirDBM directory /USER/{cur, new, del} <-- each user has these three directories @ivar postmaster: See L{__init__}. @type dbm: L{DirDBM } @ivar dbm: The authentication database for the domain. NrcCsRt|}t|||tj|d}tj|st|t ||_ ||_ dS)av @type service: L{MailService} @param service: An email service. @type root: L{bytes} @param root: The maildir root directory. @type postmaster: L{bool} @param postmaster: A flag indicating whether non-existent addresses should be forwarded to the postmaster (C{True}) or bounced (C{False}). spasswdN) r0fsencoderTrr<r?rimakedirsrr@dbm postmaster)rrVrUrrrrrrs     zMaildirDirdbmDomain.__init__cCs@||jvr |js dSd}tj|j|}tj|st||S)aq Return the path to a user's mail directory. @type name: L{bytes} @param name: A username. @rtype: L{bytes} or L{None} @return: The path to the user's mail directory for a valid user. For an invalid user, the path to the postmaster's mailbox if bounces are redirected there. Otherwise, L{None}. Nr)rrr0r<r?rUrirD)rrorBrrrrZs  z!MaildirDirdbmDomain.userDirectorycCs||j|<||dS)a Add a user to this domain by adding an entry in the authentication database and initializing the user's mail directory. @type user: L{bytes} @param user: A username. @type password: L{bytes} @param password: A password. N)rrZrwrrrry$s zMaildirDirdbmDomain.addUsercCs|jdur t|jg|_|jS)z Return credentials checkers for this domain. @rtype: L{list} of L{ICredentialsChecker } provider @return: Credentials checkers for this domain. N) _credcheckersDirdbmDatabaserrSrrrrz3s z*MaildirDirdbmDomain.getCredentialsCheckerscGsLtj|vr td|tjkrttg}n ttj |j |}tj|ddfS)aw Get the mailbox for an authenticated user. The mailbox for the authenticated user will be returned only if the given interfaces include L{IMailbox }. Requests for anonymous access will be met with a mailbox containing a message indicating that an internal error has occurred. @type avatarId: L{bytes} or C{twisted.cred.checkers.ANONYMOUS} @param avatarId: A string which identifies a user or an object which signals a request for anonymous access. @type mind: L{None} @param mind: Unused. @type interfaces: n-L{tuple} of C{zope.interface.Interface} @param interfaces: A group of interfaces, one of which the avatar must support. @rtype: 3-L{tuple} of (0) L{IMailbox }, (1) L{IMailbox } provider, (2) no-argument callable @return: A tuple of the supported interface, a mailbox, and a logout function. @raise NotImplementedError: When the given interfaces do not include L{IMailbox }. z No interfacecSsdSr]rrrrrr_craz3MaildirDirdbmDomain.requestAvatar..) r IMailboxrvr ANONYMOUSrINTERNAL_ERRORrr0r<r?rU)ravatarIdmindr r}rrr requestAvatar?s   z!MaildirDirdbmDomain.requestAvatar)r) r,r-r.r/rrrrZryrzrrrrrrs  rc@s,eZdZdZejejfZddZddZ dS)rz A credentials checker which authenticates users out of a L{DirDBM } database. @type dirdbm: L{DirDBM } @ivar dirdbm: An authentication database. cCr)zf @type dbm: L{DirDBM } @param dbm: An authentication database. Nr)rrrrrrvrzDirdbmDatabase.__init__cCs*|j|jvr||j|jr|jSt)a Authenticate a user and, if successful, return their username. @type c: L{IUsernamePassword } or L{IUsernameHashedPassword } provider. @param c: Credentials. @rtype: L{bytes} @return: A string which identifies an user. @raise UnauthorizedLogin: When the credentials check fails. )usernamer checkPasswordr)rcrrrrequestAvatarId}s zDirdbmDatabase.requestAvatarIdN) r,r-r.r/rIUsernamePasswordIUsernameHashedPasswordcredentialInterfacesrrrrrrrfs  r)3r/rr0r2rhashlibrtypingrzope.interfacer twisted.credrrrtwisted.cred.errorrtwisted.internetr r r twisted.mailr r rtwisted.persistedrtwisted.protocolsrtwisted.pythonrrrrr+rnrDrIrEIAliasableDomainrT IConsumerr{MailboxrrrIRealmrICredentialsCheckerrrrrrsF       .75 `