This file is indexed.

/usr/bin/dput is in dput 0.9.6.2ubuntu1.

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

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
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
#!/usr/bin/python
# dput - debian package upload tool
# (c) 2000,2001,2002,2003,2004,2005 Christian Kurz <shorty@debian.org>
# (c) 2006,2007,2008 Thomas Viehmann <tv@beamnet.de>
# (c) 2008,2009 Y Giridhar Appaji Nag <appaji@debian.org>
#
# 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 2 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, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import os, sys, string, re, glob, signal
import pwd, stat, rfc822
from hashlib import md5, sha1

# Now import our modules
import ConfigParser

sys.path.insert(0,'/usr/share/dput/helper')
import dputhelper

dput_version = "dput 0.9.6"

config = None
upload_methods = {}
files_to_upload = []
simulate = unsigned_upload = delay_upload = 0
debug = dinstall = check_only = 0
config_file = ''

dput_modules = ('')

# Function to import files from the /usr/share/dput and make them available
# to this script
def import_upload_functions():
    files_to_import = glob.glob('/usr/share/dput/*.py')
    for file in files_to_import:
        if debug: print "D: File: %s" % file
        base = os.path.basename(file)
        if len(dput_modules) != 0:
            if base not in dput_modules:
                base = os.path.splitext(base)[0]
        else:
            base = os.path.splitext(base)[0]
        if debug: print "D: Base: %s" % base
        d = {}
        try:
            exec open(file) in d
            if debug: print "Imported: %s" % file
        except IOError:
            print "Couldn't import %s" % file
            continue
        register_upload_function(base, d['upload'])

# add function to upload_methods dictionary using key of name
def register_upload_function(name, function):
    global upload_methods

    upload_methods[name] = function

# parse the changes file
def parse_changes(chg_fd):
    check = chg_fd.read(5)
    if check != '-----':
        chg_fd.seek(0)
    else: # found a PGP header, gonna ditch the next 3 lines
        chg_fd.readline() # eat the rest of the line
        chg_fd.readline() # Hash: SHA1
        chg_fd.readline() # empty line
    if not chg_fd.readline().find('Format') != -1:
        chg_fd.readline()
    changes = rfc822.Message(chg_fd)
    for a in changes.dict['files'].split('\n'):
      if len(a.split()) != 5:
        print >> sys.stderr, "Invalid Files line in .changes:\n  %s"%a
        sys.exit(1)
    return changes

# read configs in this order:
#   if specified on the command line, only read extra_config
#   otherwise, read /etc/dput.cf then ~/.dput.cf
# the config parser will layer values
def read_configs(extra_config, debug):
    global config

    config = ConfigParser.ConfigParser()

    config.set('DEFAULT', 'login', 'username')
    config.set('DEFAULT', 'method', 'scp')
    config.set('DEFAULT', 'hash', 'md5')
    config.set('DEFAULT', 'allow_unsigned_uploads', '0')
    config.set('DEFAULT', 'allow_dcut', '0')
    config.set('DEFAULT', 'distributions', '')
    config.set('DEFAULT', 'allowed_distributions', '')
    config.set('DEFAULT', 'run_lintian', '0')
    config.set('DEFAULT', 'run_dinstall', '0')
    config.set('DEFAULT', 'check_version', '0')
    config.set('DEFAULT', 'scp_compress', '0')
    config.set('DEFAULT', 'default_host_main', '')
    config.set('DEFAULT', 'post_upload_command', '')
    config.set('DEFAULT', 'pre_upload_command', '')
    config.set('DEFAULT', 'ssh_config_options', '')
    config.set('DEFAULT', 'passive_ftp', '1')
    config.set('DEFAULT', 'progress_indicator', '0')
    config.set('DEFAULT', 'delayed', '')

    if extra_config:
        config_files = (extra_config,)
    else:
        config_files = ('/etc/dput.cf', os.path.expanduser("~/.dput.cf"))
    fd = None
    for config_file in config_files:
        try:
            fd = open(config_file)
        except IOError, e:
            if debug:
                print >> sys.stderr, '%s: %s, skipping' % (e[1], config_file)
            continue
        if debug: print "D: Parsing Configuration File %s" % config_file
        try:
            config.readfp(fd)
        except ConfigParser.ParsingError, e:
            print >> sys.stderr, "Error parsing config file:\n%s"%str(e)
            sys.exit(1)
        fd.close()
    if fd == None:
        print >> sys.stderr, 'Error: Could not open any configfile, tried %s' % \
              (', '.join(config_files))
        sys.exit(1)
    # only check for fqdn and incoming dir, rest have reasonable defaults
    error = 0
    for section in config.sections():
      if config.get (section,'method') == 'local':
        config.set(section,'fqdn','localhost')
      if not config.has_option(section, 'fqdn') and \
             config.get(section, 'method') != 'local':
        print >> sys.stderr, 'Config error: %s must have a fqdn set' % section
        error = 1
      if not config.has_option(section, 'incoming'):
        print >> sys.stderr, 'Config error: %s must have an incoming directory set' % \
              section
        error = 1
    if error:
      sys.exit(1)
    
