This file is indexed.

/usr/lib/python2.7/dist-packages/automx/config.py is in automx 0.10.0-2.1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
"""
automx - auto configuration service
Copyright (c) 2011-2013 [*] sys4 AG

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

__version__ = '0.10.0'
__author__ = "Christian Roessner, Patrick Ben Koetter"
__copyright__ = "Copyright (c) 2011-2013 [*] sys4 AG"

import os
import sys
import ConfigParser
import subprocess
import shlex
import StringIO
import re
import memcache
import logging

from ConfigParser import NoOptionError, NoSectionError
from ipaddr import IPAddress, IPNetwork
from dateutil import parser

try:
    # Python 2.7
    from collections import OrderedDict
except:
    # Python 2.5 up to Python 2.7
    from automx.ordereddict import OrderedDict


class DataNotFoundException(Exception):
    pass


class Config(object, ConfigParser.RawConfigParser):
    """
    This class creates the internal data structure that is completely
    independend from the view. It may query different backends to gather all
    required information needed to generate XML output later on in the view
    class.
    
    It uses a OrderdDict to guarentee the correct service order that is needed
    in the XML output. This said means that it is a difference, if a service
    like IMAP is configured before POP3 or upside down, because a MUA follows
    this order.
    
    The class currently support smtp, pop and imap services.
    
    The class currently supports the following backends:
    
    -> global - This backend tells automx to use the global section
    
    -> static - all kind of service information that can be sent directly to
                the MUA
                
    -> filter - This backend can execute commands and collects results from
                stdout. The result may be "", which means we skip further
                searching. It may return data, which should point to a section
                that we try to follow.
                
    -> ldap   - Read all kind of information from LDAP servers. The result
                attributes are stored in an internal dictionary and if options
                later on in this backend section (is read as static backend)
                do contain variables in the form ${attributename}, these are
                expanded to the collected data.
                
    -> sql    - Read all kind of information from SQL servers. The result
                attributes are stored in an internal dictionary. See ldpa
                
    -> script - Execute a script and split a result into attributes, which are
                stored in an internal dictionary, See ldap
                
    -> file   - Provide static files. If present, all collected data are
                discarded and only the static file is sent to the remote
                client. This may change in future releases.
    
    Note: There may exist a DEFAULT section that is appended to _all_ sections
    in the configuration file. That said you can do really complex
    configurations that on the other hand make life easier. This section also
    may contain variables, which, if found in the vars-dictionary, are used.
    
    """
    def __init__(self, environ):
        ConfigParser.RawConfigParser.__init__(self,
                                            defaults=None,
                                            dict_type=OrderedDict)
        self.read("/etc/automx.conf")

        if not self.has_section("automx"):
            raise Exception("Missing section 'automx'")


        if self.has_option("automx", "logfile"):
            self.logfile = self.get("automx", "logfile")
        else:
            self.logfile = None

        if self.has_option("automx", "debug"):
            self.debug = self.getboolean("automx", "debug")
        else:
            self.debug = False
            
        self.memcache = Memcache(self, environ)
        
    def configure(self, emailaddress, cn=None, password=None):
        if emailaddress is None:
            return OrderedDict()

        # Full email address containing local part _and_ domain
        self.__emailaddress = emailaddress
        
        # Mobileconfig
        if cn is None:
            self.__cn = ""
        else:
            self.__cn = cn
        if password is None:
            self.__password = ""
        else:
            self.__password = password
        
        domain = emailaddress.split("@")[1]

        # The domain that is searched in the config file
        self.__search_domain = domain
        
        self.__automx = dict()

        # domain individual settings (overwrites some or all defaults)
        self.__domain = OrderedDict()
        
        # if we use dynamic backends, we might earn variables
        self.__vars = dict()
        
        try:
            provider = self.get("automx", "provider")
            
            # provider must be a domainname
            pattern = "^[0-9a-zA-Z.-]+[a-zA-Z]{2,9}$"
            prog = re.compile(pattern)
            result = prog.match(provider)
            if result is not None:
                self.__automx["provider"] = result.group(0)
            else:
                logging.error("<provider> setting broken!")
                self.__automx["provider"] = "provider.broken"
            
            tmp = self.create_list(self.get("automx", "domains"))
            self.__automx["domains"] = tmp 
        except TypeError:
            raise Exception("Missing options in section automx")

        # if a domain has its own section, use settings from it
        cmp_domains = [dom.lower() for dom in self.__automx["domains"]]
        if (domain.lower() in iter(cmp_domains) or
            self.__automx["domains"][0] == "*"):
            cmp_sections = [dom.lower() for dom in self.sections()]
            if domain.lower() in iter(cmp_sections):
                self.__eval_options(domain)
            else:
                if self.has_section("global"):
                    self.__eval_options("global")
                else:
                    raise Exception("Missing section 'global'")
                # we need to use default values from config file
                self.__domain = self.__replace_makro(self.__domain)

    def __eval_options(self, section, backend=None):
        settings = self.__domain

        settings["domain"] = self.__search_domain
        settings["emailaddress"] = self.__emailaddress
        
        section = self.__find_section(section)
        
        if self.has_option(section, "backend"):
            if backend is None:
                try:
                    backend = self.get(section, "backend")
                except NoOptionError:
                    raise Exception("Missing option <backend>")
                
            if backend in ("static", "static_append"):
                for opt in iter(self.options(section)):
                    if opt in ("action",
                               "account_type",
                               "account_name",
                               "account_name_short",
                               "display_name",
                               "server_url",
                               "server_name"):
                        tmp = self.get(section, opt)
                        result = self.__expand_vars(tmp)
                        result = self.__replace_makro(result)
                        settings[opt] = result
                    elif opt == "smtp":
                        service = self.__service(section, "smtp")
                    elif opt == "imap":
                        service = self.__service(section, "imap")
                    elif opt == "pop":
                        service = self.__service(section, "pop")
                    elif opt == "sign_mobileconfig":
                        try:
                            settings[opt] = self.getboolean(section, opt)
                        except:
                            logging.error("%s is not boolean!" % opt)
                            settings[opt] = False
                    elif opt in ("sign_cert", "sign_key"):
                        result = self.get(section, opt)
                        if os.path.exists(result):
                            settings[opt] = result
                        else:
                            logging.error("%s cannot read %s" % (opt, result))
                    else:
                        pass
                    
                    if opt in ("smtp", "imap", "pop"):
                        if backend == "static_append":
                            if settings.has_key(opt):
                                if self.debug:
                                    logging.debug("APPEND %s" % service)
                                settings[opt].append(service)
                            else:
                                if self.debug:
                                    logging.debug("APPEND NEW %s"
                                                  % service)
                                settings[opt] = [service]
                        else:
                            # do not include empty services
                            if len(service) != 0:
                                if self.debug:
                                    logging.debug("STATIC %s" % service)
                                service_category = OrderedDict()
                                service_category[opt] = [service]
                                settings.update(service_category)

                # always follow at the end!
                if "follow" in self.options(section):
                    tmp = self.get(section, "follow")
                    result = self.__expand_vars(tmp)
                    result = self.__replace_makro(result)
                    self.__eval_options(result)

            elif backend in ("ldap", "ldap_append"):
                try:
                    import ldap
                    import ldap.sasl
                except:
                    raise Exception("python ldap missing")

                ldap_cfg = dict(host = "ldap://127.0.0.1/",
                                base = "",
                                bindmethod = "simple",
                                binddn = None,
                                bindpw = None,
                                saslmech = None,
                                authzid = "",
                                filter = "(objectClass=*)",
                                result_attrs = [],
                                scope = "sub",
                                usetls = "no",
                                cipher = "TLSv1",
                                reqcert ="never",
                                cert = None,
                                key = None,
                                cacert = None)

                tls = False
                sasl = False

                for opt in iter(self.options(section)):
                    if opt in ("host",
                               "base",
                               "bindmethod",
                               "binddn",
                               "bindpw",
                               "saslmech",
                               "authzid",
                               "filter",
                               "result_attrs",
                               "scope",
                               "usetls",
                               "cipher",
                               "reqcert",
                               "cert",
                               "key",
                               "cacert"):
                        result = self.get(section, opt)
                        
                        if opt in ("host", "result_attrs"):
                            result = self.create_list(result)
                            
                        ldap_cfg[opt] = result
                
                # Do we connect with TLS?
                if ldap_cfg["usetls"].lower() in ("yes", "true", "1"):
                    if ldap_cfg["reqcert"] in ("never",
                                               "allow",
                                               "try",
                                               "demand"):
                        rc = ldap_cfg["reqcert"]
                        if rc == "never":
                            reqcert = ldap.OPT_X_TLS_NEVER
                        elif rc == "allow":
                            reqcert = ldap.OPT_X_TLS_ALLOW
                        elif rc == "try":
                            reqcert = ldap.OPT_X_TLS_TRY
                        elif rc == "demand":
                            reqcert = ldap.OPT_X_TLS_DEMAND

                    ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, reqcert)
                    ldap.set_option(ldap.OPT_X_TLS_CIPHER_SUITE,
                                    ldap_cfg["cipher"])

                    if ldap_cfg["cacert"] is not None:
                        ldap.set_option(ldap.OPT_X_TLS_CACERTFILE,
                                        ldap_cfg["cacert"])
                    if ldap_cfg["cert"] is not None:
                        ldap.set_option(ldap.OPT_X_TLS_CERTFILE,
                                        ldap_cfg["cert"])
                    if ldap_cfg["key"] is not None:
                        ldap.set_option(ldap.OPT_X_TLS_KEYFILE,
                                        ldap_cfg["key"])

                    tls = True
        
                # Are we SASL binding to our servers?
                if ldap_cfg["bindmethod"] == "sasl":
                    mech = ldap_cfg["saslmech"]

                    if mech is not None:
                        if mech.lower() == "digest-md5":
                            auth_tokens = ldap.sasl.digest_md5(
                                                        ldap_cfg["binddn"],
                                                        ldap_cfg["bindpw"])
                        elif mech.lower() == "cram-md5":
                            auth_tokens = ldap.sasl.cram_md5(
                                                        ldap_cfg["binddn"],
                                                        ldap_cfg["bindpw"])
                        elif mech.lower() == "external":
                            auth_tokens = ldap.sasl.external(
                                                        ldap_cfg["authzid"])
                        elif mech.lower() == "gssapi":
                            auth_tokens = ldap.sasl.gssapi(ldap_cfg["authzid"])

                    sasl = True
        
                con = None

                for server in iter(ldap_cfg["host"]):
                    try:
                        con = ldap.initialize(server)
                        if tls:
                            con.start_tls_s()
                        if sasl:
                            con.sasl_interactive_bind_s("", auth_tokens)
                        else:
                            con.simple_bind_s(ldap_cfg["binddn"],
                                              ldap_cfg["bindpw"])
                    except Exception, e:
                        logging.error("LDAP: %s" % e)
                        continue
                    break

                if con is not None:
                    if ldap_cfg["scope"] in ("sub", "subtree"):
                        scope = ldap.SCOPE_SUBTREE
                    elif ldap_cfg["scope"] in ("one", "onelevel"):
                        scope = ldap.SCOPE_ONELEVEL
                    elif ldap_cfg["scope"] in ("base", "exact"):
                        scope = ldap.SCOPE_BASE

                    filter = self.__replace_makro(ldap_cfg["filter"])
                                            
                    rid = con.search(ldap_cfg["base"],
                                     scope,
                                     filter,
                                     ldap_cfg["result_attrs"])
            
                    raw_res = (None, None)
                    raw_res = con.result(rid, True, 60)
                    if raw_res[0] == None:
                        con.abandon(rid)
                        raise Exception("LDAP server timeout reached")

                    # connection established, we have results
                    self.__vars = dict()
                    
                    # we did not receive data from LDAP
                    if raw_res[1] != []:
                        for entry in raw_res[1]:
                            for key, value in entry[1].items():
                                # result attributes might be multi values, but
                                # we only accept the first value.
                                self.__vars[key] = unicode(value[0], "utf-8")
                    else:
                        logging.warning("No LDAP result from server!")
                        raise DataNotFoundException

                    try:    
                        con.unbind()
                    except ldap.LDAPError, e:
                        pass

                if backend == "ldap":
                    self.__eval_options(section, backend="static")
                else:
                    self.__eval_options(section, backend="static_append")
            
            elif backend in ("sql", "sql_append"):
                try:
                    from sqlalchemy.engine import create_engine
                except:
                    raise Exception("python sqlalchemy missing")

                sql_cfg = dict(host = None, query = "", result_attrs = [])
                
                for opt in iter(self.options(section)):
                    if opt in ("host", "result_attrs"):
                        result = self.create_list(self.get(section, opt))
                        sql_cfg[opt] = result

                if self.has_option(section, "query"):
                    query = self.get(section, "query")
                    sql_cfg["query"] = self.__replace_makro(query)
                else:
                    raise Exception("Missing option <query>")
                
                for con in iter(sql_cfg["host"]):
                    try:
                        engine = create_engine(con)
                        connection = engine.connect()
                    except Exception, e:
                        logging.error("SQL: %s" % e)
                        continue
                    
                    result = connection.execute(sql_cfg["query"])
                    for row in result:
                        keys = row.keys()
                        for key in iter(keys):
                            if key in iter(sql_cfg["result_attrs"]):
                                self.__vars[key] = row[key]

                        # Implicit LIMIT 1 here
                        break
                    else:
                        logging.warning("No SQL result from server!")
                        connection.close()
                        raise DataNotFoundException

                    connection.close()
                    
                    break

                if backend == "sql":
                    self.__eval_options(section, backend="static")
                else:
                    self.__eval_options(section, backend="static_append")

            elif backend in ("file", "file_append"):
                for opt in iter(self.options(section)):
                    if opt in ("autoconfig", "autodiscover", "mobileconfig"):
                        tmp = self.get(section, opt)
                        result = self.__expand_vars(tmp)
                        
                        if os.path.exists(result):
                            settings[opt] = result

                if backend == "file":
                    self.__eval_options(section, backend="static")
                else:
                    self.__eval_options(section, backend="static_append")

            elif backend in ("script", "script_append"):
                if self.has_option(section, "script"):
                    script_args = self.get(section, "script")
                else:
                    raise Exception("Missing option <script>")

                if self.has_option(section, "result_attrs"):
                    result_attrs = self.create_list(self.get(section,
                                                             "result_attrs"))
                else:
                    raise Exception("Missing option <result_attrs>")

                seperator = None
                if self.has_option(section, "seperator"):
                    seperator = self.get(section, "seperator")

                cmd = shlex.split(self.get(section, "script"))
                for i, item in enumerate(cmd):
                    cmd[i] = self.__replace_makro(item)

                stdout_fd = sys.__stdout__.fileno()
                pipe_in, pipe_out = os.pipe()
                pid = os.fork()

                if pid == 0:
                    # child
                    os.close(pipe_in)
                    os.dup2(pipe_out, stdout_fd)

                    os.execvp(cmd[0], cmd)

                    raise Exception("ERROR in execvp()" )
                elif pid > 0:
                    # parent
                    os.close(pipe_out)
                    recv = os.read(pipe_in, 1024)

                    result = os.waitpid(pid, 0)

                # check return code
                if result[1] != 0:
                    raise Exception("ERROR while calling script",
                                    result,
                                    recv.strip())

                if len(recv) == 0:
                     logging.warning("No result from script!")
                     raise DataNotFoundException

                result = recv.strip().split(seperator, len(result_attrs))

                for i in range(min(len(result_attrs), len(result))):
                    self.__vars[result_attrs[i]] = result[i].strip()

                if backend == "script":
                    self.__eval_options(section, backend="static")
                else:
                    self.__eval_options(section, backend="static_append")
                            
            ### backends beyond this line do not have a follow option ###

            elif backend == "filter":
                if self.has_option(section, "section_filter"):
                    tmp = self.create_list(self.get(section, "section_filter"))
                    special_opts = tmp
                    
                    got_data = False
                    
                    for special_opt in iter(special_opts):
                        if self.has_option(section, special_opt):
                            cmd = shlex.split(self.get(section, special_opt)) 
                            for i, item in enumerate(cmd):
                                cmd[i] = self.__replace_makro(item)

                            stdout_fd = sys.__stdout__.fileno()
                            
                            pipe_in, pipe_out = os.pipe()
                            
                            pid = os.fork()
                            if pid == 0:
                                # child
                                os.close(pipe_in)
                                os.dup2(pipe_out, stdout_fd)
                                
                                os.execvp(cmd[0], cmd)

                                raise Exception("ERROR in execvp()")
                            elif pid > 0:
                                # parent
                                os.close(pipe_out)
                                recv = os.read(pipe_in, 1024)
                                    
                                result = os.waitpid(pid, 0)
                            else:
                                continue
                            
                            # check return code
                            if result[1] != 0:
                                raise Exception("ERROR while calling filter",
                                                result,
                                                recv.strip())
                            else:
                                new_emailaddress = recv.strip()

                            # The result seems not to be an email address
                            if '@' not in new_emailaddress:
                                continue

                            if self.debug:
                                logging.debug("Email address from filter: %s"
                                              % new_emailaddress)
                            
                            got_data = True
                            
                            # we replace our search_domain 
                            self.__search_domain = special_opt
                            self.__emailaddress = new_emailaddress

                            # recurse again, because we now have a new section
                            # that we need to scan
                            self.__eval_options(special_opt)
                            
                            # we already got a result. Do not continue!
                            break
                
                    if not got_data:
                        raise DataNotFoundException
            
            elif backend == "global":
                if self.has_section("global"):
                    self.__eval_options("global")
                    settings = self.__replace_makro(settings)
                else:
                    raise Exception("Missing section 'global'")

            else:
                raise Exception("Unknown backend specified")

    def __service(self, section, service):
        # This method only stores meta information. The results depend on
        # the MUA xml schema specification and is defined in the Viewer-class

        proto_settings = OrderedDict()

        if self.getboolean(section, service) == True:
            if self.has_option(section, service + "_server"):
                opt = service + "_server"
                result = self.__expand_vars(self.get(section, opt))

                proto_settings[opt] = result
                
            if self.has_option(section, service + "_port"):
                opt = service + "_port"
                result = self.__expand_vars(self.get(section, opt))
                
                proto_settings[opt] = result
                
            if self.has_option(section, service + "_encryption"):
                opt = service + "_encryption"
                result = self.__expand_vars(self.get(section, opt))
                
                if result.lower() == "none":
                    result = "none"
                elif result.lower() == "ssl":
                    result = "ssl"
                elif result.lower() == "starttls":
                    result = "starttls"
                elif result.lower() == "auto":
                    result = "auto"
                    
                proto_settings[opt] = result
                
            if self.has_option(section, service + "_auth"):
                opt = service + "_auth"
                result = self.__expand_vars(self.get(section, opt))
                
                if result.lower() == "plaintext":
                    result = "cleartext"
                elif result.lower() == "encrypted":
                    result = "encrypted"
                elif result.lower() == "ntlm":
                    result = "ntlm"
                elif result.lower() == "gssapi":
                    result = "gssapi"
                elif result.lower() == "client-ip-address":
                    result = "client-ip-address"
                elif result.lower() == "tls-client-cert":
                    result = "tls-client-cert"
                elif result.lower() == "none":
                    result = "none"
                elif result.lower() == "smtp-after-pop":
                    if service == "smtp":
                        result = "smtp-after-pop"
                # TODO: we allow bogus keys/values.
                
                proto_settings[opt] = result

            if self.has_option(section, service + "_auth_identity"):
                opt = service + "_auth_identity"
                result = self.__expand_vars(self.get(section, opt))
                proto_settings[opt] = self.__replace_makro(result)
            else:
                emaillocalpart = self.__replace_makro("%u")
                proto_settings[service + "_auth_identity"] = emaillocalpart
            
            if self.has_option(section, service + "_expiration_date"):
                opt = service + "_expiration_date"
                result = self.__expand_vars(self.get(section, opt))
                dt = parser.parse(result, fuzzy=True)
                proto_settings[opt] = dt.strftime("%Y%m%d")
                
            if self.has_option(section, service + "_refresh_ttl"):
                opt = service + "_refresh_ttl"
                result = self.get(section, opt)
                proto_settings[opt] = result

            if service == "smtp":
                if self.has_option(section, service + "_author"):
                    opt = service + "_author"
                    author = self.__expand_vars(self.get(section, opt))

                    if author == "%s":
                        proto_settings[opt] = self.__emailaddress
                    
                if self.has_option(section, service + "_default"):
                    try:
                        opt = service + "_default"
                        tmp = self.__expand_vars(self.get(section, opt))
                        if tmp.lower() in ("yes", "true", "1"):
                            result = "Yes"
                        else:
                            result = "No"
                        proto_settings[opt] = result
                    except ValueError:
                        pass

        return proto_settings
    
    def create_list(self, value):
        result = value.split()
        
        if len(result) > 1:
            for i, item in enumerate(result):
                result[i] = item.split(",")[0]
                
        return result
    
    def __replace_makro(self, expression):
        if "%u" in expression:
            user = self.__emailaddress.split("@")[0]
            expression = expression.replace("%u", user)
        if "%d" in expression:
            domain = self.__search_domain
            expression = expression.replace("%d", domain)
        if "%s" in expression:
            email = self.__emailaddress
            expression = expression.replace("%s", email)

        return expression

    def __expand_vars(self, expression):
        # do we have some dynamic variables?
        if len(self.__vars) == 0:
            return expression
        
        def repl(mobj):
            if self.__vars.has_key(mobj.group(1)):
                result = self.__vars[mobj.group(1)]
                
                if mobj.group(2) is not None:
                    macro = mobj.group(2)[1:]
                    
                    if self.debug:
                        logging.debug("__expand_vars()->macro=%s" % macro)
                        
                    if "@" in result:
                        if macro == "%u":
                            return result.split("@")[0]
                        if macro == "%d":
                            return result.split("@")[1]
                        if macro == "%s":
                            return result
                        
                        result = result.split("@")[1]
                        
                    # now the macro may only be part of a FQDN hostname
                    if "." in result:
                        dcs = result.split(".")
                        if macro in ("%1", "%2", "%3", "%4", "%5",
                                     "%6", "%7", "%8", "%9"):
                            i = int(macro[1])
                            if len(dcs) < i:
                                return ""
                            
                            return dcs[-i]
                    
                return result
            else:
                # we always must expand variables. Even if it is the empty
                # string
                return ""

        result = re.sub(r"\$\{(\w+)(:%[sud1-9])?\}",
                        repl,
                        unicode(expression, "utf-8"),
                        re.UNICODE)
     
        if self.debug:
            logging.debug("__expand_vars()->result=%s" % result)
            
        return result
        
    def __find_section(self, domain):
        l = self.sections()
        for section in iter(l):
            if section.lower() == domain.lower():
                return section

        raise NoSectionError(domain)
        
    def get_provider(self):
        return self.__automx["provider"]
    provider = property(fget=get_provider)

    def get_domain(self):
        return self.__domain
    domain = property(fget=get_domain)

    def get_cn(self):
        return self.__cn
    cn = property(fget=get_cn)

    def get_password(self):
        return self.__password
    password = property(fget=get_password)
    
    def get_emailaddress(self):
        return self.__emailaddress
    emailaddress = property(fget=get_emailaddress)
    
    
class Memcache(object):
    
    def __init__(self, config, environ):
        self.__config = config
        self.__environ = environ
                
        # Memcache usage is optional
        self.__has_memcache = True

        self.__found = False
        self.__client = None
        self.__current = 0
        
        try:
            self.__mc = memcache.Client([config.get("automx", "memcache")])
        except ValueError, e:
            logging.warning("Memcache misconfigured: ", e)
            self.__has_memcache = False

    def counter(self):
        return self.__current

    def set_client(self):
        if not self.__has_memcache:
            return

        if self.__is_trusted_network():
            return

        if self.__config.has_option("automx", "memcache_ttl"):
            try:
                ttl = self.__config.getint("automx", "memcache_ttl")
            except ValueError, e:
                logging.warning("Memcache <memcache_ttl>, using default: ", e)
                ttl = 600
        else:
            ttl = 600

        if self.__found:
            self.__current += 1

        self.__mc.set(self.__client, self.__current, time=ttl)
                                                            
    def allow_client(self):
        if not self.__has_memcache:
            return True

        self.__client = self.__environ["REMOTE_ADDR"]

        if self.__is_trusted_network():
            return True
        
        if self.__config.has_option("automx", "client_error_limit"):
            try:
                limit = self.__config.getint("automx", "client_error_limit")
            except ValueError, e:
                logging.warning("Memcache <client_error_limit>, "
                                "using default: ", e)
                limit = 20
        else:
            limit = 20
        
        result = self.__mc.get(self.__client)

        if result is not None:
            self.__found = True
            self.__current = result

        if self.__current < limit:
            return True
        else:
            self.set_client()
            return False

    def __is_trusted_network(self):
        if self.__config.has_option("automx", "rate_limit_exception_networks"):
            networks = self.__config.get("automx",
                                        "rate_limit_exception_networks")
            networks = self.__config.create_list(networks)
        else:
            networks = ("127.0.0.1", "::1/128")
        
        for network in iter(networks):
            if IPAddress(self.__client) in IPNetwork(network):
                return True
        
        return False

# vim: expandtab ts=4 sw=4