# Convert a hex string into readable characters.
hexStr = string.hexdigits
def hexify_string(string):
    char = ''
    for c in string:
        char = char + hexStr[(ord(c) >> 4) & 0xF] + hexStr[ord(c) & 0xF]
    return char

# Function to generatea checksum for a file.
# Currently supports md5, sha1. ripemd may come in the future.
def checksum_test(filename,hash):
    try:
        file_to_test = open(filename, 'r')
    except IOError:
        print "Can't open %s" % filename
        sys.exit(1)

    if hash == 'md5':
        hash_type = md5
    else:
        hash_type = sha1

    check_obj = hash_type()

    while 1:
        data = file_to_test.read(65536)
        if len(data) == 0: break
        check_obj.update(data)

    file_to_test.close()
    checksum = hexify_string(check_obj.digest())

    return checksum

# Verify the GnuPG signature on a file.
def check_signature(filename):
    if os.access(filename, os.R_OK):
        if os.access("/usr/bin/gpg", os.R_OK):
            stream = os.popen("/usr/bin/gpg --status-fd 1 --verify --batch %s" % filename).read()
            if stream.count('[GNUPG:] GOODSIG'):
                print "Good signature on %s." % filename
            elif stream.count('[GNUPG:] BADSIG'):
                print "Bad signature on %s." % filename
                sys.exit(1)
            elif stream.count('[GNUPG:] ERRSIG'):
                print "Error verifying signature on %s." % filename
                sys.exit(1)
            elif stream.count('[GNUPG:] NODATA'):
                print "No signature on %s." % filename
                sys.exit(1)
            else:
                print "Error in finding signature verification status."
        else:
            print "Can't verify signature on %s without GnuPG" % filename
            print "If you are still using PGP, please read this:"
            print "http://www.gnupg.org/gph/en/pgp2x.html"
            sys.exit(1)
    else:
        print "Can't read %s" % filename
        sys.exit(1)

# Check if this is a binary_upload only or not.
def check_upload_variant(changes, debug):
    binary_upload = 0
    if changes.dict.has_key('architecture'):
        arch = changes.dict['architecture']
        if debug: print "D: Architecture: %s" % arch
        if arch.find('source') < 0:
            if debug:
                print "D: Doing a binary upload only."
            binary_upload = 1
    return binary_upload

# Check the signature on the two files given via function call.
def verify_signature(host, changes_file, dsc_file, check_only, debug,
                     unsigned_upload, binary_upload):

    if debug:
        print "D: .changes-File: %s" % changes_file
        print "D: .dsc-File: %s" % dsc_file
    if ((check_only or config.getboolean(host, 'allow_unsigned_uploads') == 0)
        and unsigned_upload == 0):
        print "Checking signature on .changes"
        check_signature(changes_file)
        if not binary_upload:
            print "Checking signature on .dsc"
            check_signature(dsc_file)

# Check if an orig.tar.gz or tar.gz has to be included in the package or not.
def source_check(changes, debug):
    include_orig = include_tar = 0
    if changes.dict.has_key('version'):
        version = changes.dict['version']
        if debug: print "D: Package Version: %s" % version
        # versions with a dash in them are for non-native only
        if version.find('-') == -1: # debian native
            include_tar = 1
        else:
            if version.find(':') > 0:
                if debug: print "D: Epoch found"
                epoch, version = version.split(':', 1)
            pos = version.rfind('-')
            upstream_version = version[0:pos]
            debian_version = version[pos+1:]
            if debug:
                print "D: Upstream Version: %s" % upstream_version
                print "D: Debian Version: %s" % debian_version
            if debian_version == '0.1' or debian_version == '1' \
               or debian_version == '1.1' or debian_version == '0ubuntu1':
                include_orig = 1
            else:
                include_tar = 1
    return (include_orig, include_tar)

# Run some tests on the files before uploading them to 
# verify that they are in good shape.
def verify_files(path, filename, host, check_only, check_version,
                 unsigned_upload, debug):
    file_seen = include_orig_tar_gz = include_tar_gz = binary_only = 0

    name_of_file = filename
   
    change_file = os.path.join(path, name_of_file)

    if debug:
        print "D: Validating contents of changes file %s" % change_file
    try:
        chg_fd = open(change_file, 'r')
    except IOError:
        print "Can't open %s" % change_file
        sys.exit(1)
    changes = parse_changes(chg_fd)
    chg_fd.close

    # Find out if it's a binary only upload or not
    binary_upload = check_upload_variant(changes, debug)

    if binary_upload:
        dsc_file = ''
    else:
        dsc_file = None
        for file in changes.dict['files'].split('\n'):
            filename = string.split(file)[4] # filename only
            if filename.find('.dsc') != -1:
                if debug:
                    print "D: dsc-File: %s" % filename
                dsc_file = os.path.join(path, filename)
        if not dsc_file:
          print >> sys.stderr, "Error: no dsc file found in sourceful upload"
          sys.exit(1)

    # Run the check to verify that the package has been tested.
    if config.getboolean(host, 'check_version') == 1 or check_version:
        version_check (path, changes, debug)

    # Verify the signature of the maintainer
    verify_signature(host, change_file, dsc_file, check_only, debug,\
        unsigned_upload, binary_upload)

    # Check the sources
    (include_orig_tar_gz, include_tar_gz) = source_check(changes, debug)

    # Check md5sum and the size
    file_list = changes.dict['files'].split('\n')
    hash_to_use = config.get('DEFAULT','hash')
    for line in file_list:
        (check_sum, size, section, priority, file) = line.split()
        file_to_upload = os.path.join(path, file)
        if debug:
            print "D: File to upload: %s" % file_to_upload
        if checksum_test(file_to_upload,hash_to_use) != check_sum:
            if debug:
                print "D: Checksum from .changes: %s" % check_sum
                print "D: Generated Checksum: %s" % \
                      checksum_test(file_to_upload,hash_to_use)
            print "Checksum doesn't match for %s" % file_to_upload
            sys.exit(1)
        else:
            if debug: print "D: Checksum for %s is fine" % file_to_upload
        if os.stat(file_to_upload)[stat.ST_SIZE] != int(size):
            if debug:
                print "D: size from .changes: %s" % size
                print "D: calculated size: %s" % \
                    os.stat(file_to_upload)[stat.ST_SIZE]
            print "size doesn't match for %s" % file_to_upload
        
        files_to_upload.append(file_to_upload)
    
    # Check filenames
    for file in files_to_upload:
        if file[-12:] == '.orig.tar.gz' and not include_orig_tar_gz:
            if debug:
                print "D: Filename: %s" % file
                print "D: Suffix: %s" % file[-12:]
            print "Package includes an .orig.tar.gz file although the debian revision suggests"
            print "that it might not be required. Multiple uploads of the .orig.tar.gz may be"
            print "rejected by the upload queue management software."
        elif file[-7:] == '.tar.gz' and not include_tar_gz \
            and not include_orig_tar_gz:
            if debug:
                print "D: Filename: %s" % file
                print "D: Suffix: %s" % file[-7:]
            print "Package includes a .tar.gz file although the version suggests that it might"
            print "not be required. Multiple uploads of the .tar.gz may be rejected by the"
            print "upload queue management software."

    distribution = changes.get('distribution')
    allowed_distributions = config.get(host, 'allowed_distributions')
    if distribution and allowed_distributions:
        if debug:
            print "D: Checking: distribution %s matches %s" % (distribution, allowed_distributions)
        if not re.match(allowed_distributions, distribution):
            raise dputhelper.DputUploadFatalException("Error: uploading files for distribution %s to %s not allowed."%(distribution, host))

    if debug:
        print "D: File to upload: %s" % change_file
    files_to_upload.append(change_file)

# Print the configuration and exit.
def print_config(config, debug):
    print
    config.write(sys.stdout)
    print

# Write a logfile of the upload and call it .upload
def create_upload_file(package, host, path, files_to_upload, debug):
    base = os.path.splitext(package)[0] # only need first part
    logfile_name = os.path.join(path, base + '.' + host + '.upload')
    if config.get(host, 'method') == 'local':
        fqdn = 'localhost'
    else:
        fqdn = config.get(host, 'fqdn')
    if debug:
        print "D: Writing logfile: %s" % logfile_name
    try:
        if os.access(logfile_name, os.R_OK):
            logfile_fd = open(logfile_name, 'a')
        else:
            logfile_fd = open(logfile_name, 'w')
    except IOError:
        print >> sys.stderr, "Could not write %s"%logfile_name
        sys.exit(1)

    for file in files_to_upload:
        entry_for_logfile = 'Successfully uploaded ' + os.path.basename(file) + \
            ' to ' + fqdn + ' for ' + host + '.\n'
        logfile_fd.write(entry_for_logfile)
    logfile_fd.close()
        
# Run lintian on the changes file and stop if it finds errors.
def run_lintian_test(changes_file):
    if os.access(changes_file, os.R_OK):
        if os.access("/usr/bin/lintian", os.R_OK):
            old_signal = signal.signal(signal.SIGPIPE, signal.SIG_DFL)
            print "Package is now being checked with lintian."
            if dputhelper.spawnv(os.P_WAIT, "/usr/bin/lintian",
                  ['lintian', '-i', changes_file]):
                print 
                print "Lintian says this package is not compliant" +\
                    "with the current policy."
                print "Please check the current policy and your package."
                print "Also see lintian documentation about overrides."
                sys.exit(1)
            else:
                signal.signal(signal.SIGPIPE, old_signal)
                return 0
        else:
            print "lintian is not installed, skipping package test."
    else:
        print "Can't read %s" % changes_file
        sys.exit(1)
    
# Guess the host where the package should be uploaded to. This is based
# on information from the changes file.
def guess_upload_host(path, filename):
    non_us = 0
    distribution = ""
    dist_re = re.compile(r'^Distribution: (.*)')

    name_of_file = filename
    changes_file = os.path.join(path, name_of_file)
    
    try:
        changes_file_fd = open(changes_file, 'r')
    except IOError:
        print "Can't open %s" % changes_file
        sys.exit(1)
    lines = changes_file_fd.readlines()
    for line in lines:
        match = dist_re.search(line)
        if match:
            distribution = match.group(1)

    # Try to guess a host based on the Distribution: field
    if distribution:
        for section in config.sections():
            host_dists = config.get(section, 'distributions')
            if not host_dists:
                continue
            for host_dist in host_dists.split(','):
                if distribution == host_dist.strip():
                    if debug:
                        print "D: guessing host %s based on distribution %s" % (section, host_dist)
                    return section

    if len(config.get('DEFAULT', 'default_host_main')) != 0:
      print "Trying to upload package to %s" % config.get('DEFAULT',
                                                     'default_host_main')
      return config.get('DEFAULT', 'default_host_main')
    else:
      print "Trying to upload package to ftp-master (ftp.upload.debian.org)"
      return "ftp-master"

# Run dinstall in test-mode and present the output to the user so that
# he can see if his package would be installed or not.
def dinstall_caller(filename, host, login, incoming, debug):
    command = ['ssh', '%s@%s' % (login, config.get(host, 'fqdn')),
           'cd', '%s' % incoming,
           ';', 'dinstall', '-n', '%s' % filename]
    if debug:
        print "D: Logging into %s@%s:%s" % (login, host, incoming)
        print "D: dinstall -n %s" % filename
    if config.getboolean(host, 'run_dinstall') == 1 or dinstall:
        if dputhelper.spawnv(os.P_WAIT, '/usr/bin/ssh', command):
            print "Error occured while trying to connect, or while " +\
                  "attempting to run dinstall."
            sys.exit(1)

# Check if the caller has installed the package also on his system
# for testing purposes before uploading it. If not, we reject the upload.
def version_check(path, changes, debug):
    files_to_check = []

    # Get arch
    dpkg_stdin,dpkg_stdout,dpkg_stderr = os.popen3('dpkg --print-architecture')
    dpkg_stdin.close()
    dpkg_architecture = dpkg_stdout.read().strip()
    dpkg_stdout.close()
    dpkg_stderr_output = dpkg_stderr.read()
    dpkg_stderr.close()
    if debug and dpkg_stderr_output:
      print "D: dpkg-architecture stderr output:",repr(dpkg_stderr_output)
    if debug:
      print "D: detected architecture: '%s'"%dpkg_architecture
    
    # Get filenames of deb files:
    for file in changes.dict['files'].split('\n'):
        filename = os.path.join(path, string.split(file)[4])
        if filename.endswith('.deb'):
            if debug:
                print "D: Debian Package: %s" % filename
            dpkg_stdin,dpkg_stdout,dpkg_stderr = os.popen3('dpkg --field %s' % filename)
            dpkg_stdin.close()
            dpkg_output = rfc822.Message(dpkg_stdout)
            dpkg_stdout.close()
            dpkg_stderr_output = dpkg_stderr.read()
            dpkg_stderr.close()
            if debug and dpkg_stderr_output:
              print "D: dpkg stderr output:",repr(dpkg_stderr_output)
            if dpkg_architecture and dpkg_output['architecture'] not in ['all',dpkg_architecture]:
              if debug:
                print "D: not install-checking %s due to arch mismatch"%filename
            else:
              package_name = dpkg_output['package']
              version_number = dpkg_output['version']
              if debug: print "D: Package to Check: %s" % package_name
              if debug: print "D: Version to Check: %s" % version_number
              files_to_check.append((package_name,version_number))
    
    for file,version_to_check in files_to_check:
        if debug: print "D: Name of Package: %s" % file
        dpkg_stdin,dpkg_stdout,dpkg_stderr = os.popen3('dpkg -s %s' % file)
        dpkg_stdin.close()
        dpkg_output = rfc822.Message(dpkg_stdout)
        dpkg_stdout.close()
        dpkg_stderr_output = dpkg_stderr.read()
        dpkg_stderr.close()
        if debug and dpkg_stderr_output:
            print "D: dpkg stderr output:",repr(dpkg_stderr_output)
        if dpkg_output.has_key('version'):
            installed_version = dpkg_output.dict['version']
            if debug: print "D: Installed-Version: %s" % installed_version
            if debug: print "D: Check-Version: %s" % \
               version_to_check
            if installed_version != version_to_check:
              print "Package to upload is not installed, but it appears " +\
                    "you have an older version installed."    
        else:
          print "Uninstalled Package. Test it before uploading it."
          sys.exit(1)

# Run a command that the user-defined in the config_file.
def execute_command(host, debug, type):
    lookup_command = type + '_upload_command'
    if debug: print "D: Command: %s" % config.get(host, lookup_command)
    if os.system(config.get(host, lookup_command)):
        raise dputhelper.DputUploadFatalException("Error: %s upload command failed."%type)

# Open a Logfile and check if the user already put
# this package on the specified host or not:
def check_upload_logfile(changes_file, host, check_only,
                         call_lintian, force_upload, debug):
    uploaded = 0
    upload_logfile = changes_file[:-8] + '.' + host + '.upload'
    if not check_only and not force_upload:
        if not os.path.exists(upload_logfile):
            return
        try:
            fd_logfile = open(upload_logfile)
        except IOError:
            print "Couldn't open %s" % upload_logfile
            sys.exit(1)
        for line in fd_logfile.readlines():
            if config.get(host, 'method') == 'local':
                fqdn = 'localhost'
            else:
                fqdn = config.get(host, 'fqdn')
            if line.find(fqdn) != -1:
                uploaded = 1
        if uploaded:
            print "Package has already been uploaded to %s on %s" % (host, fqdn)
            print "Nothing more to do for %s" % changes_file
            sys.exit(0)

# Help Message to print
USAGE = """Usage: dput [options] [host] <package(s).changes>
 Supported options (see man page for long forms):
   -c: Config file to parse.
   -d: Enable debug messages.
   -D: Run dinstall after upload.
   -e: Upload to a delayed queue. Takes an argument from 0 to 15.
   -f: Force an upload.
   -h: Display this help message.
   -H: Display a list of hosts from the config file.
   -l: Run lintian before upload.
   -U: Do not write a .upload file after uploading.
   -o: Only check the package.
   -p: Print the configuration.
   -P: Use passive mode for ftp uploads.
   -s: Simulate the upload only.
   -u: Don't check GnuPG signature.
   -v: Display version information.
   -V: Check the package version and then upload it.
"""

# Main function, no further comment needed. :)
def main():
    global simulate 
    global debug
    global check_only
    global dinstall
    global unsigned_upload
    global config_file
    global delay_upload

    check_version = config_print = force_upload = \
    call_lintian = no_upload_log = config_host_list = 0
    ftp_passive_mode = 0
    preferred_host = ''

    # Parse Command Line Options.
    (opts, args) = dputhelper.getopt(sys.argv[1:],
                            'c:dDe:fhHlUopPsuvV',
                            ['debug', 'dinstall', 'check-only',
                            'check-version', 'config=', 'force', 'help',
                            'host-list', 'lintian', 'no-upload-log',
                            'passive', 'print', 'simulate', 'unchecked',
                            'delayed=', 'version'])
    for option, arg in opts:
        if option in ('-h', '--help'):
            print USAGE
            return
        elif option in ('-v', '--version'):
            print dput_version
            return
        elif option in ('-d', '--debug'):
            debug = 1
        elif option in ('-D', '--dinstall'):
            dinstall = 1
        elif option in ('-c', '--config'):
            config_file = arg   
        elif option in ('-f', '--force'):
            force_upload = 1
        elif option in ('-H', '--host-list'):
            config_host_list = 1
        elif option in ('-l', '--lintian'):
            call_lintian = 1
        elif option in ('-U', '--no-upload-log'):
            no_upload_log = 1
        elif option in ('-o', '--check-only'):
            check_only = 1
        elif option in ('-p', '--print'):
            config_print = 1
        elif option in ('-P', '--passive'):
            ftp_passive_mode = 1
        elif option in ('-s', '--simulate'):
            simulate = 1
        elif option in ('-u', '--unchecked'):
            unsigned_upload = 1
        elif option in ('-e', '--delayed'):
            if arg in map(str, range(16)):
                delay_upload = arg
            else:
                print "Incorrect delayed argument, dput only understands 0 to 15."
                sys.exit(1)
        elif option in ('-V', '--check_version'):
            check_version = 1           
  
    # Always print the version number in the debug output
    # so that in case of bugreports, we know which version
    # the user has installed
    if debug: print "D: %s" % dput_version
    
    # Try to get the login from the enviroment
    if os.environ.has_key('USER'):
        login = os.environ['USER']
        if debug: print "D: Login: %s" % login
    else:
        print "$USER not set, will use login information."
        # Else use the current username
        login = pwd.getpwuid(os.getuid( ))[0]
        if debug:
           print "D: User-ID: %s" % os.getuid()
           print "D: Login: %s" % login

    # Start Config File Parsing.
    read_configs(config_file, debug)

    if config_print:
        print_config(config, debug)
        sys.exit(0)

    if config_host_list:
        print
        print "Default Method: %s" % config.get('DEFAULT','method')
        print
        for section in config.sections():
            distributions = ""
            if config.get(section,'distributions'):
                distributions = ", distributions: %s" % \
                        config.get(section,'distributions')
            print "%s => %s  (Upload method: %s%s)" % (section, \
                config.get(section,'fqdn'), config.get(section,'method'), \
                distributions)
        print
        sys.exit(0)

    # Process further command line options.
    if len(args) == 0:
        print "No package or host has been provided, see dput -h"
        sys.exit(0)
    elif len(args) == 1 and not check_only:
        package_to_upload = args[0:]
    else:
        if ':' in args[0]:
            args[0], hostArgument = args[0].split(":", 1)
        else:
            hostArgument = ""

        if config.has_section(args[0]):
            config.set(args[0], args[0], hostArgument)
        else:
            # Let the code below handle this as it is sometimes okay (ie. -o)
            pass
        
        if not check_only:
            if debug:
                print "D: Checking if a host was named on the command line."
            if config.has_section(args[0]):
                if debug:
                    print "D: Host %s found in config" % args[0]
                # Host was also named, so only the rest will be a list
                # of packages to upload.
                preferred_host = args[0]
                package_to_upload = args[1:]
            elif not config.has_section(args[0]) and not args[0].endswith('.changes'):
                print >> sys.stderr, "No host %s found in config" % args[0]
                if args[0]=='gluck_delayed':
                    print >> sys.stderr, """
   The delayed upload queue has been moved back to
   ftp-master (aka ftp.upload.debian.org)."""
                sys.exit(1)
            else:
                if debug:
                    print "D: No host named on command line."
                # Only packages have been named on the command line.
                preferred_host = '' 
                package_to_upload = args[0:]
        else:
            if debug:
                print "D: Checking for the package name."
            if config.has_section(args[0]):
                print "D: Host %s found in config." % args[0]
                preferred_host = args[0]
                package_to_upload = args[1:]
            elif len(args) > 1:
                print "D: No host %s found in config" % args[0]
                package_to_upload = args[1:]
            else:
                print "D: No host specified."
                package_to_upload = args[0:]

    # Now Import the Upload functions
    import_upload_functions()

    # Run the same checks for all packages that have been given on
    # the command line
    for package_name in package_to_upload:
        # Check that a .changes file was given on the command line 
        # and no matching .upload file exists.
        if package_name[-8:] != '.changes':
            print "Not a .changes file."
            print "Please select a .changes file to upload."
            print "Tried to upload: %s" % package_name
            sys.exit(1)
        files_to_upload[:] = []

        # Construct the package name for further usage.
        path, name_of_package = os.path.split(package_name)
        if path == '':
            path = os.getcwd()
    
        # Define the host to upload to.
        if preferred_host == '':
            host = guess_upload_host(path, name_of_package)
        else:
            host = preferred_host
        
        if not config.has_section(host):
            print "E: No host %s found in config" % host
            sys.exit(1)
        
        # Check if we already did this upload or not
        check_upload_logfile(package_name, host, check_only,
                             call_lintian, force_upload, debug)

        # Run the change file tests.
        verify_files(path, name_of_package, host, check_only, check_version,
                     unsigned_upload, debug)

        # Run the lintian test if the user asked us to do so.
        if (call_lintian or
            config.getboolean(host, 'run_lintian') == 1):
            run_lintian_test(os.path.join(path, name_of_package))
        elif check_only:
            print "Warning: The option -o does not automatically include "
            print "a lintian run any more. Please use the option -ol if "
            print "you want to include running lintian in your checking."

        # don't upload, skip to the next item
        if check_only:
            print "Package checked by dput."
            continue

        # Pre-Upload Commands
        if len(config.get(host, 'pre_upload_command')) !=0:
            type = 'pre'
            execute_command(host, debug, type)

        # Check the upload methods that we have as default and per host
        if debug: print "D: Default Method: %s" % \
            config.get('DEFAULT', 'method')
        if not upload_methods.has_key(config.get('DEFAULT', 'method')):
            print "Unknown upload method: %s" % \
                config.get('DEFAULT', 'method')
            sys.exit(1)
        if debug: print "D: Host Method: %s" % config.get(host, 'method') 
        if not upload_methods.has_key(config.get(host, 'method')):
            print "Unknown upload method: %s" % config.get(host, 'method')
            sys.exit(1)

        # Inspect the Config and set appropriate upload method
        if not config.get(host, 'method'):
            method = config.get('DEFAULT', 'method')
        else:
            method = config.get(host, 'method')

        # Check now the login and redefine it if needed
        if (len(config.get(host, 'login')) != 0 and \
                    config.get(host, 'login') != 'username'):
            login = config.get(host, 'login')
            if debug: print "D: Login %s from section %s used"%(login,host)
        elif (len(config.get('DEFAULT', 'login')) != 0 and \
                    config.get('DEFAULT', 'login') != 'username'):
            login = config.get('DEFAULT', 'login')
            if debug: print "D: Default login %s used"%login
        else:
            if debug: print "D: Neither host %s nor default login used. Using %s" %(host,login)

        # Messy, yes. But it isn't referenced by the upload method anyway.
        if config.get(host, 'method') == 'local':
            fqdn = 'localhost'
        else:
            fqdn = config.get(host, 'fqdn')
        incoming = config.get(host, 'incoming')

        # if delay_upload wasn't passed via -e/--delayed
        if not delay_upload:
            delay_upload = config.get(host, 'delayed')
            if not delay_upload:
                delay_upload = config.get('DEFAULT', 'delayed')

        if delay_upload:
            if int(delay_upload) == 0:
                print "Uploading to DELAYED/0-day."
            if incoming[-1] == '/':
                first_char = ''
            else:
                first_char = '/'
            incoming += first_char + 'DELAYED/' + delay_upload + '-day'
            delayed = ' [DELAYED/' + delay_upload + ']'
        else:
            delayed = ''

        # Do the actual upload
        if not simulate:
            print "Uploading to %s%s (via %s to %s):"%(host,delayed,method,fqdn)
            if debug:
                print "D: FQDN: %s" % fqdn
                print "D: Login: %s" % login
                print "D: Incoming: %s" % incoming
            progress = config.getint(host,'progress_indicator')
            if not os.isatty(1):
              progress = 0
            if method == 'ftp':
                if ':' in fqdn:
                    fqdn, port = fqdn.rsplit(":",1)
                else:
                    port = 21
                ftp_mode = config.getboolean(host, 'passive_ftp')
                if ftp_passive_mode == 1: ftp_mode = 1
                if debug:
                    print "D: FTP port: %s" % port
                    if ftp_mode == 1:
                        print "D: Using passive ftp"
                    else:
                        print "D: Using active ftp"
                upload_methods[method](
                  fqdn, login, incoming,
                  files_to_upload, debug, ftp_mode, progress=progress, port=port)
            elif method == 'scp':
                if debug and config.getboolean(host, 'scp_compress'):
                    print "D: Setting compression for scp"
                scp_compress = config.getboolean(host, 'scp_compress')
                ssh_config_options = filter(None, map(lambda x: x.strip(),
                   config.get (host ,'ssh_config_options').split('\n')))
                if debug:
                  print "D: ssh config options:\n  "+'\n  '.join(ssh_config_options)
                upload_methods[method](fqdn, login, incoming, \
                    files_to_upload, debug, scp_compress, ssh_config_options)
            else:
                upload_methods[method](fqdn, login, incoming, \
                    files_to_upload, debug, 0, progress=progress)
        # Or just simulate it.
        else:
            for file in files_to_upload:
                print 'Uploading with %s: %s to %s:%s' % (method, \
                    file, fqdn, incoming)

        # Create the logfile after the package has 
        # been put into the archive.
        if not simulate:
            if not no_upload_log:
                create_upload_file(name_of_package, host, path, \
                    files_to_upload, debug)
            print "Successfully uploaded packages."
        else:
            print "Simulated upload."
    
        # Run dinstall if the user asked us to do so.
        if debug:
            print "D: dinstall: %s" % dinstall
            print "D: Host Config: %s" % config.getboolean(host, 'run_dinstall')
        if config.getboolean(host, 'run_dinstall') == 1 or dinstall:
            if not simulate:
                dinstall_caller(name_of_package, host, login, incoming, debug)
            else:
                print "Will run dinstall now."

        # Post-Upload Command
        if len(config.get(host, 'post_upload_command')) != 0:
            type = 'post'
            execute_command(host, debug, type)
            
    return

# Main
if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print "Exiting due to user interrupt."
        sys.exit(1)
    except dputhelper.DputException, e:
      print >> sys.stderr, e
      sys.exit(1)