Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/rpms/sugar/0105-uy-1769-1-to-N-Feature.patch
blob: b391e9d2679534e2669b0bcac2648430d8170695 (plain)
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
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
From b3c6fee84f9c3b612432b9131217a563c2a50c7a Mon Sep 17 00:00:00 2001
From: Ajay Garg <ajay@activitycentral.com>
Date: Fri, 4 May 2012 01:03:13 +0530
Subject: [sugar PATCH v5] uy#1769: 1-to-N Feature
Organization: Sugar Labs Foundation
Signed-off-by: Ajay Garg <ajay@activitycentral.com>
---

The feature specs, and workflow-screenshots, are listed at ::
http://wiki.sugarlabs.org/go/Features/Transfer_to_many_options



Changes of version-5 over version-4 ::
--------------------------------------


a)
Fixed the bug (Thanks Anish for catching this) ::

* Server adds files to "Shares" folder
* Client tries to add the Server's "Shares", by clicking on 
  "Access Share" in Neighborhood-View.
* The Server's Shares' button appears in the bottom panel-tray.
* Server disconnects from the network.
* Client tries to access the Server's Shares, by clicking on
  the Server's Shares' button.
* UI Freeze.
* No Exception in logs.


The solution is, again, to display the "Connection Failed" error, much on the 
same lines as "Entries without a file cannot be copied".
This holds true for both ===> batch-mode, and single-mode.



b)
Fixed the bug ::

* Server adds files to "Shares" folder
* Client tries to add the Server's "Shares", by clicking on 
  "Access Share" in Neighborhood-View.
* The Server's Shares' button appears in the bottom panel-tray.
* Client tries to access the Server's Shares, by clicking on
  the Server's Shares' button.
* Server's Shares' items are visible in the listview.
* Client starts copying a (large) file, say "big_image.img".
* Before the file could be downloaded from remote server, server disconnects 
  from the network.
* UI Freeze.
* No Exception in logs.


The solution is, again, to display the (socket) "Timed Out" error, much on the
same lines as "Entries without a file cannot be copied".
This holds true for both ===> batch-mode, and single-mode.



c)
Made the locally-mounted-remote-shares icon, the same as that of "Shares" folder.

Thanks to Anish for the motivation.



d)
There was a bug in "v4", wherein during server-disconnected cases, the "busy-cursor"
would persist, even when the operations were over during batch-mode. This was due to 
bug a) as listed above, which resulted in not-loading-of-listview after batch-operations
were over.

With a) fixed, this got fixed automatically.

Thanks to Anish for catching this.




===========================================================================




Changes of version-4 over version-3 ::
--------------------------------------

NOTE ::

The WebDAV backend-library being used is the one from 
https://launchpad.net/python-webdav-lib/trunk/0.3.0/+download/Python_WebDAV_Library-0.3.0.zip

The reason for using this, is purely based on not reinventing-the-wheel.
Moreover, it served the following three major purposes ::

   (i)   Open-Source, in python.
    
   (ii)  It provided the API for accessing URLs of type ::

         * dav://1.2.3.4/webdav/
         * dav://1.2.3.4/webdav/dir_1
         * dav://1.2.3.4/webdav/dir_1/dir_2
     
   (iii) It provided the API for downloading a resource (file) of type ::

         * dav://1.2.3.4/webdav/1.txt
         * dav://1.2.3.4/webdav/dir_1/2.png
         * dav://1.2.3.4/webdav/dir_1/dir_2/1743.avi


Thanks to Sascha, for the motivation of making it absolutely clear and explicit that 
the reason for using this 3rd-party library be mentioned (since I myself had to struggle 
quite a bit for finding the suitable one :) )




===========================================================================




Changes of version-3 over version-2 ::
--------------------------------------

a)
Added new icon for "Shares" folder.

For this to take effect, patch at http://patchwork.sugarlabs.org/patch/1419/
must be applied.

Thanks to Frederick Grose for the image, and Anish for validating it.




===========================================================================




Changes of version-2 over version-1 ::
--------------------------------------

a)
Fixed the bug, wherein it was required that activities should NOT be launched,
by clicking on the icons in "locally-mounted-remote-shares" listview.

Thanks Anish for providing the solution to this :)



b)
Fixed the bug (Thanks Anish for catching this) ::

* Server adds files to "Shares" folder.
* Client tries to add the Server's "Shares", by clicking on 
  "Access Share" in Neighborhood-View.
* The Server's Shares' button appears in the bottom panel-tray.
* Client tries to access the Server's Shares, by clicking on
  the Server's Shares' button.
* Server's Shares' items are visible in the listview.
* Server disconnects from the network.
* Client tries to copy files.
* UI Freeze.
* Exception in logs.


The solution is to "catch" the Connection-Failed exception, and display the error-message,
on similar lines as "Entries without a file cannot be copied."
This holds true for both ===> batch-mode, and single-mode.



c)
Did "Code Extraction" from "src/webdav/WebdavClient.py" to "src/jarabe/journal/webdavmanager.py".
Now, all files in "src/webdav" and "src/webdav/acp" directories contain code present at 
https://launchpad.net/python-webdav-lib/trunk/0.3.0/+download/Python_WebDAV_Library-0.3.0.zip

Thanks Anish, for providing the motivation.


 configure.ac                          |    4 +-
 src/Makefile.am                       |    4 +-
 src/jarabe/journal/Makefile.am        |    5 +-
 src/jarabe/journal/journalactivity.py |    3 +
 src/jarabe/journal/journaltoolbox.py  |    7 +
 src/jarabe/journal/listview.py        |    9 +
 src/jarabe/journal/model.py           |  205 ++++++++-
 src/jarabe/journal/palettes.py        |   79 +++
 src/jarabe/journal/volumestoolbar.py  |   94 ++++-
 src/jarabe/journal/webdavmanager.py   |  256 ++++++++++
 src/jarabe/model/buddy.py             |   11 +
 src/jarabe/model/neighborhood.py      |    3 +
 src/jarabe/view/buddymenu.py          |   11 +
 src/jarabe/view/palettes.py           |   33 ++
 src/webdav/Condition.py               |  475 +++++++++++++++++++
 src/webdav/Connection.py              |  321 +++++++++++++
 src/webdav/Constants.py               |  199 ++++++++
 src/webdav/Makefile.am                |   20 +
 src/webdav/NameCheck.py               |  193 ++++++++
 src/webdav/Utils.py                   |  154 ++++++
 src/webdav/VersionHandler.py          |  198 ++++++++
 src/webdav/WebdavClient.py            |  840 +++++++++++++++++++++++++++++++++
 src/webdav/WebdavRequests.py          |  205 ++++++++
 src/webdav/WebdavResponse.py          |  525 ++++++++++++++++++++
 src/webdav/__init__.py                |   16 +
 src/webdav/acp/Ace.py                 |  293 ++++++++++++
 src/webdav/acp/AceHandler.py          |  182 +++++++
 src/webdav/acp/Acl.py                 |  311 ++++++++++++
 src/webdav/acp/GrantDeny.py           |  241 ++++++++++
 src/webdav/acp/Makefile.am            |   12 +
 src/webdav/acp/Principal.py           |  189 ++++++++
 src/webdav/acp/Privilege.py           |  125 +++++
 src/webdav/acp/__init__.py            |   33 ++
 src/webdav/davlib.py                  |  336 +++++++++++++
 src/webdav/logger.py                  |   51 ++
 src/webdav/qp_xml.py                  |  240 ++++++++++
 src/webdav/uuid_.py                   |  476 +++++++++++++++++++
 37 files changed, 6340 insertions(+), 19 deletions(-)
 create mode 100644 src/jarabe/journal/webdavmanager.py
 create mode 100644 src/webdav/Condition.py
 create mode 100644 src/webdav/Connection.py
 create mode 100644 src/webdav/Constants.py
 create mode 100644 src/webdav/Makefile.am
 create mode 100644 src/webdav/NameCheck.py
 create mode 100644 src/webdav/Utils.py
 create mode 100644 src/webdav/VersionHandler.py
 create mode 100644 src/webdav/WebdavClient.py
 create mode 100644 src/webdav/WebdavRequests.py
 create mode 100644 src/webdav/WebdavResponse.py
 create mode 100644 src/webdav/__init__.py
 create mode 100644 src/webdav/acp/Ace.py
 create mode 100644 src/webdav/acp/AceHandler.py
 create mode 100644 src/webdav/acp/Acl.py
 create mode 100644 src/webdav/acp/GrantDeny.py
 create mode 100644 src/webdav/acp/Makefile.am
 create mode 100644 src/webdav/acp/Principal.py
 create mode 100644 src/webdav/acp/Privilege.py
 create mode 100644 src/webdav/acp/__init__.py
 create mode 100644 src/webdav/davlib.py
 create mode 100644 src/webdav/logger.py
 create mode 100644 src/webdav/qp_xml.py
 create mode 100644 src/webdav/uuid_.py

diff --git a/configure.ac b/configure.ac
index 8e6d871..e04bdec 100644
--- a/configure.ac
+++ b/configure.ac
@@ -61,8 +61,6 @@ extensions/cpsection/modemconfiguration/config.py
 extensions/cpsection/Makefile
 extensions/cpsection/network/Makefile
 extensions/cpsection/power/Makefile
-extensions/cpsection/updater/backends/Makefile
-extensions/cpsection/updater/Makefile
 extensions/deviceicon/Makefile
 extensions/globalkey/Makefile
 extensions/Makefile
@@ -79,6 +77,8 @@ src/jarabe/model/Makefile
 src/jarabe/util/Makefile
 src/jarabe/util/telepathy/Makefile
 src/jarabe/view/Makefile
+src/webdav/acp/Makefile
+src/webdav/Makefile
 src/Makefile
 ])
 
diff --git a/src/Makefile.am b/src/Makefile.am
index 83571a4..765da8b 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -1 +1,3 @@
-SUBDIRS = jarabe
+SUBDIRS =        \
+        jarabe   \
+	webdav
diff --git a/src/jarabe/journal/Makefile.am b/src/jarabe/journal/Makefile.am
index f24dcfe..8efca6d 100644
--- a/src/jarabe/journal/Makefile.am
+++ b/src/jarabe/journal/Makefile.am
@@ -15,5 +15,6 @@ sugar_PYTHON =				\
 	model.py			\
 	objectchooser.py		\
 	palettes.py			\
-	volumestoolbar.py			\
-	processdialog.py
+	volumestoolbar.py		\
+	processdialog.py                \
+	webdavmanager.py
diff --git a/src/jarabe/journal/journalactivity.py b/src/jarabe/journal/journalactivity.py
index fa308cd..1b841e9 100644
--- a/src/jarabe/journal/journalactivity.py
+++ b/src/jarabe/journal/journalactivity.py
@@ -485,6 +485,9 @@ class JournalActivity(JournalWindow):
     def is_editing_mode_present(self):
         return self._editing_mode
 
+    def get_volumes_toolbar(self):
+        return self._volumes_toolbar
+
 
 def get_journal():
     global _journal
diff --git a/src/jarabe/journal/journaltoolbox.py b/src/jarabe/journal/journaltoolbox.py
index fd14826..c3614d7 100644
--- a/src/jarabe/journal/journaltoolbox.py
+++ b/src/jarabe/journal/journaltoolbox.py
@@ -624,6 +624,13 @@ class BatchEraseButton(ToolButton, palettes.ActionItem):
                                      show_not_completed_ops_info=True)
         self.props.tooltip = _('Erase')
 
+        # De-sensitize Batch-Erase button, for locally-mounted-remote-shares.
+        from jarabe.journal.journalactivity import get_mount_point
+        current_mount_point = get_mount_point()
+
+        if model.is_mount_point_for_locally_mounted_remote_share(current_mount_point):
+            self.set_sensitive(False)
+
     def _get_actionable_signal(self):
         return 'clicked'
 
diff --git a/src/jarabe/journal/listview.py b/src/jarabe/journal/listview.py
index 8522dca..10f468f 100644
--- a/src/jarabe/journal/listview.py
+++ b/src/jarabe/journal/listview.py
@@ -634,6 +634,15 @@ class ListView(BaseListView):
         self.emit('volume-error', message, severity)
 
     def __icon_clicked_cb(self, cell, path):
+        # For locally-mounted remote shares, we do not want to launch
+        # by clicking on the icons.
+        # So, check if this is a part of locally-mounted-remote share,
+        # and if yes, return, without doing anything.
+        from jarabe.journal.journalactivity import get_mount_point
+        current_mount_point = get_mount_point()
+        if model.is_mount_point_for_locally_mounted_remote_share(current_mount_point):
+            return
+
         row = self.tree_view.get_model()[path]
         metadata = model.get(row[ListModel.COLUMN_UID])
         misc.resume(metadata)
diff --git a/src/jarabe/journal/model.py b/src/jarabe/journal/model.py
index 83e216f..527f78d 100644
--- a/src/jarabe/journal/model.py
+++ b/src/jarabe/journal/model.py
@@ -20,6 +20,7 @@
 
 import logging
 import os
+import stat
 import errno
 import subprocess
 from datetime import datetime
@@ -36,11 +37,14 @@ import gobject
 import dbus
 import gio
 import gconf
+import string
 
 from sugar import dispatch
 from sugar import mime
 from sugar import util
 
+from jarabe.journal.webdavmanager import get_remote_webdav_share_metadata
+
 DS_DBUS_SERVICE = 'org.laptop.sugar.DataStore'
 DS_DBUS_INTERFACE = 'org.laptop.sugar.DataStore'
 DS_DBUS_PATH = '/org/laptop/sugar/DataStore'
@@ -425,6 +429,123 @@ class InplaceResultSet(BaseResultSet):
         return
 
 
+class RemoteShareResultSet(object):
+    def __init__(self, ip_address, query):
+        self._ip_address = ip_address
+        self._file_list = []
+
+        self.ready = dispatch.Signal()
+        self.progress = dispatch.Signal()
+
+        # First time, query is none.
+        if query is None:
+            return
+
+        query_text = query.get('query', '')
+        if query_text.startswith('"') and query_text.endswith('"'):
+            self._regex = re.compile('*%s*' % query_text.strip(['"']))
+        elif query_text:
+            expression = ''
+            for word in query_text.split(' '):
+                expression += '(?=.*%s.*)' % word
+            self._regex = re.compile(expression, re.IGNORECASE)
+        else:
+            self._regex = None
+
+        if query.get('timestamp', ''):
+            self._date_start = int(query['timestamp']['start'])
+            self._date_end = int(query['timestamp']['end'])
+        else:
+            self._date_start = None
+            self._date_end = None
+
+        self._mime_types = query.get('mime_type', [])
+
+        self._sort = query.get('order_by', ['+timestamp'])[0]
+
+    def setup(self):
+        metadata_list_complete = get_remote_webdav_share_metadata(self._ip_address)
+        for metadata in metadata_list_complete:
+
+            add_to_list = False
+            if self._regex is not None:
+                for f in ['fulltext', 'title',
+                          'description', 'tags']:
+                    if f in metadata and \
+                            self._regex.match(metadata[f]):
+                        add_to_list = True
+                        break
+            else:
+                add_to_list = True
+            if not add_to_list:
+                continue
+
+            add_to_list = False
+            if self._date_start is not None:
+                if metadata['timestamp'] > self._date_start:
+                    add_to_list = True
+            else:
+                add_to_list = True
+            if not add_to_list:
+                continue
+
+            add_to_list = False
+            if self._date_end is not None:
+                if metadata['timestamp'] < self._date_end:
+                    add_to_list = True
+            else:
+                add_to_list = True
+            if not add_to_list:
+                continue
+
+            add_to_list = False
+            if self._mime_types:
+                mime_type = metadata['mime_type']
+                if mime_type in self._mime_types:
+                    add_to_list = True
+            else:
+                add_to_list = True
+            if not add_to_list:
+                continue
+
+            # If control reaches here, the current metadata has passed
+            # out all filter-tests.
+            file_info = (metadata['timestamp'],
+                         metadata['creation_time'],
+                         metadata['filesize'],
+                         metadata)
+            self._file_list.append(file_info)
+
+        if self._sort[1:] == 'filesize':
+            keygetter = itemgetter(2)
+        elif self._sort[1:] == 'creation_time':
+            keygetter = itemgetter(1)
+        else:
+            # timestamp
+            keygetter = itemgetter(0)
+
+        self._file_list.sort(lambda a, b: cmp(b, a),
+                             key=keygetter,
+                             reverse=(self._sort[0] == '-'))
+
+        self.ready.send(self)
+
+    def get_length(self):
+        return len(self._file_list)
+
+    length = property(get_length)
+
+    def seek(self, position):
+        self._position = position
+
+    def read(self):
+        modified_timestamp, creation_timestamp, filesize, metadata =  self._file_list[self._position]
+        return  metadata
+
+    def stop(self):
+        self._stopped = True
+
+
 def _get_file_metadata(path, stat, fetch_preview=True):
     """Return the metadata from the corresponding file.
 
@@ -436,10 +557,16 @@ def _get_file_metadata(path, stat, fetch_preview=True):
     dir_path = os.path.dirname(path)
     metadata = _get_file_metadata_from_json(dir_path, filename, fetch_preview)
     if metadata:
+        # For Documents/Shares/Mounted-Drives.
+        # Special case: for locally-mounted-remote-files, ensure that
+        # "metadata['filesize' is already present before-hand. This
+        # will have to be done at the time of fetching
+        # webdav-properties per resource.
         if 'filesize' not in metadata:
             metadata['filesize'] = stat.st_size
         return metadata
 
+    # For Journal.
     return {'uid': path,
             'title': os.path.basename(path),
             'timestamp': stat.st_mtime,
@@ -529,11 +656,33 @@ def find(query_, page_size):
         raise ValueError('Exactly one mount point must be specified')
 
     if mount_points[0] == '/':
+        """
+        For Journal.
+        """
         return DatastoreResultSet(query, page_size)
+    elif is_mount_point_for_locally_mounted_remote_share(mount_points[0]):
+        """
+        For Locally-Mounted-Remote-Shares.
+        Regex Matching is used, to ensure that the mount-point is an
+        IP-Address.
+        """
+        return RemoteShareResultSet(mount_points[0], query)
     else:
+        """
+        For Documents/Shares/Mounted-Drives.
+        """
         return InplaceResultSet(query, page_size, mount_points[0])
 
 
+def is_mount_point_for_locally_mounted_remote_share(mount_point):
+    import re
+
+    pattern = '[1-9][0-9]{0,2}\.[0-9]{0,3}\.[0-9]{0,3}\.[0-9]{0,3}'
+    if re.match(pattern, mount_point) is None:
+        return False
+    return True
+
+
 def _get_mount_point(path):
     dir_path = os.path.dirname(path)
     while dir_path:
@@ -544,14 +693,45 @@ def _get_mount_point(path):
     return None
 
 
+def is_locally_mounted_remote_share(path):
+    return string.find(path, '/tmp/') == 0
+
+
+def extract_ip_address_from_locally_mounted_remote_share_path(path):
+    """
+    Path is of type ::
+
+        /tmp/127.0.0.1/webdav/a.txt
+    """
+    return path.split('/')[2]
+
+
 def get(object_id):
     """Returns the metadata for an object
     """
-    if os.path.exists(object_id):
-        stat = os.stat(object_id)
+    if (os.path.exists(object_id) or (is_locally_mounted_remote_share(object_id))):
+        """
+        For Documents/Shares/Mounted-Drives/Locally-Mounted-Remote-Shares,
+        where ".Sugar-Metadata" folder exists.
+
+        The only thing is that, for locally-mounted-remote-shares, the
+        "file" is not physically present.
+        """
+        if os.path.exists(object_id):
+            # if the file is physically present, derive file-metadata
+            # by physical examination of the file.
+            stat = os.stat(object_id)
+        else:
+            # if the file is remote, derive file-metadata by fetching
+            # properties remotely (webdav properties).
+            stat = None
+
         metadata = _get_file_metadata(object_id, stat)
         metadata['mountpoint'] = _get_mount_point(object_id)
     else:
+        """
+        For journal, where ".Sugar-Metadata" folder does not exists.
+        """
         metadata = _get_datastore().get_properties(object_id, byte_arrays=True)
         metadata['mountpoint'] = '/'
     return metadata
@@ -561,9 +741,16 @@ def get_file(object_id):
     """Returns the file for an object
     """
     if os.path.exists(object_id):
+        """
+        For Documents/Shares/Mounted-Drives/
+        Locally-Mounted-Remote-Shares-in-case-when-it-is-present-already.
+        """
         logging.debug('get_file asked for file with path %r', object_id)
         return object_id
     else:
+        """
+        For Journal.
+        """
         logging.debug('get_file asked for entry with id %r', object_id)
         file_path = _get_datastore().get_filename(object_id)
         if file_path:
@@ -754,6 +941,20 @@ def _write_entry_on_external_device(metadata, file_path):
         _rename_entry_on_external_device(file_path, destination_path,
                                          metadata_dir_path)
 
+    # For "Shares" folder, we need to set the permissions of the newly
+    # copied file to 0777, else it will not be accessible by "httpd"
+    # service.
+    if metadata['mountpoint'] == '/var/www/web1/web':
+        fd = os.open(destination_path, os.O_RDONLY)
+        os.fchmod(fd, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
+        os.close(fd)
+
+        metadata_file_path = os.path.join(metadata_dir_path, file_name + '.metadata')
+        fd = os.open(metadata_file_path, os.O_RDONLY)
+        os.fchmod(fd, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
+        os.close(fd)
+
+
     object_id = destination_path
     created.send(None, object_id=object_id)
 
diff --git a/src/jarabe/journal/palettes.py b/src/jarabe/journal/palettes.py
index 740b65a..46ade98 100644
--- a/src/jarabe/journal/palettes.py
+++ b/src/jarabe/journal/palettes.py
@@ -29,6 +29,7 @@ import gconf
 import gio
 import glib
 import time
+import socket
 
 from sugar import _sugarext
 
@@ -45,6 +46,10 @@ from jarabe.model import mimeregistry
 from jarabe.journal import misc
 from jarabe.journal import model
 
+from webdav.Connection import WebdavError
+from jarabe.journal.webdavmanager import get_resource_by_ip_address_and_resource_key
+
+
 friends_model = friends.get_model()
 
 _copy_menu_helper = None
@@ -77,6 +82,9 @@ class ObjectPalette(Palette):
         Palette.__init__(self, primary_text=title,
                          icon=activity_icon)
 
+        from jarabe.journal.journalactivity import get_mount_point
+        current_mount_point = get_mount_point()
+
         if misc.get_activities(metadata) or misc.is_bundle(metadata):
             if metadata.get('activity_id', ''):
                 resume_label = _('Resume')
@@ -86,10 +94,15 @@ class ObjectPalette(Palette):
                 resume_with_label = _('Start with')
             menu_item = MenuItem(resume_label, 'activity-start')
             menu_item.connect('activate', self.__start_activate_cb)
+            if model.is_mount_point_for_locally_mounted_remote_share(current_mount_point):
+                menu_item.set_sensitive(False)
             self.menu.append(menu_item)
             menu_item.show()
 
             menu_item = MenuItem(resume_with_label, 'activity-start')
+            if model.is_mount_point_for_locally_mounted_remote_share(current_mount_point):
+                menu_item.set_sensitive(False)
+
             self.menu.append(menu_item)
             menu_item.show()
             start_with_menu = StartWithMenu(self._metadata)
@@ -101,6 +114,7 @@ class ObjectPalette(Palette):
             self.menu.append(menu_item)
             menu_item.show()
 
+
         menu_item = MenuItem(_('Copy to'))
         icon = Icon(icon_name='edit-copy', xo_color=color,
                     icon_size=gtk.ICON_SIZE_MENU)
@@ -120,16 +134,21 @@ class ObjectPalette(Palette):
         copy_menu.connect('volume-error', self.__volume_error_cb)
         menu_item.set_submenu(copy_menu)
 
+
         if self._metadata['mountpoint'] == '/':
             menu_item = MenuItem(_('Duplicate'))
             icon = Icon(icon_name='edit-duplicate', xo_color=color,
                         icon_size=gtk.ICON_SIZE_MENU)
             menu_item.set_image(icon)
             menu_item.connect('activate', self.__duplicate_activate_cb)
+            if model.is_mount_point_for_locally_mounted_remote_share(current_mount_point):
+                menu_item.set_sensitive(False)
             self.menu.append(menu_item)
             menu_item.show()
 
         menu_item = MenuItem(_('Send to'), 'document-send')
+        if model.is_mount_point_for_locally_mounted_remote_share(current_mount_point):
+            menu_item.set_sensitive(False)
         self.menu.append(menu_item)
         menu_item.show()
 
@@ -140,14 +159,19 @@ class ObjectPalette(Palette):
         if detail == True:
             menu_item = MenuItem(_('View Details'), 'go-right')
             menu_item.connect('activate', self.__detail_activate_cb)
+            if model.is_mount_point_for_locally_mounted_remote_share(current_mount_point):
+                menu_item.set_sensitive(False)
             self.menu.append(menu_item)
             menu_item.show()
 
         menu_item = MenuItem(_('Erase'), 'list-remove')
         menu_item.connect('activate', self.__erase_activate_cb)
+        if model.is_mount_point_for_locally_mounted_remote_share(current_mount_point):
+            menu_item.set_sensitive(False)
         self.menu.append(menu_item)
         menu_item.show()
 
+
     def __start_activate_cb(self, menu_item):
         misc.resume(self._metadata)
 
@@ -541,6 +565,31 @@ class ActionItem(gobject.GObject):
         self._post_operate_per_metadata_per_action(metadata)
 
     def _file_path_valid(self, metadata):
+        from jarabe.journal.journalactivity import get_mount_point
+        current_mount_point = get_mount_point()
+
+        # Now, for locally mounted remote-shares, download the file.
+        # Note that, always download the file, to avoid the problems
+        # of stale-cache.
+        if model.is_mount_point_for_locally_mounted_remote_share(current_mount_point):
+            file_path = metadata['uid']
+            filename = os.path.basename(file_path)
+            ip_address = model.extract_ip_address_from_locally_mounted_remote_share_path(file_path)
+            resource = get_resource_by_ip_address_and_resource_key(ip_address, '/webdav/' + filename)
+            download_file_path = '/tmp/' + ip_address + '/' + filename
+            try:
+                resource.downloadFile(download_file_path)
+                return True
+            except (WebdavError, socket.error), e:
+                error_message = e
+                logging.warn(error_message)
+                if self._batch_mode:
+                    self._handle_error_alert(error_message, metadata)
+                else:
+                    self.emit('volume-error', error_message,
+                            _('Error'))
+                return False
+
         file_path = model.get_file(metadata['uid'])
         if not file_path or not os.path.exists(file_path):
             logging.warn('Entries without a file cannot be copied.')
@@ -708,6 +757,25 @@ class DocumentsMenu(BaseCopyMenuItem):
         self._post_operate_per_metadata_per_action(metadata)
 
 
+class SharesMenu(BaseCopyMenuItem):
+    def __init__(self, metadata_list, show_editing_alert,
+                 show_progress_info_alert, batch_mode):
+        BaseCopyMenuItem.__init__(self, metadata_list, _('Shares'),
+                                  show_editing_alert,
+                                  show_progress_info_alert,
+                                  batch_mode)
+
+    def _operate(self, metadata):
+        if not self._file_path_valid(metadata):
+            return False
+        if not self._metadata_copy_valid(metadata,
+                                         '/var/www/web1/web'):
+            return False
+
+        # This is sync-operation. Call the post-operation now.
+        self._post_operate_per_metadata_per_action(metadata)
+
+
 class FriendsMenu(gtk.Menu):
     __gtype_name__ = 'JournalFriendsMenu'
 
@@ -835,6 +903,17 @@ class CopyMenuHelper(gtk.Menu):
             menu.append(documents_menu)
             documents_menu.show()
 
+        if get_mount_point() != '/var/www/web1/web':
+            documents_menu = SharesMenu(metadata_list,
+                                           show_editing_alert,
+                                           show_progress_info_alert,
+                                           batch_mode)
+            documents_menu.set_image(Icon(icon_name='emblem-neighborhood-shared',
+                                          icon_size=gtk.ICON_SIZE_MENU))
+            documents_menu.connect('volume-error', self.__volume_error_cb)
+            menu.append(documents_menu)
+            documents_menu.show()
+
         if get_mount_point() != '/':
             client = gconf.client_get_default()
             color = XoColor(client.get_string('/desktop/sugar/user/color'))
diff --git a/src/jarabe/journal/volumestoolbar.py b/src/jarabe/journal/volumestoolbar.py
index 94914e6..1f6e3ec 100644
--- a/src/jarabe/journal/volumestoolbar.py
+++ b/src/jarabe/journal/volumestoolbar.py
@@ -37,8 +37,10 @@ from sugar.graphics.palette import Palette
 from sugar.graphics.xocolor import XoColor
 from sugar import env
 
+from jarabe.frame.notification import NotificationIcon
 from jarabe.journal import model
-from jarabe.view.palettes import JournalVolumePalette, JournalXSPalette
+from jarabe.view.palettes import JournalVolumePalette, JournalXSPalette, RemoteSharePalette
+import jarabe.frame
 
 
 _JOURNAL_0_METADATA_DIR = '.olpc.store'
@@ -209,6 +211,7 @@ class VolumesToolbar(gtk.Toolbar):
 
     def _set_up_volumes(self):
         self._set_up_documents_button()
+        self._set_up_shares_button()
 
         volume_monitor = gio.volume_monitor_get()
         self._mount_added_hid = volume_monitor.connect('mount-added',
@@ -219,12 +222,11 @@ class VolumesToolbar(gtk.Toolbar):
         for mount in volume_monitor.get_mounts():
             self._add_button(mount)
 
-    def _set_up_documents_button(self):
-        documents_path = model.get_documents_path()
-        if documents_path is not None:
-            button = DocumentsButton(documents_path)
+    def _set_up_directory_button(self, dir_path, icon_name, label_text):
+        if dir_path is not None:
+            button = DirectoryButton(dir_path, icon_name)
             button.props.group = self._volume_buttons[0]
-            label = glib.markup_escape_text(_('Documents'))
+            label = glib.markup_escape_text(label_text)
             button.set_palette(Palette(label))
             button.connect('toggled', self._button_toggled_cb)
             button.show()
@@ -234,6 +236,39 @@ class VolumesToolbar(gtk.Toolbar):
             self._volume_buttons.append(button)
             self.show()
 
+    def _set_up_documents_button(self):
+        documents_path = model.get_documents_path()
+        self._set_up_directory_button(documents_path,
+                                      'user-documents',
+                                      _('Documents'))
+
+    def _set_up_shares_button(self):
+        shares_dir_path = '/var/www/web1/web'
+        self._set_up_directory_button(shares_dir_path,
+                                      'emblem-neighborhood-shared',
+                                      _('Shares'))
+
+    def _add_remote_share_button(self, buddy):
+        button = RemoteSharesButton(buddy)
+        button.props.group = self._volume_buttons[0]
+        label = glib.markup_escape_text(_('%s\'s share') % \
+                                        buddy.props.nick)
+        button.set_palette(RemoteSharePalette(buddy, button))
+        button.connect('toggled', self._button_toggled_cb)
+        button.show()
+
+        position = self.get_item_index(self._volume_buttons[-1]) + 1
+        self.insert(button, position)
+        self._volume_buttons.append(button)
+        self.show()
+
+        frame = jarabe.frame.get_view()
+        notif_icon = NotificationIcon()
+        notif_icon.props.icon_name = 'emblem-neighborhood-shared'
+        notif_icon.props.xo_color = buddy.props.color
+        frame.add_notification(notif_icon,
+                               gtk.CORNER_BOTTOM_RIGHT)
+
     def __mount_added_cb(self, volume_monitor, mount):
         self._add_button(mount)
 
@@ -271,8 +306,8 @@ class VolumesToolbar(gtk.Toolbar):
     def __volume_error_cb(self, button, strerror, severity):
         self.emit('volume-error', strerror, severity)
 
-    def _button_toggled_cb(self, button):
-        if button.props.active:
+    def _button_toggled_cb(self, button, force_toggle=False):
+        if button.props.active or force_toggle:
             self.emit('volume-changed', button.mount_point)
 
     def _unmount_activated_cb(self, menu_item, mount):
@@ -300,6 +335,19 @@ class VolumesToolbar(gtk.Toolbar):
         if len(self.get_children()) < 2:
             self.hide()
 
+    def _remove_remote_share_button(self, mount_point):
+        # Here, IP_Address is the mount_point.
+        for button in self.get_children():
+            if type(button) == RemoteSharesButton and \
+                    button.mount_point == mount_point:
+                        self._volume_buttons.remove(button)
+                        self.remove(button)
+                        self.get_children()[0].props.active = True
+
+                        if len(sel.get_children()) < 2:
+                            self.hide()
+                        break;
+
     def set_active_volume(self, mount):
         button = self._get_button_for_mount(mount)
         button.props.active = True
@@ -313,6 +361,12 @@ class VolumesToolbar(gtk.Toolbar):
             if button.mount_point != mount_point:
                 button.set_sensitive(sensitive)
 
+    def get_journal_button(self):
+        return self._volume_buttons[0]
+
+    def get_button_toggled_cb(self):
+        return self._button_toggled_cb
+
 
 class BaseButton(RadioToolButton):
     __gsignals__ = {
@@ -427,18 +481,34 @@ class JournalButtonPalette(Palette):
                 {'free_space': free_space / (1024 * 1024)}
 
 
-class DocumentsButton(BaseButton):
+class DirectoryButton(BaseButton):
 
-    def __init__(self, documents_path):
-        BaseButton.__init__(self, mount_point=documents_path)
+    def __init__(self, dir_path, icon_name):
+        BaseButton.__init__(self, mount_point=dir_path)
 
-        self.props.named_icon = 'user-documents'
+        self.props.named_icon = icon_name
 
         client = gconf.client_get_default()
         color = XoColor(client.get_string('/desktop/sugar/user/color'))
         self.props.xo_color = color
 
 
+class RemoteSharesButton(BaseButton):
+
+    def __init__(self, buddy):
+        BaseButton.__init__(self, mount_point=buddy.props.ip_address)
+
+        self._buddy = buddy
+        self.props.named_icon = 'emblem-neighborhood-shared'
+        self.props.xo_color = buddy.props.color
+        self._buddy_ip_address = buddy.props.ip_address
+
+    def create_palette(self):
+        palette = RemoteSharePalette(self._buddy)
+        return palette
+
+
+
 class XSButton(ToolButton):
     def __init__(self):
         ToolButton.__init__(self)
diff --git a/src/jarabe/journal/webdavmanager.py b/src/jarabe/journal/webdavmanager.py
new file mode 100644
index 0000000..6cd0713
--- /dev/null
+++ b/src/jarabe/journal/webdavmanager.py
@@ -0,0 +1,256 @@
+from gettext import gettext as _
+
+import os
+import sys
+
+import gobject
+import simplejson
+import shutil
+
+from webdav.Connection import AuthorizationError, WebdavError
+from webdav.WebdavClient import CollectionStorer
+
+def get_key_from_resource(resource):
+    return resource.path
+
+def ensure_correct_remote_webdav_hierarchy(remote_webdav_share_resources,
+                                           remote_webdav_share_collections):
+    pass
+    #assert len(remote_webdav_share_collections.keys()) == 1
+
+class WebDavUrlManager(gobject.GObject):
+    """
+    This class holds all data, relevant to a WebDavUrl.
+
+    One thing must be noted, that a valid WebDavUrl is the one which
+    may contain zero or more resources (files), or zero or more
+    collections (directories).
+
+    Thus, following are valid WebDavUrls ::
+
+        dav://1.2.3.4/webdav
+        dav://1.2.3.4/webdav/dir_1
+        dav://1.2.3.4/webdav/dir_1/dir_2
+
+    but following are not ::
+
+        dav://1.2.3.4/webdav/a.txt
+        dav://1.2.3.4/webdav/dir_1/b.jpg
+        dav://1.2.3.4/webdab/dir_1/dir_2/c.avi
+    """
+
+    def __init__(self, WebDavUrl, username, password):
+        self._WebDavUrl = WebDavUrl
+        self._username = username
+        self._password = password
+
+    def _get_key_from_resource(self, resource):
+        return resource.path.encode(sys.getfilesystemencoding())
+
+    def _get_number_of_collections(self):
+        return len(self._remote_webdav_share_collections)
+
+    def _get_resources_dict(self):
+        return self._remote_webdav_share_resources
+
+    def _get_collections_dict(self):
+        return self._remote_webdav_share_collections
+
+    def _get_resource_by_key(self, key):
+        return self._remote_webdav_share_resources[key]['resource']
+
+    def _get_metadata_list(self):
+        metadata_list = []
+        for key in self._remote_webdav_share_resources.keys():
+            metadata_list.append(self._remote_webdav_share_resources[key]['metadata'])
+        return metadata_list
+
+    def _get_live_properties(self, resource_key):
+        resource_container = self._remote_webdav_share_resources[resource_key]
+        return resource_container['webdav-properties']
+
+    def _set_metadata_for_resource(self, key, metadata):
+        self._remote_webdav_share_resources[key]['metadata'] = metadata
+
+    def _fetch_resources_and_collections(self):
+        webdavConnection = CollectionStorer(self._WebDavUrl, validateResourceNames=False)
+
+        authFailures = 0
+        while authFailures < 2:
+            try:
+                self._remote_webdav_share_resources = {}
+                self._remote_webdav_share_collections = {}
+
+                try:
+                    self._collection_contents = webdavConnection.getCollectionContents()
+                    for resource, properties in self._collection_contents:
+                        try:
+                            key = self._get_key_from_resource(resource)
+                            selected_dict = None
+
+                            if properties.getResourceType() == 'resource':
+                                selected_dict = self._remote_webdav_share_resources
+                            else:
+                                selected_dict = self._remote_webdav_share_collections
+
+                            selected_dict[key] = {}
+                            selected_dict[key]['resource'] = resource
+                            selected_dict[key]['webdav-properties'] = properties
+                        except UnicodeEncodeError:
+                            print("Cannot encode resource path or properties.")
+
+                    return True
+
+                except WebdavError, e:
+                    # Note that, we need to deal with all errors,
+                    # except "AuthorizationError", as that is not
+                    # really an error from our perspective.
+                    if not type(e) == AuthorizationError:
+                        from jarabe.journal.journalactivity import get_journal
+
+                        error_message = e
+                        get_journal()._volume_error_cb(None, error_message,_('Error'))
+
+                        # Simply return, in case of connection-not-available.
+                        return False
+
+                    else:
+                    # If this indeed is an Authorization Error,
+                    # re-raise it, so that it is caught by the outer
+                    # "except" block.
+                        raise e
+
+
+            except AuthorizationError, e:
+                if self._username is None or self._password is None:
+                    raise Exception("WebDav username or password is None. Please specify appropriate values.")
+
+                if e.authType == "Basic":
+                    webdavConnection.connection.addBasicAuthorization(self._username, self._password)
+                elif e.authType == "Digest":
+                    info = parseDigestAuthInfo(e.authInfo)
+                    webdavConnection.connection.addDigestAuthorization(self._username, self._password, realm=info["realm"], qop=info["qop"], nonce=info["nonce"])
+                else:
+                    raise
+                authFailures += 1
+
+        return False
+
+webdav_manager = {}
+
+
+def get_resource_by_ip_address_and_resource_key(ip_address, key):
+    global webdav_manager
+
+    if ip_address in webdav_manager.keys():
+        root_webdav = webdav_manager[ip_address]
+        resources_dict = root_webdav._get_resources_dict()
+        resource_dict = resources_dict[key]
+        resource = resource_dict['resource']
+
+        return resource
+
+
+def get_remote_webdav_share_metadata(ip_address):
+    protocol = 'dav://'
+
+    root_webdav_url = '/webdav'
+
+    complete_root_url = protocol + ip_address + root_webdav_url
+
+    root_webdav = WebDavUrlManager(complete_root_url, 'test', 'olpc')
+    if root_webdav._fetch_resources_and_collections() is False:
+        # Return empty metadata list.
+        return []
+
+    # Keep reference to the "WebDavUrlManager", keyed by IP-Address.
+    global webdav_manager
+    webdav_manager[ip_address] = root_webdav
+
+
+    # Assert that the number of collections is only one at this url
+    # (i.e. only ".Sugar-Metadata" is present).
+    assert root_webdav._get_number_of_collections() == 1
+
+    root_sugar_metadata_url = root_webdav_url + '/.Sugar-Metadata'
+
+    complete_root_sugar_metadata_url = protocol + ip_address + root_sugar_metadata_url
+    root_webdav_sugar_metadata = WebDavUrlManager(complete_root_sugar_metadata_url, 'test', 'olpc')
+    if root_webdav_sugar_metadata._fetch_resources_and_collections() is False:
+        # Return empty metadata list.
+        return []
+
+    # assert that the number of collections is zero at this url.
+    assert root_webdav_sugar_metadata._get_number_of_collections() == 0
+
+    # Now. associate sugar-metadata with each of the "root-webdav"
+    # resource.
+    root_webdav_resources = root_webdav._get_resources_dict()
+    root_webdav_sugar_metadata_resources = root_webdav_sugar_metadata._get_resources_dict()
+
+    # Prepare the metadata-download folder.
+    downloaded_data_root_dir = '/tmp/' + ip_address
+    downloaded_metadata_file_dir = downloaded_data_root_dir + '/.Sugar-Metadata'
+    if os.path.isdir(downloaded_data_root_dir):
+        shutil.rmtree(downloaded_data_root_dir)
+    os.makedirs(downloaded_metadata_file_dir)
+
+    for root_webdav_resource_name in root_webdav_resources.keys():
+        """
+        root_webdav_resource_name is of the type ::
+
+            /webdav/a.txt
+        """
+        split_tokens_array = root_webdav_resource_name.split('/')
+
+        # This will provide us with "a.txt"
+        basename = split_tokens_array[len(split_tokens_array) - 1]
+
+        # This will provide us with "a.txt.metadata"
+        sugar_metadata_basename = basename + '.metadata'
+
+        # Thus will provide us with "/webdav/.Sugar-Metadata/a.txt.metadata"
+        sugar_metadata_url = root_sugar_metadata_url + '/' + sugar_metadata_basename
+
+        # Ensure that "sugar_metadata_url" is present as one of the
+        # keys in "root_webdav_sugar_metadata_resources"
+        assert sugar_metadata_url in root_webdav_sugar_metadata_resources.keys()
+
+        # Now download the metadata file, read its contents, and store
+        # the metadata in memory.
+        # It is assumed that the metadata-file is small enough to be
+        # read in one call to "read".
+
+        downloaded_metadata_file_path = downloaded_metadata_file_dir + '/' + sugar_metadata_basename
+        metadata_resource = root_webdav_sugar_metadata._get_resource_by_key(sugar_metadata_url)
+        metadata_resource.downloadFile(downloaded_metadata_file_path)
+
+        file_pointer = open(downloaded_metadata_file_path)
+        metadata = eval(file_pointer.read())
+        file_pointer.close()
+
+        # Very critical.
+        # 1. CRITICAL ONE:
+        #    Fill in the uid.
+        #    Note that the file is not physically present.
+        metadata['uid'] = downloaded_data_root_dir + '/' + basename
+
+        # 2. CRITICAL TWO:
+        #    Fill in the properties, that can only be done by reading
+        #    in the webdav-properties.
+        live_properties = root_webdav._get_live_properties(root_webdav_resource_name)
+        metadata['filesize'] = live_properties.getContentLength()
+        metadata['timestamp'] = live_properties.getLastModified()
+        metadata['creation_time'] = live_properties.getCreationDate()
+
+        # Now, write this to the metadata-file, so that
+        # webdav-properties get gelled into sugar-metadata.
+
+        file_pointer = open(downloaded_metadata_file_path, 'w')
+        file_pointer.write(simplejson.dumps(metadata))
+        file_pointer.close()
+
+        root_webdav._set_metadata_for_resource(root_webdav_resource_name,
+                                               metadata)
+
+    return root_webdav._get_metadata_list()
diff --git a/src/jarabe/model/buddy.py b/src/jarabe/model/buddy.py
index 8f17d7e..c088aa9 100644
--- a/src/jarabe/model/buddy.py
+++ b/src/jarabe/model/buddy.py
@@ -43,6 +43,7 @@ class BaseBuddyModel(gobject.GObject):
         self._color = None
         self._tags = None
         self._current_activity = None
+        self._ip_address = None
 
         gobject.GObject.__init__(self, **kwargs)
 
@@ -87,6 +88,16 @@ class BaseBuddyModel(gobject.GObject):
                                         getter=get_current_activity,
                                         setter=set_current_activity)
 
+    def get_ip_address(self):
+        return self._ip_address
+
+    def set_ip_address(self, ip_address):
+        self._ip_address = ip_address
+
+    ip_address = gobject.property(type=object,
+                                  getter=get_ip_address,
+                                  setter=set_ip_address)
+
     def is_owner(self):
         raise NotImplementedError
 
diff --git a/src/jarabe/model/neighborhood.py b/src/jarabe/model/neighborhood.py
index 4528a15..39f648e 100644
--- a/src/jarabe/model/neighborhood.py
+++ b/src/jarabe/model/neighborhood.py
@@ -930,6 +930,9 @@ class Neighborhood(gobject.GObject):
         if 'key' in properties:
             buddy.props.key = properties['key']
 
+        if 'ip4-address' in properties:
+            buddy.props.ip_address = properties['ip4-address']
+
         nick_key = CONNECTION_INTERFACE_ALIASING + '/alias'
         if nick_key in properties:
             buddy.props.nick = properties[nick_key]
diff --git a/src/jarabe/view/buddymenu.py b/src/jarabe/view/buddymenu.py
index de5a772..dfbcfa3 100644
--- a/src/jarabe/view/buddymenu.py
+++ b/src/jarabe/view/buddymenu.py
@@ -73,6 +73,12 @@ class BuddyMenu(Palette):
         self.menu.append(menu_item)
         menu_item.show()
 
+        access_buddy_remote_share_menu_item = MenuItem(_('Access Share'), 'list-add')
+        access_buddy_remote_share_menu_item.connect('activate',
+                self._access_share_cb)
+        self.menu.append(access_buddy_remote_share_menu_item)
+        access_buddy_remote_share_menu_item.show()
+
         self._invite_menu = MenuItem('')
         self._invite_menu.connect('activate', self._invite_friend_cb)
         self.menu.append(self._invite_menu)
@@ -83,6 +89,11 @@ class BuddyMenu(Palette):
         activity = home_model.get_active_activity()
         self._update_invite_menu(activity)
 
+    def _access_share_cb(self, menuitem):
+        from jarabe.journal.journalactivity import get_journal
+        volumes_toolbar = get_journal().get_volumes_toolbar()
+        volumes_toolbar._add_remote_share_button(self._buddy)
+
     def _add_my_items(self):
         item = MenuItem(_('Shutdown'), 'system-shutdown')
         item.connect('activate', self.__shutdown_activate_cb)
diff --git a/src/jarabe/view/palettes.py b/src/jarabe/view/palettes.py
index 7a17f32..3b26faf 100644
--- a/src/jarabe/view/palettes.py
+++ b/src/jarabe/view/palettes.py
@@ -336,3 +336,36 @@ class JournalXSPalette(Palette):
     def __journal_restore_activate_cb(self, menu_item, xs_hostname):
         dialog = XSRestoreDialog(xs_hostname)
         dialog.show()
+
+
+class RemoteSharePalette(Palette):
+    def __init__(self, buddy, button):
+        Palette.__init__(self, label=('%s\'s share' % buddy.props.nick))
+        self._buddy = buddy
+        self._button = button
+
+        self.props.secondary_text = glib.markup_escape_text(buddy.props.ip_address)
+
+        vbox = gtk.VBox()
+        self.set_content(vbox)
+        vbox.show()
+
+        self.connect('popup', self.__popup_cb)
+
+        menu_item = MenuItem(pgettext('Share', 'Unmount'))
+
+        icon = Icon(icon_name='media-eject', icon_size=gtk.ICON_SIZE_MENU)
+        menu_item.set_image(icon)
+        icon.show()
+
+        menu_item.connect('activate', self.__unmount_activate_cb)
+        self.menu.append(menu_item)
+        menu_item.show()
+
+    def __unmount_activate_cb(self, menu_item):
+        from jarabe.journal.journalactivity import get_journal
+        singleton_volumes_toolbar = get_journal().get_volumes_toolbar()
+        singleton_volumes_toolbar._remove_remote_share_button(self._buddy.props.ip_address)
+
+    def __popup_cb(self, palette):
+        pass
diff --git a/src/webdav/Condition.py b/src/webdav/Condition.py
new file mode 100644
index 0000000..76acf94
--- /dev/null
+++ b/src/webdav/Condition.py
@@ -0,0 +1,475 @@
+# pylint: disable-msg=R0921,W0704,R0901,W0511,R0201
+# Copyright 2008 German Aerospace Center (DLR)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+ 
+
+"""
+This module contains classes for creating a search condition according to the DASL draft.
+The classes will output the WHERE part of a search request to a WebDAV server.
+
+Instances of the classes defined in this module form a tree data structure which represents
+a search condition. This tree is made up of AND-nodes, OR-nodes, Operator- and comparison-
+nodes and from property (i.e. variable) and constant leaf nodes.
+"""
+
+
+import types
+from time import strftime
+from calendar import timegm
+from rfc822 import formatdate
+
+from webdav.Constants import NS_DAV, PROP_LAST_MODIFIED, DATE_FORMAT_ISO8601
+
+
+__version__ = "$Revision$"[11:-2]
+
+
+class ConditionTerm(object):
+    """
+    This is the abstact base class for all condition terms.
+    """
+    def __init__(self):
+        pass
+    
+    def toXML(self):
+        """
+        Abstact method which return a XML string which can be passed to a WebDAV server
+        for a search condition.
+        """
+        raise NotImplementedError
+    
+    # start Tamino workaround for missing like-op:
+    def postFilter(self, resultSet):
+        """
+        Abstact method for temporary workaround for Tamino's absense of the like-operator.
+        This method shall filter the given result set for those resources which match
+        all Contains-trems.
+        """
+        return resultSet
+    # end of workaround
+
+
+class IsCollectionTerm(ConditionTerm):
+    """ Leaf condition. Checks if the matching resources are collections. """
+    
+    def __init__(self):
+        """ Constructor. """
+        
+        ConditionTerm.__init__(self)
+
+    def toXML(self):
+        """
+        Returns XML encoding.
+        """
+        
+        return "<D:is-collection/>"
+
+
+class Literal(ConditionTerm):
+    """
+    A leaf class for condition expressions representing a constant value.
+    """
+    def __init__(self, literal):
+        ConditionTerm.__init__(self)
+        self.literal = literal
+        
+    def toXML(self):
+        '''
+        Returns XML encoding.
+        '''
+        return "<D:literal>" + self.literal + "</D:literal>"
+    
+
+class UnaryTerm(ConditionTerm):
+    """
+    Base class of all nodes with a single child node.
+    """
+    def __init__(self, child):
+        ConditionTerm.__init__(self)
+        self.child = child
+    
+    def toXML(self):
+        '''
+        Returns XML encoding.
+        '''
+        return self.child.toXML()
+    
+    
+class BinaryTerm(ConditionTerm):
+    """
+    Base class of all nodes with two child nodes
+    """
+    def __init__(self, left, right):
+        ConditionTerm.__init__(self)
+        self.left = left
+        self.right = right
+    
+    def toXML(self):
+        '''
+        Returns XML encoding.
+        '''
+        return self.left.toXML() + self.right.toXML()
+
+class TupleTerm(ConditionTerm):
+    """
+    Base class of all nodes with multiple single child nodes.
+    """
+    def __init__(self, terms):
+        ConditionTerm.__init__(self)
+        self.terms = terms
+    
+    def addTerm(self, term):
+        '''
+        Removes a term.
+        
+        @param term: term to add
+        '''
+        self.terms.append(term)
+    
+    def removeTerm(self, term):
+        '''
+        Adds a term.
+        
+        @param term: term to remove
+        '''   
+        try:
+            self.terms.remove(term)
+        except ValueError:
+            pass
+                
+    def toXML(self):
+        '''
+        Returns XML encoding.
+        '''
+        result = ""
+        for term in self.terms:
+            result += term.toXML()
+        return result
+
+
+class AndTerm(TupleTerm):
+    """
+    This class represents and logical AND-condition with multiple sub terms.
+    """
+    def toXML(self):
+        '''
+        Returns XML encoding.
+        '''
+        return "<D:and>" + TupleTerm.toXML(self) + "</D:and>"
+
+    # start Tamino workaround for missing like-op:
+    def postFilter(self, resultSet):
+        '''
+        Filters the given result set. This is a TAMINO WebDav server workaround
+        for the missing 'like' tag.
+        
+        @param resultSet: the result set that needs to be filtered.
+        '''
+        for term in self.terms:
+            filtered = term.postFilter(resultSet)
+            resultSet = filtered
+        return resultSet
+    # end of workaround
+
+class OrTerm(TupleTerm):
+    """
+    This class represents and logical OR-condition with multiple sub terms.
+    """
+    def toXML(self):
+        '''
+        Returns XML encoding.
+        '''
+        return "<D:or>" + TupleTerm.toXML(self) + "</D:or>"
+    
+    # start Tamino workaround for missing like-op:
+    def postFilter(self, resultSet):
+        '''
+        Filters the given result set. This is a TAMINO WebDav server workaround
+        for the missing 'like' tag.
+        
+        @param resultSet: the result set that needs to be filtered.
+        '''
+        raise NotImplementedError
+
+   
+class NotTerm(UnaryTerm):
+    """
+    This class represents a negation term for the contained sub term.
+    """
+    def toXML(self):
+        '''
+        Returns XML encoding.
+        '''
+        # start Tamino workaround for missing like-op:
+        if  isinstance(self.child, ContainsTerm):
+            return ""
+        # end of workaround        
+        return "<D:not>" + UnaryTerm.toXML(self) + "</D:not>"
+
+    # start Tamino workaround for missing like-op:
+    def postFilter(self, resultSet):
+        '''
+        Filters the given result set. This is a TAMINO WebDav server workaround
+        for the missing 'like' tag.
+        
+        @param resultSet: the result set that needs to be filtered.
+        '''
+        if  isinstance(self.child, ContainsTerm):
+            self.child.negate = 1
+            # TODO: pass on filter
+        return self.child.postFilter(resultSet)
+        
+
+class ExistsTerm(UnaryTerm):
+    """
+    Nodes of this class must have a single child with tuple type (of len 2) representing a 
+    WebDAV property.
+    This leaf term evaluates to true if the (child) property exists.
+    """
+    def toXML(self):
+        '''
+        Returns XML encoding.
+        '''
+        return '<D:is-defined><D:prop xmlns="%s"><%s' % self.child + ' /></D:prop></D:is-defined>'
+
+class ContentContainsTerm(UnaryTerm):
+    """
+    This class can be used to search for a given phrase in resources' contents.
+    """
+    def toXML(self):
+        '''
+        Returns XML encoding.
+        '''
+        return "<D:contains>" + self.child + "</D:contains>"
+
+
+
+class BinaryRelationTerm(BinaryTerm):
+    """
+    This is the abstact base class for the following relation operands.
+    """
+    def __init__(self, left, right):
+        BinaryTerm.__init__(self, left, right)
+        if isinstance(self.left, types.StringType):     # Must be namespace + name pair
+            self.left = ('DAV:', self.left)
+        if not isinstance(self.right, Literal):
+            self.right = Literal(self.right)             # Must be Literal instance
+
+    def toXML(self):
+        '''
+        Returns XML encoding.
+        '''
+        ## TODO: extract name space and create shortcut for left element
+        return '<D:prop xmlns="%s"><%s /></D:prop>' % self.left + self.right.toXML()
+
+        
+class StringRelationTerm(BinaryRelationTerm):
+    """
+    This is the abstact base class for the following string relation classes.
+    """
+    def __init__(self, left, right, caseless=None):
+        """
+        @param left: webdav property (namespace, name)
+        @param right: string/unicode literal
+        qparam caseless: 1 for case sensitive comparison
+        """
+        BinaryRelationTerm.__init__(self, left, Literal(right))
+        self.caseless = caseless
+        if self.caseless:
+            self.attrCaseless = "yes"
+        else:
+            self.attrCaseless = "no"
+        
+class NumberRelationTerm(BinaryRelationTerm):
+    """
+    This is the abstact base class for the following number comparison classes.
+    """
+    def __init__(self, left, right):
+        """
+        @param left: webdav property (namespace, name)
+        @param right: constant number
+        """
+        ## TODO: implemet typed literal
+        BinaryRelationTerm.__init__(self, left, Literal(str(right)))
+
+class DateRelationTerm(BinaryRelationTerm):
+    """
+    This is the abstact base class for the following date comparison classes.
+    """
+    def __init__(self, left, right):
+        """
+        @param left: webdav property (namespace, name)
+        @param right: string literal containing a date in ISO8601 format
+        """
+        ## TODO: implemet typed literal
+        assert len(right) == 9, "No time is specified for literal: " + str(right)
+        BinaryRelationTerm.__init__(self, left, right)        
+        if self.left == (NS_DAV, PROP_LAST_MODIFIED):
+            rfc822Time = formatdate(timegm(right))      # must not use locale setting                  
+            self.right = Literal(rfc822Time)
+        else:               
+            self.right = Literal(strftime(DATE_FORMAT_ISO8601, right))
+
+
+class MatchesTerm(StringRelationTerm):
+    """
+    Nodes of this class evaluate to true if the (child) property's value matches the (child) string.
+    """
+    def toXML(self):
+        '''
+        Returns XML encoding.
+        '''
+        return '<D:eq caseless="%s">' % self.attrCaseless + StringRelationTerm.toXML(self) + "</D:eq>"
+
+class ContainsTerm(StringRelationTerm):        
+    """
+    Nodes of this class evaluate to true if the (left child) property's value contains the
+    (right child) string.
+    """
+    def __init__(self, left, right, isTaminoWorkaround=False):
+        right = unicode(right)
+        StringRelationTerm.__init__(self, left, "%" + right + "%")
+        # Tamino workaround: operator like is not yet implemented:
+        self.negate = 0
+        self.isTaminoWorkaround = isTaminoWorkaround 
+            
+    def toXML(self):
+        '''
+        Returns XML encoding.
+        '''
+        # Tamino workaround: operator like is not yet implemented:
+        # Produce a is-defined-condition instead
+        if self.isTaminoWorkaround:
+            return "<D:isdefined><D:prop xmlns='%s'><%s" % self.left + " /></D:prop></D:isdefined>"
+        else:
+            return '<D:like caseless="%s">' % self.attrCaseless + StringRelationTerm.toXML(self) + "</D:like>"
+        
+    # start Tamino workaround for missing like-op:
+    def postFilter(self, resultSet):
+        '''
+        Filters the given result set. This is a TAMINO WebDav server workaround
+        for the missing 'like' tag.
+        
+        @param resultSet: the result set that needs to be filtered.
+        '''
+        newResult = {}
+        word = self.right.literal[1:-1]       # remove leading and trailing '%' characters (see __init__())
+        for url, properties in resultSet.items():
+            value = properties.get(self.left)
+            if self.negate:
+                if not value or value.textof().find(word) < 0:
+                    newResult[url] = properties                
+            else:
+                if value and value.textof().find(word) >= 0:
+                    newResult[url] = properties
+        return newResult
+    # end of workaround
+
+class IsEqualTerm(NumberRelationTerm):
+    """
+    Nodes of this class evaluate to true if the (left child) numerical property's value is equal
+    to the (right child) number.
+    """
+    def toXML(self):
+        '''
+        Returns XML encoding.
+        '''
+        return "<D:eq>" + NumberRelationTerm.toXML(self) + "</D:eq>"
+
+class IsGreaterTerm(NumberRelationTerm):
+    """
+    Nodes of this class evaluate to true if the (left child) numerical property's value is greater
+    than the (right child) number.
+    """
+    def toXML(self):
+        '''
+        Returns XML encoding.
+        '''
+        return "<D:gt>" + NumberRelationTerm.toXML(self) + "</D:gt>"
+
+class IsGreaterOrEqualTerm(NumberRelationTerm):
+    """
+    Nodes of this class evaluate to true if the (left child) numerical property's value is greater
+    than or equal to the (right child) number.
+    """
+    def toXML(self):
+        '''
+        Returns XML encoding.
+        '''
+        return "<D:gte>" + NumberRelationTerm.toXML(self) + "</D:gte>"
+
+class IsSmallerTerm(NumberRelationTerm):
+    """
+    Nodes of this class evaluate to true if the (left child) numerical property's value is less
+    than the (right child) number.
+    """
+    def toXML(self):
+        '''
+        Returns XML encoding.
+        '''
+        return "<D:lt>" + NumberRelationTerm.toXML(self) + "</D:lt>"
+
+class IsSmallerOrEqualTerm(NumberRelationTerm):
+    """
+    Nodes of this class evaluate to true if the (left child) numerical property's value is less
+    than or equal to the (right child) number.
+    """
+    def toXML(self):
+        '''
+        Returns XML encoding.
+        '''
+        return "<D:lte>" + NumberRelationTerm.toXML(self) + "</D:lte>"
+
+
+class OnTerm(DateRelationTerm):
+    """
+    Nodes of this class evaluate to true if the (left child) property's value is a date
+    equal to the (right child) date.
+    """
+    def toXML(self):
+        '''
+        Returns XML encoding.
+        '''
+        return "<D:eq>" + DateRelationTerm.toXML(self) + "</D:eq>"
+
+class AfterTerm(DateRelationTerm):
+    """
+    Nodes of this class evaluate to true if the (left child) property's value is a date
+    succeeding the (right child) date.
+    """
+    def toXML(self):
+        '''
+        Returns XML encoding.
+        '''
+        return "<D:gt>" + DateRelationTerm.toXML(self) + "</D:gt>"
+
+class BeforeTerm(DateRelationTerm):
+    """
+    Nodes of this class evaluate to true if the (left child) property's value is a date
+    preceeding the (right child) date.
+    """
+    def toXML(self):
+        '''
+        Returns XML encoding.
+        '''
+        return "<D:lt>" + DateRelationTerm.toXML(self) + "</D:lt>"
+
+
+    
+# Simple module test
+if  __name__ == '__main__':
+    # use the example from the webdav specification
+    condition = AndTerm( (MatchesTerm('getcontenttype', 'image/gif'), \
+                IsGreaterTerm('getcontentlength', 4096)) )
+    print "Where: " + condition.toXML()
diff --git a/src/webdav/Connection.py b/src/webdav/Connection.py
new file mode 100644
index 0000000..66f7833
--- /dev/null
+++ b/src/webdav/Connection.py
@@ -0,0 +1,321 @@
+# pylint: disable-msg=W0142,W0102,R0901,R0904,E0203,E1101,C0103
+#
+# Copyright 2008 German Aerospace Center (DLR)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+"""
+The contained class extends the HTTPConnection class for WebDAV support.
+"""
+
+
+from httplib import HTTPConnection, CannotSendRequest, BadStatusLine, ResponseNotReady
+from copy import copy
+import base64   # for basic authentication
+try:
+    import hashlib
+except ImportError: # for Python 2.4 compatibility
+    import md5
+    hashlib = md5
+import mimetypes
+import os       # file handling
+import urllib
+import types
+import socket   # to "catch" socket.error
+from threading import RLock
+try:
+    from uuid import uuid4
+except ImportError: # for Python 2.4 compatibility
+    from uuid_ import uuid4
+from xml.parsers.expat import ExpatError
+
+from davlib import DAV
+from qp_xml import Parser
+
+from webdav.WebdavResponse import MultiStatusResponse, ResponseFormatError
+from webdav import Constants
+from webdav.logger import getDefaultLogger
+
+
+__version__ = "$LastChangedRevision$"
+
+
+class Connection(DAV):
+    """
+    This class handles a connection to a WebDAV server.
+    This class is used internally. Client code should prefer classes
+    L{WebdavClient.ResourceStorer} and L{WebdavClient.CollectionStorer}.
+    
+    @author: Roland Betz
+    """
+    
+    # Constants
+    #  The following switch activates a workaround for the Tamino webdav server:
+    #  Tamino expects URLs which are passed in a HTTP header to be Latin-1 encoded
+    #  instead of Utf-8 encoded.
+    #  Set this switch to zero in order to communicate with conformant servers.
+    blockSize = 30000
+    MaxRetries = 10
+    
+    def __init__(self, *args, **kwArgs):
+        DAV.__init__(self, *args, **kwArgs)
+        self.__authorizationInfo = None
+        self.logger = getDefaultLogger()
+        self.isConnectedToCatacomb = True
+        self.serverTypeChecked = False
+        self._lock = RLock()
+         
+    def _request(self, method, url, body=None, extra_hdrs={}):
+        
+        self._lock.acquire()
+        try:
+            # add the authorization header
+            extraHeaders = copy(extra_hdrs)
+            if self.__authorizationInfo:
+
+                # update (digest) authorization data
+                if hasattr(self.__authorizationInfo, "update"):
+                    self.__authorizationInfo.update(method=method, uri=url)
+                
+                extraHeaders["AUTHORIZATION"] = self.__authorizationInfo.authorization
+            
+            # encode message parts
+            body = _toUtf8(body)
+            url = _urlEncode(url)
+            for key, value in extraHeaders.items():
+                extraHeaders[key] = _toUtf8(value)
+                if key == "Destination": # copy/move header
+                    if self.isConnectedToCatacomb:
+                        extraHeaders[key] = _toUtf8(value.replace(Constants.SHARP, Constants.QUOTED_SHARP))
+                        
+                    else: # in case of TAMINO 4.4
+                        extraHeaders[key] = _urlEncode(value)
+            # pass message to httplib class
+            for retry in range(0, Connection.MaxRetries):    # retry loop
+                try:
+                    self.logger.debug("REQUEST Send %s for %s" % (method, url))
+                    self.logger.debug("REQUEST Body: " + repr(body))
+                    for hdr in extraHeaders.items():
+                        self.logger.debug("REQUEST Header: " + repr(hdr))
+                    self.request(method, url, body, extraHeaders)
+                    response = self.getresponse()
+                    break  # no retry needed
+                except (CannotSendRequest, socket.error, BadStatusLine, ResponseNotReady), exc:
+                    # Workaround, start: reconnect and retry...
+                    self.logger.debug("Exception: " + str(exc) + " Retry ... ")
+                    self.close()
+                    try:
+                        self.connect()
+                    except (CannotSendRequest, socket.error, BadStatusLine, ResponseNotReady), exc:
+                        raise WebdavError("Cannot perform request. Connection failed.")
+                    if retry == Connection.MaxRetries - 1:
+                        raise WebdavError("Cannot perform request.")
+            return self.__evaluateResponse(method, response)
+        finally:
+            self._lock.release()
+        
+    def __evaluateResponse(self, method, response):
+        """ Evaluates the response of the WebDAV server. """
+        
+        status, reason = response.status, response.reason
+        self.logger.debug("Method: " + method + " Status %d: " % status + reason)
+        
+        if status >= Constants.CODE_LOWEST_ERROR:     # error has occured ?
+            self.logger.debug("ERROR Response: " + response.read())
+            
+            # identify authentication CODE_UNAUTHORIZED, throw appropriate exception
+            if status == Constants.CODE_UNAUTHORIZED:
+                raise AuthorizationError(reason, status, response.msg["www-authenticate"])
+            
+            response.close()
+            raise WebdavError(reason, status)
+        
+        if status == Constants.CODE_MULTISTATUS:
+            content = response.read()
+            ## check for UTF-8 encoding
+            try:
+                response.root = Parser().parse(content)
+            except ExpatError, error:
+                errorMessage = "Invalid XML document has been returned.\nReason: '%s'" % str(error.args)
+                raise WebdavError(errorMessage)
+            try:
+                response.msr = MultiStatusResponse(response.root)
+            except ResponseFormatError:
+                raise WebdavError("Invalid WebDAV response.")
+            response.close()
+            self.logger.debug("RESPONSE (Multi-Status): " + unicode(response.msr))
+        elif method == 'LOCK' and status == Constants.CODE_SUCCEEDED:
+            response.parse_lock_response()
+            response.close()
+        elif method != 'GET' and method != 'PUT':
+            self.logger.debug("RESPONSE Body: " + response.read())
+            response.close()
+        return response
+        
+    def addBasicAuthorization(self, user, password, realm=None):
+        if user and len(user) > 0:
+            self.__authorizationInfo = _BasicAuthenticationInfo(realm=realm, user=user, password=password)
+                   
+    def addDigestAuthorization(self, user, password, realm, qop, nonce, uri = None, method = None):
+        if user and len(user) > 0:
+            # username, realm, password, uri, method, qop are required
+            self.__authorizationInfo = _DigestAuthenticationInfo(realm=realm, user=user, password=password, uri=uri, method=method, qop=qop, nonce=nonce)
+
+    def putFile(self, path, srcfile, header={}):
+        self._lock.acquire()
+        try:
+            # Assemble header
+            try:
+                size = os.path.getsize(srcfile.name)    
+            except os.error, error:
+                raise WebdavError("Cannot determine file size.\nReason: ''" % str(error.args))
+            header["Content-length"] = str(size)
+            
+            contentType, contentEnc = mimetypes.guess_type(path)
+            if contentType:
+                header['Content-Type'] = contentType
+            if contentEnc:
+                header['Content-Encoding'] = contentEnc
+            if self.__authorizationInfo:
+                # update (digest) authorization data
+                if hasattr(self.__authorizationInfo, "update"):
+                    self.__authorizationInfo.update(method="PUT", uri=path)
+                header["AUTHORIZATION"] = self.__authorizationInfo.authorization
+                
+            # send first request
+            path = _urlEncode(path)
+            try:
+                HTTPConnection.request(self, 'PUT', path, "", header)
+                self._blockCopySocket(srcfile, self, Connection.blockSize)
+                srcfile.close()
+                response = self.getresponse()
+            except (CannotSendRequest, socket.error, BadStatusLine, ResponseNotReady), exc:
+                self.logger.debug("Exception: " + str(exc) + " Retry ... ")
+                raise WebdavError("Cannot perform request.")
+            status, reason = (response.status, response.reason)
+            self.logger.debug("Status %d: %s" % (status, reason))
+            try:
+                if status >= Constants.CODE_LOWEST_ERROR:     # error has occured ?
+                    raise WebdavError(reason, status)
+            finally:
+                self.logger.debug("RESPONSE Body: " + response.read())
+                response.close()        
+            return response
+        finally:
+            self._lock.release()
+                  
+    def _blockCopySocket(self, source, toSocket, blockSize):
+        transferedBytes = 0
+        block = source.read(blockSize)
+        #while source.readinto(block, blockSize):
+        while len(block):
+            toSocket.send(block)
+            self.logger.debug("Wrote %d bytes." % len(block))
+            transferedBytes += len(block)
+            block = source.read(blockSize)        
+        self.logger.info("Transfered %d bytes." % transferedBytes)
+
+    def __str__(self):
+        return self.protocol + "://" + self.host + ':' + str(self.port)
+        
+
+class _BasicAuthenticationInfo(object):
+    def __init__(self, **kwArgs):
+        self.__dict__.update(kwArgs)
+        self.cookie = base64.encodestring("%s:%s" % (self.user, self.password) ).strip()
+        self.authorization = "Basic " + self.cookie
+        self.password = None     # protect password security
+        
+class _DigestAuthenticationInfo(object):
+    
+    __nc = "0000000" # in hexadecimal without leading 0x
+    
+    def __init__(self, **kwArgs):
+
+        self.__dict__.update(kwArgs)
+        
+        if self.qop is None:
+            raise WebdavError("Digest without qop is not implemented.")
+        if self.qop == "auth-int":
+            raise WebdavError("Digest with qop-int is not implemented.")
+    
+    def update(self, **kwArgs):
+        """ Update input data between requests"""
+    
+        self.__dict__.update(kwArgs)
+
+    def _makeDigest(self):
+        """ Creates the digest information. """
+        
+        # increment nonce count
+        self._incrementNc()
+        
+        # username, realm, password, uri, method, qop are required
+        
+        a1 = "%s:%s:%s" % (self.user, self.realm, self.password)
+        ha1 = hashlib.md5(a1).hexdigest()
+
+        #qop == auth
+        a2 = "%s:%s" % (self.method, self.uri)
+        ha2 = hashlib.md5(a2).hexdigest()
+        
+        cnonce = str(uuid4())
+        
+        responseData = "%s:%s:%s:%s:%s:%s" % (ha1, self.nonce, _DigestAuthenticationInfo.__nc, cnonce, self.qop, ha2)
+        digestResponse = hashlib.md5(responseData).hexdigest()
+        
+        authorization = "Digest username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", algorithm=MD5, response=\"%s\", qop=auth, nc=%s, cnonce=\"%s\"" \
+                        % (self.user, self.realm, self.nonce, self.uri, digestResponse, _DigestAuthenticationInfo.__nc, cnonce)
+        return authorization
+    
+    authorization = property(_makeDigest)
+    
+    def _incrementNc(self):
+        _DigestAuthenticationInfo.__nc = self._dec2nc(self._nc2dec() + 1)
+    
+    def _nc2dec(self):
+        return int(_DigestAuthenticationInfo.__nc, 16)
+    
+    def _dec2nc(self, decimal):
+        return hex(decimal)[2:].zfill(8)
+    
+
+class WebdavError(IOError):
+    def __init__(self, reason, code=0):
+        IOError.__init__(self, code)
+        self.code = code
+        self.reason = reason
+    def __str__(self):
+        return self.reason
+
+
+class AuthorizationError(WebdavError):
+    def __init__(self, reason, code, authHeader):
+        WebdavError.__init__(self, reason, code)
+        
+        self.authType = authHeader.split(" ")[0]
+        self.authInfo = authHeader
+
+
+def _toUtf8(body):
+    if not body is None:
+        if type(body) == types.UnicodeType:
+            body = body.encode('utf-8')
+    return body
+
+
+def _urlEncode(url):
+    if type(url) == types.UnicodeType:
+        url = url.encode('utf-8')
+    return urllib.quote(url)
diff --git a/src/webdav/Constants.py b/src/webdav/Constants.py
new file mode 100644
index 0000000..56dfd77
--- /dev/null
+++ b/src/webdav/Constants.py
@@ -0,0 +1,199 @@
+# pylint: disable-msg=C0103
+#
+# Copyright 2008 German Aerospace Center (DLR)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+"""
+Contains XML tag names for the WebDAV protocol (RFC 2815)
+and further WebDAV related constants.
+"""
+
+
+__version__ = "$Revision$"[11:-2]
+
+
+QUOTED_SHARP = "%23"
+SHARP = "#"
+
+# Date formats
+DATE_FORMAT_ISO8601 = r"%Y-%m-%dT%H:%M:%SZ"
+DATE_FORMAT_HTTP = r"%a, %d %b %Y %H:%M:%S GMT"  # not used, substituted by rfc822 function
+
+NS_DAV = 'DAV:'
+NS_TAMINO = 'http://namespaces.softwareag.com/tamino/response2'
+
+TAG_PROPERTY_FIND   = 'propfind'
+TAG_PROPERTY_NAME   = 'propname'
+TAG_PROPERTY_UPDATE = 'propertyupdate'
+TAG_PROPERTY_SET    = 'set'
+TAG_PROPERTY_REMOVE = 'remove'
+TAG_ALL_PROPERTY    = 'allprop'
+TAG_PROP            = 'prop'
+
+TAG_MULTISTATUS         = 'multistatus'
+TAG_RESPONSE            = 'response'
+TAG_HREF                = 'href'
+TAG_PROPERTY_STATUS     = 'propstat'
+TAG_STATUS              = 'status'
+TAG_RESPONSEDESCRIPTION = 'responsdescription'
+
+PROP_CREATION_DATE    = 'creationdate'
+PROP_DISPLAY_NAME     = 'displayname'
+PROP_CONTENT_LANGUAGE = 'getcontentlanguage'
+PROP_CONTENT_LENGTH   = 'getcontentlength'
+PROP_CONTENT_TYPE     = 'getcontenttype'
+PROP_ETAG             = 'getetag'
+PROP_MODIFICATION_DATE = 'modificationdate' # this property is supported by
+# Tamino 4.4 but not by Catacomb; the date format is ISO8601
+PROP_LAST_MODIFIED    = 'getlastmodified'
+PROP_LOCK_DISCOVERY   = 'lockdiscovery'
+PROP_RESOURCE_TYPE    = 'resourcetype'
+PROP_SOURCE           = 'source'
+PROP_SUPPORTED_LOCK   = 'supportedlock'
+PROP_OWNER            = 'owner'
+
+PROP_RESOURCE_TYPE_RESOURCE    = 'resource'
+PROP_RESOURCE_TYPE_COLLECTION  = 'collection'
+
+TAG_LINK             = 'link'
+TAG_LINK_SOURCE      = 'src'
+TAG_LINK_DESTINATION = 'dst'
+
+TAG_LOCK_ENTRY     = 'lockentry'
+TAG_LOCK_SCOPE     = 'lockscope'
+TAG_LOCK_TYPE      = 'locktype'
+TAG_LOCK_INFO      = 'lockinfo'
+TAG_ACTIVE_LOCK    = 'activelock'
+TAG_LOCK_DEPTH     = 'depth'
+TAG_LOCK_TOKEN     = 'locktoken'
+TAG_LOCK_TIMEOUT   = 'timeout'
+TAG_LOCK_EXCLUSIVE = 'exclusive'
+TAG_LOCK_SHARED    = 'shared'
+TAG_LOCK_OWNER     = 'owner'
+
+# HTTP error code constants
+CODE_MULTISTATUS = 207
+CODE_SUCCEEDED = 200
+CODE_CREATED = 201
+CODE_NOCONTENT = 204
+
+CODE_LOWEST_ERROR = 300
+
+CODE_UNAUTHORIZED = 401
+CODE_FORBIDDEN = 403
+CODE_NOT_FOUND = 404
+CODE_CONFLICT = 409
+CODE_PRECONDITION_FAILED = 412
+CODE_LOCKED = 423   # no permission
+CODE_FAILED_DEPENDENCY = 424
+
+CODE_OUTOFMEM = 507
+
+# ?
+CONFIG_UNICODE_URL = 1
+
+# constants for WebDAV DASL according to draft
+
+TAG_SEARCH_REQUEST = 'searchrequest'
+TAG_SEARCH_BASIC   = 'basicsearch'
+TAG_SEARCH_SELECT  = 'select'
+TAG_SEARCH_FROM    = 'from'
+TAG_SEARCH_SCOPE   = 'scope'
+TAG_SEARCH_WHERE   = 'where'
+
+# constants for WebDAV ACP (according to draft-ietf-webdav-acl-09) below ...
+
+TAG_ACL                 = 'acl'
+TAG_ACE                 = 'ace'
+TAG_GRANT               = 'grant'
+TAG_DENY                = 'deny'
+TAG_PRIVILEGE           = 'privilege'
+TAG_PRINCIPAL           = 'principal'
+TAG_ALL                 = 'all'
+TAG_AUTHENTICATED       = 'authenticated'
+TAG_UNAUTHENTICATED     = 'unauthenticated'
+TAG_OWNER               = 'owner'
+TAG_PROPERTY            = 'property'
+TAG_SELF                = 'self'
+TAG_INHERITED           = 'inherited'
+TAG_PROTECTED           = 'protected'
+TAG_SUPPORTED_PRIVILEGE = 'supported-privilege'
+TAG_DESCRIPTION         = 'description'
+
+# privileges for WebDAV ACP:
+TAG_READ = 'read'
+TAG_WRITE = 'write'
+TAG_WRITE_PROPERTIES = 'write-properties'
+TAG_WRITE_CONTENT = 'write-content'
+TAG_UNLOCK = 'unlock'
+TAG_READ_ACL = 'read-acl'
+TAG_READ_CURRENT_USER_PRIVILEGE_SET = 'read-current-user-privilege-set'
+TAG_WRITE_ACL = 'write-acl'
+TAG_ALL = 'all'
+TAG_BIND = 'bind'
+TAG_UNBIND = 'unbind'
+# Tamino-specific privileges
+TAG_TAMINO_SECURITY = 'security' 
+# Limestone-specific privileges
+TAG_BIND_COLLECTION = 'bind-collection'
+TAG_UNBIND_COLLECTION = 'unbind-collection'
+TAG_READ_PRIVATE_PROPERTIES = 'read-private-properties'
+TAG_WRITE_PRIVATE_PROPERTIES = 'write-private-properties'
+
+# properties for WebDAV ACP:
+PROP_CURRENT_USER_PRIVILEGE_SET = 'current-user-privilege-set'
+PROP_SUPPORTED_PRIVILEGE_SET    = 'supported-privilege-set'
+PROP_PRINCIPAL_COLLECTION_SET = 'principal-collection-set' 
+
+# reports for WebDAV ACP
+REPORT_ACL_PRINCIPAL_PROP_SET   = 'acl-principal-prop-set'
+
+
+
+# constants for WebDAV Delta-V
+
+#   WebDAV Delta-V method names
+METHOD_REPORT = 'REPORT'
+METHOD_VERSION_CONTROL = 'VERSION-CONTROL'
+METHOD_UNCHECKOUT = 'UNCHECKOUT'
+METHOD_CHECKOUT = 'CHECKOUT'
+METHOD_CHECKIN = 'CHECKIN'
+METHOD_UPDATE = 'UPDATE'
+
+#   Special properties
+PROP_SUCCESSOR_SET = (NS_DAV, 'successor-set')
+PROP_PREDECESSOR_SET = (NS_DAV, 'predecessor-set')
+PROP_VERSION_HISTORY = (NS_DAV, 'version-history')
+PROP_CREATOR = (NS_DAV, 'creator-displayname')
+PROP_VERSION_NAME = (NS_DAV, 'version-name')
+PROP_CHECKEDIN = (NS_DAV, 'checked-in')
+PROP_CHECKEDOUT = (NS_DAV, 'checked-out')
+PROP_COMMENT = (NS_DAV, 'comment')
+
+#   XML tags for request body
+TAG_VERSION_TREE = 'version-tree'
+TAG_LOCATE_BY_HISTORY = 'locate-by-history'
+TAG_UPDATE = 'update'
+TAG_VERSION = 'version'
+
+# HTTP header constants
+HTTP_HEADER_DEPTH_INFINITY  = 'infinity'
+HTTP_HEADER_IF  = 'if'
+HTTP_HEADER_DAV = 'dav'
+HTTP_HEADER_DASL = 'dasl'
+HTTP_HEADER_OPTION_ACL = 'access-control'
+HTTP_HEADER_OPTION_DAV_BASIC_SEARCH = 'DAV:basicsearch'
+HTTP_HEADER_SERVER = 'server'
+HTTP_HEADER_SERVER_TAMINO = 'Apache/2.0.54 (Win32)'
diff --git a/src/webdav/Makefile.am b/src/webdav/Makefile.am
new file mode 100644
index 0000000..3356daf
--- /dev/null
+++ b/src/webdav/Makefile.am
@@ -0,0 +1,20 @@
+SUBDIRS = acp
+
+sugardir = $(pythondir)/webdav
+sugar_PYTHON =                  \
+             Connection.py      \
+             davlib.py          \
+             logger.py          \
+             NameCheck.py       \
+             Utils.py           \
+             VersionHandler.py  \
+             WebdavRequests.py  \
+             Condition.py       \
+             Constants.py       \
+             __init__.py        \
+             qp_xml.py          \
+             uuid_.py           \
+             WebdavClient.py    \
+             WebdavResponse.py
+
+
diff --git a/src/webdav/NameCheck.py b/src/webdav/NameCheck.py
new file mode 100644
index 0000000..7976973
--- /dev/null
+++ b/src/webdav/NameCheck.py
@@ -0,0 +1,193 @@
+# pylint: disable-msg=R0904,W0142,W0511,W0104,C0321,E1103,W0212
+# 
+# Copyright 2008 German Aerospace Center (DLR)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+"""
+Check name of new collections/resources for "illegal" characters.
+"""
+
+
+import re
+import unicodedata
+
+
+__version__ = "$LastChangedRevision$"
+
+
+_unicodeUmlaut = [unicodedata.lookup("LATIN CAPITAL LETTER A WITH DIAERESIS"),
+                  unicodedata.lookup("LATIN SMALL LETTER A WITH DIAERESIS"),
+                  unicodedata.lookup("LATIN CAPITAL LETTER O WITH DIAERESIS"),
+                  unicodedata.lookup("LATIN SMALL LETTER O WITH DIAERESIS"),
+                  unicodedata.lookup("LATIN CAPITAL LETTER U WITH DIAERESIS"),
+                  unicodedata.lookup("LATIN SMALL LETTER U WITH DIAERESIS"),
+                  unicodedata.lookup("LATIN SMALL LETTER SHARP S")]
+ 
+# Define characters and character base sets
+_german  = u"".join(_unicodeUmlaut)
+_alpha = "A-Za-z"
+_num = "0-9"
+_alphaNum = _alpha + _num
+_space = " "
+_under = "_"
+_dash = "\-"
+_dot = "\."
+_exclam = "\!"
+_tilde   = "\~"
+_dollar  = "\$"
+_plus = "+"
+_equal = "="
+_sharp = "#"
+
+# Define character groups
+_letterNum = _alphaNum + _german
+_letter = _alpha + _german
+
+# Define character sets for names
+firstPropertyChar = _letter + _under
+propertyChar = firstPropertyChar + _num + _dash + _dot
+firstResourceChar = firstPropertyChar + _num + _tilde + _exclam + _dollar + \
+                     _dot + _dash + _plus + _equal + _sharp
+resourceChar = firstResourceChar + _space
+
+# Define regular expressions for name validation
+_propertyFirstRe = re.compile(u"^["+ firstPropertyChar +"]")
+
+_propertyRe = re.compile(u"[^"+ propertyChar +"]")
+_resourceFirstRe = re.compile(u"^["+ firstResourceChar +"]")
+_resourceRe = re.compile(u"[^"+ resourceChar +"]")
+                    
+                    
+def isValidPropertyName(name):
+    """
+    Check if the given property name is valid.
+    
+    @param name: Property name.
+    @type name: C{unicode}
+    
+    @return: Boolean indicating whether the given property name is valid or not. 
+    @rtype: C{bool}
+    """
+
+    illegalChar = _propertyRe.search(name)
+    return illegalChar == None  and  _propertyFirstRe.match(name) != None
+    
+    
+def isValidResourceName(name):
+    """
+    Check if the given resource name is valid.
+    
+    @param name: Resource name.
+    @type name: C{unicode}
+    
+    @return: Boolean indicating whether the given resource name is valid or not. 
+    @rtype: C{bool}
+    """
+    
+    illegalChar = _resourceRe.search(name)
+    return illegalChar == None  and  _resourceFirstRe.match(name) != None
+
+
+def validatePropertyName(name):
+    """
+    Check if the given property name is valid.
+    
+    @param name: Property name.
+    @type name: C{unicode}
+    @raise WrongNameError: if validation fails (see L{datafinder.common.NameCheck.WrongNameError})
+    """
+    
+    illegalChar = _propertyRe.search(name)
+    if illegalChar:
+        raise WrongNameError(illegalChar.start(), name[illegalChar.start()])
+    if not _propertyFirstRe.match(name):
+        if len(name) > 0:
+            raise WrongNameError(0, name[0])
+        else:
+            raise WrongNameError(0, 0)
+       
+    
+def validateResourceName(name):
+    """
+    Check if the given resource name is valid.
+    
+    @param name: name of resource/collection
+    @type name: C{unicode}
+    @raise WrongNameError: if validation fails (@see L{datafinder.common.NameCheck.WrongNameError})
+    """
+
+    illegalChar = _resourceRe.search(name)
+    if illegalChar:
+        raise WrongNameError(illegalChar.start(), name[illegalChar.start()])
+    if not _resourceFirstRe.match(name):
+        if len(name) > 0:
+            raise WrongNameError(0, name[0])
+        else:
+            raise WrongNameError(0, 0)
+
+
+def getResourceNameErrorPosition(name):
+    """
+    Get position of illegal character (and the error-message).
+    This method can be used to get this information if L{isValidPropertyName}
+    or L{isValidResourceName} failed.
+    
+    @param name: Resource name.
+    @type name: C{unicode}
+    
+    @return: Tuple of error position and message.
+    @rtype: C{tuple} of C{int} and C{unicode}
+    """
+
+    result = (-1, None)
+    illegalChar = _resourceRe.search(name)
+    if illegalChar:
+        result = (illegalChar.start(), \
+                  u"Illegal character '%s' at index %d." % \
+                      (name[illegalChar.start()], illegalChar.start()))
+    elif not _resourceFirstRe.match(name):
+        result = (0, u"Illegal character '%s' at index %d." % (name[0], 0))
+    return result
+
+    
+class WrongNameError(ValueError):
+    """
+    Exception raised if an "illegal" character was found.
+    
+    @ivar character: character that caused the exception
+    @type character: C{unicode}
+    @ivar position: position of C{character}
+    @type position: C{int}
+    """
+    
+    def __init__(self, position, character):
+        """
+        Constructor.
+        
+        @param character: Character that caused the exception.
+        @type character: C{unicode}
+        @param position: Position of C{character}
+        @type position: C{int}
+        """
+        
+        ValueError.__init__(self)        
+        self.character = character
+        self.position = position
+    
+    def __str__(self):
+        """ Returns string representation. """
+        
+        return ValueError.__str__(self) + \
+            "Character '%s' at index %d." % (self.character, self.position)
diff --git a/src/webdav/Utils.py b/src/webdav/Utils.py
new file mode 100644
index 0000000..ec05755
--- /dev/null
+++ b/src/webdav/Utils.py
@@ -0,0 +1,154 @@
+# pylint: disable-msg=W0141,R0912
+#
+# Copyright 2008 German Aerospace Center (DLR)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+"""
+The module contains functions to support use of the WebDav functionalities.
+"""
+
+
+import os
+import sys
+
+from webdav.WebdavClient import CollectionStorer, ResourceStorer
+from webdav.Constants import NS_DAV, PROP_RESOURCE_TYPE, CODE_NOT_FOUND, PROP_RESOURCE_TYPE_RESOURCE
+from webdav.Connection import WebdavError
+
+
+__version__ = "$Revision$"[11:-2]
+
+
+def resourceExists(node, name = None, resourceType = PROP_RESOURCE_TYPE_RESOURCE):
+    """
+    Check if resource exists.
+    
+    Usage:
+      - resourceExists(ResourceStorer-object):
+        check if resource exists
+      - resourceExists(CollectionStorer-object, name):
+        check if resource name exists in collection
+    
+    @param node: node that has to be checked or node of collection
+    @type node: L{ResourceStorer<webdav.WebdavClient.ResourceStorer>}
+    @param name: name of resource (in collection node) that has to be checked
+    @type name: string
+    
+    @return: boolean
+    
+    @raise WebdavError: all WebDAV errors except WebDAV error 404 (not found)
+    """
+    
+    exists = False
+    if not node:
+        return exists
+    try:
+        myResourceType = ""
+        if name:
+            # make sure it's unicode:
+            if not isinstance(name, unicode):
+                name = name.decode(sys.getfilesystemencoding())
+            url = node.url
+            if url.endswith("/"):
+                url = url  + name
+            else:
+                url = url + "/" + name
+            newNode = ResourceStorer(url, node.connection)
+            element = newNode.readProperty(NS_DAV, PROP_RESOURCE_TYPE)
+        else: # name is "None":
+            element = node.readProperty(NS_DAV, PROP_RESOURCE_TYPE)
+        
+        if len(element.children) > 0:
+            myResourceType = element.children[0].name
+        if resourceType == myResourceType or resourceType == PROP_RESOURCE_TYPE_RESOURCE:
+            exists = True
+        else:
+            exists = False
+    except WebdavError, wderr:
+        if wderr.code == CODE_NOT_FOUND:
+            # node doesn't exist -> exists = False:
+            exists = False
+        else:
+            # another exception occured -> "re-raise" it:
+            raise
+    return exists
+
+
+def downloadCollectionContent(destinationPath, collectionToDownload):
+    """
+    Downloads the resources contained to the given directory.
+    
+    @param destinationPath: Path to download the files to, will be created if it not exists.
+    @type destinationPath: C{String}
+    @param collectionToDownload: Collection to download the content from.
+    @type collectionToDownload: instance of L{CollectionStorer<webdav.WebdavClient.CollectionStorer>}
+    
+    @raise  WebdavError: If something goes wrong.
+    """
+    
+    from time import mktime, gmtime
+
+    downloadCount = 0
+
+    listOfItems = collectionToDownload.getCollectionContents()
+    
+    if not os.path.exists(destinationPath):
+        try:
+            os.makedirs(destinationPath)
+        except OSError:
+            errorMessage = "Cannot create download destination directory '%s'." % destinationPath
+            raise WebdavError(errorMessage)
+        
+    try:
+        itemsInPath = os.listdir(destinationPath)
+    except OSError:
+        errorMessage = "Cannot read the content of download destination directory '%s'." % destinationPath
+        raise WebdavError(errorMessage)
+    
+    for item in listOfItems:
+        # skip collections
+        if not isinstance(item[0], CollectionStorer):
+            itemSavePath = os.path.join(destinationPath, item[0].name)
+            existsItemSavePath = os.path.exists(itemSavePath)
+            
+            # update?
+            if existsItemSavePath:
+                try:
+                    isUpdateNecessary = mktime(item[1].getLastModified()) > mktime(gmtime(os.path.getmtime(itemSavePath)))
+                except (ValueError, OverflowError):
+                    isUpdateNecessary = True
+                # windows is not case sensitive
+                for realItem in itemsInPath:
+                    if realItem.lower() == item[0].name.lower():
+                        itemsInPath.remove(realItem)
+            else:
+                isUpdateNecessary = True
+            
+            # download
+            if not existsItemSavePath or (existsItemSavePath and isUpdateNecessary):
+                item[0].downloadFile(itemSavePath)
+                downloadCount = downloadCount + 1
+    
+    # delete old items
+    try:
+        for item in itemsInPath:
+            os.remove(os.path.join(destinationPath, item))
+    except OSError, e:
+        if e.errno == 13:    # permission error
+            sys.stderr.write("permission problem on '%s' in %s\n" % (e.filename, e.strerror))
+        else:
+            raise  
+        
+    return downloadCount
diff --git a/src/webdav/VersionHandler.py b/src/webdav/VersionHandler.py
new file mode 100644
index 0000000..a1962c6
--- /dev/null
+++ b/src/webdav/VersionHandler.py
@@ -0,0 +1,198 @@
+# pylint: disable-msg=W0612,W0142
+#
+# Copyright 2008 German Aerospace Center (DLR)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+"""
+The WebDAV client module forwards Delta-V related method invocations to
+the following VersionHandler class.
+"""
+
+__version__ = '$Revision$'[11:-2]
+
+
+import types
+
+from webdav import Constants
+from davlib import XML_CONTENT_TYPE, XML_DOC_HEADER
+
+
+class VersionHandler(object):
+    """
+    Implements a client interface for WebDAV Delta-V methods
+    For the Delta-V see RFC 3253 at http://www.ietf.org/rfc/rfc3253.txt
+    """
+    
+    # restrict instance variables
+    __slots__ = ('path', 'connection')
+ 
+    
+    def __init__(self, connection, path):
+        """
+        Construct a VersionHandler with a URL path and a WebDAV connection.
+        This constructor must not be called outside class ResourceStorer.
+        
+        @param connection: L{webdav.Connection} instance
+        @param path: resource's path part of URL
+        """
+        #assert isinstance(connection, Connection), \
+        #    "Class of connection is %s." % connection.__class__.__name__
+        self.connection = connection
+        self.path = path
+ 
+ 
+    def activateVersionControl(self):
+        """
+        Turns version control on for this resource.
+        The resource becomes a version controlled resource (VCR)
+        """
+        response = self.connection._request(Constants.METHOD_VERSION_CONTROL, self.path, None, {})
+        # set auto-versioning to DAV:locked-checkout
+        ## parse response body in case of an error
+
+    def uncheckout(self, lockToken=None):
+        """
+        Undos a previous check-out operation on this VCR.
+        The VCR is reverted to the state before the checkout/lock operation.
+        Beware: Property or content changes will be lost !
+        A (optional) lock has to be removed seperatedly.
+        
+        @param lockToken: returned by a preceeding lock() method invocation or None
+        """
+        headers = {}
+        if lockToken:
+            headers = lockToken.toHeader() 
+        response = self.connection._request(Constants.METHOD_UNCHECKOUT, self.path, None, headers)
+        ## parse response body in case of an error
+    
+    def listAllVersions(self):
+        """
+        List version history.
+        
+        @return: List of versions for this VCR. Each version entry is a tuple adhering
+            to the format (URL-path, name, creator, tuple of successor URL-paths).
+            If there are no branches then there is at most one successor within the tuple. 
+        """
+        # implementation is similar to the propfind method
+        headers                 = {}
+        headers['Content-Type'] = XML_CONTENT_TYPE
+        body = _createReportVersionTreeBody()
+        response = self.connection._request(Constants.METHOD_REPORT, self.path, body, headers)
+        # response is multi-status
+        result = []
+        for path, properties in response.msr.items():           
+            # parse the successor-set value from XML into alist
+            result.append( (path, str(properties[Constants.PROP_VERSION_NAME]), \
+                            str(properties[Constants.PROP_CREATOR]), \
+                            _extractSuccessorList(properties[Constants.PROP_SUCCESSOR_SET])) )
+        ## TODO: sort for path and produce list
+        result.sort()
+        return result
+
+    # warning: not tested yet
+    def readVersionProperties(self):
+        """
+        Provide version related information on this VCR.
+        This include a reference to the latest version resource,
+        check-out state information and a comment.
+        
+        @return: map of version properties with values.
+        """
+        versionProperties = (Constants.PROP_CHECKEDIN, Constants.PROP_CHECKEDOUT, Constants.PROP_COMMENT)
+        return self.connection.readProperties(*versionProperties)
+    
+
+    def revertToVersion(self, oldVersion):
+        """
+        Revert this VCR to the given version.
+        Beware: All versions succeeding the given version are made unavailable.
+        
+        @param oldVersion: URL-path of a previous version of this VCR.
+        """
+        ## send an update request
+        assert isinstance(oldVersion, types.StringType) or isinstance(oldVersion, types.UnicodeType)
+        response = self.connection._request(Constants.METHOD_UPDATE, self.path,
+                        _createUpdateBody(oldVersion), {})
+        return response
+
+
+    # the following is not needed when using auto-versioning
+    
+    # warning: not tested yet
+    def checkout(self):
+        """
+        Marks resource as checked-out
+        This is usually followed by a GET (download) operation.
+        """
+        response = self.connection._request(Constants.METHOD_CHECKOUT, self.path, None, {})
+        ## parse response body in case of an error
+
+    # warning: not tested yet
+    def checkin(self):
+        """
+        Creates a new version from the VCR's content.
+        This opeartion is usually preceeded by one or more write operations.
+        """
+        response = self.connection._request(Constants.METHOD_CHECKIN, self.path, None, {})
+        versionUrl = response.getheader('Location')
+        return versionUrl
+        ## parse response body in case of an error
+
+
+
+
+# Helper functions
+def _createReportVersionTreeBody():
+    """
+    TBD
+    
+    @return: ...
+    @rtype: string
+    """
+    versions = 'D:' + Constants.TAG_VERSION_TREE
+    prop = 'D:' + Constants.TAG_PROP
+    nameList = [Constants.PROP_SUCCESSOR_SET, Constants.PROP_VERSION_NAME, Constants.PROP_CREATOR]
+    return XML_DOC_HEADER + \
+        '<%s xmlns:D="DAV:"><%s>' % (versions, prop) + \
+        reduce(lambda xml, name: xml + "<D:%s/>" % name[1], [''] + nameList) + \
+        '</%s></%s>' % (prop, versions)
+
+def _createUpdateBody(path):
+    """
+    TBD
+    
+    @return: ...
+    @rtype: string
+    """
+    update = 'D:' + Constants.TAG_UPDATE
+    version = 'D:' + Constants.TAG_VERSION
+    href = 'D:' + Constants.TAG_HREF
+    #PROP = 'D:' + TAG_PROP
+    return XML_DOC_HEADER + \
+        '<%s xmlns:D="DAV:"><%s><%s>' % (update, version, href) + \
+        path + \
+        '</%s></%s></%s>' % (href, version, update)
+
+def _extractSuccessorList(element):
+    """
+    TBD
+    
+    @return: ...
+    @rtype: tuple of strings
+    """
+    result = []
+    for href in element.children:
+        result.append(href.textof())
+    return tuple(result)
diff --git a/src/webdav/WebdavClient.py b/src/webdav/WebdavClient.py
new file mode 100644
index 0000000..ab5cec3
--- /dev/null
+++ b/src/webdav/WebdavClient.py
@@ -0,0 +1,840 @@
+# pylint: disable-msg=R0904,W0142,W0511,W0104,C0321,E1103,W0212
+# 
+# Copyright 2008 German Aerospace Center (DLR)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+ 
+
+"""
+This module contains the classes ResourceStorer and CollectionStorer for accessing WebDAV resources.
+"""
+
+
+from davlib import XML_CONTENT_TYPE
+
+from urlparse import urlsplit
+import re
+import types
+import sys
+import os
+import shutil
+import socket
+
+from webdav import Constants
+from webdav.WebdavResponse import LiveProperties
+from webdav.WebdavRequests import createFindBody, createUpdateBody, createDeleteBody, createSearchBody
+from webdav.Condition import ConditionTerm
+from webdav.Connection import Connection, WebdavError, AuthorizationError
+from webdav.VersionHandler import VersionHandler
+
+from webdav.acp.Privilege import Privilege
+from webdav.acp.Acl import ACL
+from webdav.NameCheck import validateResourceName, WrongNameError
+
+
+__version__ = '$Revision$'[11:-2]
+
+SOCKET_DEFAULT_TIMEOUT = 10
+
+
+def switchUnicodeUrlOn(switch):
+    """
+    Configure whether to use unicode (UTF-8) encoded URLs (default) or
+    Latin-1 encoded URLs.
+    
+    @param switch: 1 if unicode URLs shall be used
+    """
+
+    assert switch == 0 or switch == 1, "Pass boolean argument, please."
+    Constants.CONFIG_UNICODE_URL = switch
+
+
+def parseDigestAuthInfo(authInfo):
+    """ 
+    Parses the authentication information returned from a server and returns
+    a dictionary containing realm, qop, and nonce.
+    
+    @see: L{AuthorizationError<webdav.Connection.AuthorizationError>} 
+    or the main function of this module.
+    """
+    
+    info = dict()
+    info["realm"] = re.search('realm="([^"]+)"', authInfo).group(1)
+    info["qop"] = re.search('qop="([^"]+)"', authInfo).group(1)
+    info["nonce"] = re.search('nonce="([^"]+)"', authInfo).group(1)
+    return info
+
+
+class ResourceStorer(object):
+    """
+    This class provides client access to a WebDAV resource
+    identified by an URI. It provides all WebDAV class 2 features which include
+    uploading data, getting and setting properties qualified by a XML name space,
+    locking and unlocking the resource. 
+    This class does not cache resource data. This has to be performed by its clients.
+    
+    @author: Roland Betz
+    """
+        
+    # Instance properties
+    url = property(lambda self: str(self.connection) + self.path, None, None, "Resource's URL")
+
+    def __init__(self, url, connection=None, validateResourceNames=True):
+        """
+        Creates an instance for the given URL
+        User must invoke validate() after construction to check the resource on the server.
+        
+        @param url: Unique resource location for this storer.
+        @type  url: C{string}
+        @param connection: this optional parameter contains a Connection object 
+            for the host part of the given URL. Passing a connection saves 
+            memory by sharing this connection. (defaults to None)
+        @type  connection: L{webdav.Connection}
+        @raise WebdavError: If validation of resource name path parts fails.
+        """
+
+        assert connection == None or isinstance(connection, Connection)
+        parts = urlsplit(url, allow_fragments=False)
+        self.path = parts[2]
+        self.validateResourceNames = validateResourceNames
+        
+        # validate URL path
+        for part in self.path.split('/'):
+            if part != '' and not "ino:" in part: # explicitly allowing this character sequence as a part of a path (Tamino 4.4)
+                if self.validateResourceNames:
+                    try:
+                        validateResourceName(part)
+                    except WrongNameError:
+                        raise WebdavError("Found invalid resource name part.")
+                self.name = part
+        # was: filter(lambda part: part and validateResourceName(part), self.path.split('/'))
+        # but filter is deprecated
+        
+        self.defaultNamespace = None     # default XML name space of properties
+        if connection:
+            self.connection = connection
+        else:
+            conn = parts[1].split(":")
+            if len(conn) == 1:
+                self.connection = Connection(conn[0], protocol = parts[0])  # host and protocol
+            else:
+                self.connection = Connection(conn[0], int(conn[1]), protocol = parts[0])  # host and port and protocol
+        self.versionHandler = VersionHandler(self.connection, self.path)
+        
+
+    def validate(self):
+        """
+        Check whether URL contains a WebDAV resource
+        Uses the WebDAV OPTIONS method.
+        
+        @raise WebdavError: L{WebdavError} if URL does not contain a WebDAV resource
+        """
+        #davHeader = response.getheader(HTTP_HEADER_DAV)
+        davHeader = self.getSpecificOption(Constants.HTTP_HEADER_DAV)
+        self.connection.logger.debug("HEADER DAV: %s" % davHeader)
+        if not(davHeader) or davHeader.find("2") < 0:   # DAV class 2 supported ?
+            raise WebdavError("URL does not support WebDAV", 0)
+
+    def options(self):
+        """
+        Send an OPTIONS request to server and return all HTTP headers.
+        
+        @return: map of all HTTP headers returned by the OPTIONS method.
+        """
+        response = self.connection.options(self.path)
+        result = {}
+        result.update(response.msg)
+        self.connection.logger.debug("OPTION returns: " + str(result.keys()))
+        return result
+        
+    def _getAclSupportAvailable(self):
+        """
+        Returns True if the current connection has got ACL support.
+        
+        @return: ACL support (True / False)
+        @rtype: C{bool}
+        """
+        options = self.getSpecificOption(Constants.HTTP_HEADER_DAV)
+        if options.find(Constants.HTTP_HEADER_OPTION_ACL) >= 0:
+            return True
+        else:
+            return False
+        
+    aclSupportAvailable = property(_getAclSupportAvailable)
+        
+    def _getDaslBasicsearchSupportAvailable(self):
+        """
+        Returns True if the current connection supports DASL basic search.
+        
+        @return: DASL basic search support (True / False)
+        @rtype: C{bool}
+        """
+        options = self.getSpecificOption(Constants.HTTP_HEADER_DASL)
+        if not options or \
+           not options.find(Constants.HTTP_HEADER_OPTION_DAV_BASIC_SEARCH) >= 0:
+            return False
+        else:
+            return True
+    
+    daslBasicsearchSupportAvailable = property(_getDaslBasicsearchSupportAvailable)
+    
+    def isConnectedToCatacombServer(self):
+        """
+        Returns True if connected to a Catacomb WebDav server.
+        
+        @return: if connected to Catacomb Webdav server (True / False)
+        @rtype: C{bool}
+        """
+        if not self.connection.serverTypeChecked:
+            options = self.getSpecificOption(Constants.HTTP_HEADER_SERVER)
+            if options.find(Constants.HTTP_HEADER_SERVER_TAMINO) >= 0:
+                self.connection.isConnectedToCatacomb = False
+            else:
+                self.connection.isConnectedToCatacomb = True
+            self.connection.serverTypeChecked = True
+        return self.connection.isConnectedToCatacomb
+        
+    def getSpecificOption(self, option):
+        """
+        Returns specified WebDav options.
+        @param option: name of the option
+        
+        @return: String containing the value of the option.
+        @rtype: C{string}
+        """
+        options = ''
+        try:
+            options = self.options().get(option)
+        except KeyError:
+            return options
+        return options  
+        
+    ### delegate some method invocations    
+    def __getattr__(self, name):
+        """
+        Build-in method:
+        Forwards unknow lookups (methods) to delegate object 'versionHandler'.
+        
+        @param name: name of unknown attribute
+        """
+        # delegate Delta-V methods
+        return getattr(self.versionHandler, name)
+    
+    def copy(self, toUrl, infinity=True):
+        """
+        Copies this resource.
+        
+        @param toUrl: target URI path
+        @param infinity: Flag that indicates that the complete content of collection is copied. (default)  
+        @type depth: C{boolean}
+        """
+        self.connection.logger.debug("Copy to " + repr(toUrl));
+        _checkUrl(toUrl)
+        if infinity:
+            response = self.connection.copy(self.path, toUrl)
+        else:
+            response = self.connection.copy(self.path, toUrl, 0)
+        if  response.status == Constants.CODE_MULTISTATUS and response.msr.errorCount > 0:
+            raise WebdavError("Request failed: " + response.msr.reason, response.msr.code)        
+        
+    def delete(self, lockToken=None):
+        """
+        Deletes this resource.
+        
+        @param lockToken: String returned by last lock operation or null.
+        @type  lockToken: L{LockToken}
+        """
+        assert lockToken == None or isinstance(lockToken, LockToken), \
+                "Invalid lockToken argument %s" % type(lockToken)
+        header = {}
+        if lockToken:
+            header = lockToken.toHeader()
+        response = self.connection.delete(self.path, header)
+        if  response.status == Constants.CODE_MULTISTATUS and response.msr.errorCount > 0:
+            raise WebdavError("Request failed: " + response.msr.reason, response.msr.code)        
+
+    def move(self, toUrl):
+        """
+        Moves this resource to the given path or renames it.
+        
+        @param toUrl: new (URI) path
+        """
+        self.connection.logger.debug("Move to " + repr(toUrl));
+        _checkUrl(toUrl)
+        response = self.connection.move(self.path, toUrl)
+        if  response.status == Constants.CODE_MULTISTATUS and response.msr.errorCount > 0:
+            raise WebdavError("Request failed: " + response.msr.reason, response.msr.code)        
+
+ 
+    def lock(self, owner):
+        """
+        Locks this resource for exclusive write access. This means that for succeeding
+        write operations the returned lock token has to be passed.
+        If the methode does not throw an exception the lock has been granted.
+        
+        @param owner: describes the lock holder
+        @return: lock token string (automatically generated)
+        @rtype: L{LockToken}
+        """
+        response = self.connection.lock(self.path, owner)
+        if  response.status == Constants.CODE_MULTISTATUS and response.msr.errorCount > 0:
+            raise WebdavError("Request failed: " + response.msr.reason, response.msr.code)        
+        return LockToken(self.url, response.locktoken)
+
+    def unlock(self, lockToken):
+        """
+        Removes the lock from this resource.
+        
+        @param lockToken: which has been return by the lock() methode
+        @type  lockToken: L{LockToken}
+        """
+        self.connection.unlock(self.path, lockToken.token)
+
+
+    def deleteContent(self, lockToken=None):
+        """
+        Delete binary data at permanent storage.
+        
+        @param lockToken: None or lock token from last lock request
+        @type  lockToken: L{LockToken}
+        """
+        assert lockToken == None or isinstance(lockToken, LockToken), \
+                "Invalid lockToken argument %s" % type(lockToken)
+        header = {}
+        if lockToken:
+            header = lockToken.toHeader()
+        self.connection.put(self.path, "", extra_hdrs=header)
+
+    def uploadContent(self, content, lockToken=None):
+        """
+        Write binary data to permanent storage.
+        
+        @param content: containing binary data
+        @param lockToken: None or lock token from last lock request
+        @type  lockToken: L{LockToken}
+        """
+        assert not content or isinstance(content, types.UnicodeType) or\
+                isinstance(content, types.StringType), "Content is not a string: " + content.__class__.__name__
+        assert lockToken == None or isinstance(lockToken, LockToken), \
+                "Invalid lockToken argument %s" % type(lockToken)
+        header = {}
+        if lockToken:
+            header = lockToken.toHeader()
+        response = None
+        if not content is None:
+            header["Content-length"] = len(content)
+        else:
+            header["Content-length"] = 0
+
+        try: 
+            response = self.connection.put(self.path, content, extra_hdrs=header)
+        finally:
+            if response:        
+                self.connection.logger.debug(response.read())
+                response.close()
+
+    def uploadFile(self, newFile, lockToken=None):
+        """
+        Write binary data to permanent storage.
+        
+        @param newFile: File containing binary data.
+        @param lockToken: None or lock token from last lock request
+        @type  lockToken: L{LockToken}
+        """
+        assert isinstance(newFile, types.FileType), "Argument is no file: " + file.__class__.__name__
+        assert lockToken == None or isinstance(lockToken, LockToken), \
+                "Invalid lockToken argument %s" % type(lockToken)
+        header = {}
+        if lockToken:
+            header = lockToken.toHeader()
+        self.connection.putFile(self.path, newFile, header=header)
+
+    def downloadContent(self):
+        """
+        Read binary data from permanent storage.
+        """
+        response = self.connection.get(self.path)
+        # TODO: Other interface ? return self.connection.getfile()
+        return response
+
+    def downloadFile(self, localFileName):
+        """
+        Copy binary data from permanent storage to a local file.
+        
+        @param localFileName: file to write binary data to
+        """
+        localFile = open(localFileName, 'wb')
+        remoteFile = self.downloadContent()
+        try:
+            socket.setdefaulttimeout(SOCKET_DEFAULT_TIMEOUT)
+            _blockCopyFile(remoteFile, localFile, Connection.blockSize)
+        except socket.error, e:
+            raise e
+        remoteFile.close()
+        localFile.close()
+
+    def readProperties(self, *names):
+        """
+        Reads the given properties.
+        
+        @param names: a list of property names.
+                      A property name is a (XmlNameSpace, propertyName) tuple.
+        @return: a map from property names to DOM Element or String values.
+        """
+        assert names, "Property names are missing."
+        body = createFindBody(names, self.defaultNamespace)
+        response = self.connection.propfind(self.path, body, depth=0)
+        properties = response.msr.values()[0]
+        if  properties.errorCount > 0:
+            raise WebdavError("Property is missing on '%s': %s" % (self.path, properties.reason), properties.code)
+        return properties
+
+    def readProperty(self, nameSpace, name):
+        """
+        Reads the given property.
+        
+        @param nameSpace: XML-namespace
+        @type nameSpace: string
+        @param name: A property name.
+        @type name: string
+        
+        @return: a map from property names to DOM Element or String values.
+        """
+        results = self.readProperties((nameSpace, name))
+        if  len(results) == 0:
+            raise WebdavError("Property is missing: " + results.reason)
+        return results.values()[0]
+
+    def readAllProperties(self):
+        """
+        Reads all properties of this resource.
+        
+        @return: a map from property names to DOM Element or String values.
+        """
+        response = self.connection.allprops(self.path, depth=0)
+        return response.msr.values()[0]
+
+    def readAllPropertyNames(self):
+        """
+        Returns the names of all properties attached to this resource.
+        
+        @return: List of property names
+        """
+        response = self.connection.propnames(self.path, depth=0)
+        return response.msr.values()[0]
+
+    def readStandardProperties(self):
+        """
+        Read all WebDAV live properties.
+        
+        @return: A L{LiveProperties} instance which contains a getter method for each live property.
+        """
+        body = createFindBody(LiveProperties.NAMES, Constants.NS_DAV)
+        response = self.connection.propfind(self.path, body, depth=0)
+        properties = response.msr.values()[0]
+        return LiveProperties(properties)
+
+    def writeProperties(self, properties, lockToken=None):
+        """
+        Sets or updates the given properties.
+        
+        @param lockToken: if the resource has been locked this is the lock token.
+        @type  lockToken: L{LockToken}
+        @param properties: a map from property names to a String or
+                           DOM element value for each property to add or update.
+        """
+        assert isinstance(properties, types.DictType)
+        assert lockToken == None or isinstance(lockToken, LockToken), \
+                "Invalid lockToken argument %s" % type(lockToken)
+        header = {}
+        if lockToken:
+            header = lockToken.toHeader()
+        body = createUpdateBody(properties, self.defaultNamespace)
+        response = self.connection.proppatch(self.path, body, header)
+        if  response.msr.errorCount > 0:
+            raise WebdavError("Request failed: " + response.msr.reason, response.msr.code)
+
+    def deleteProperties(self, lockToken=None, *names):
+        """
+        Removes the given properties from this resource.
+        
+        @param lockToken: if the resource has been locked this is the lock token.
+        @type  lockToken: L{LockToken}
+        @param names: a collection of property names.
+               A property name is a (XmlNameSpace, propertyName) tuple.
+        """
+        assert lockToken == None or isinstance(lockToken, LockToken), \
+                "Invalid lockToken argument %s" % type(lockToken)
+        header = {}
+        if lockToken:
+            header = lockToken.toHeader()
+        body = createDeleteBody(names, self.defaultNamespace)
+        response = self.connection.proppatch(self.path, body, header)
+        if  response.msr.errorCount > 0:
+            raise WebdavError("Request failed: " + response.msr.reason, response.msr.code)
+
+    # ACP extension
+    def setAcl(self, acl, lockToken=None):
+        """
+        Sets ACEs in the non-inherited and non-protected ACL or the resource.
+        This is the implementation of the ACL method of the WebDAV ACP.
+        
+        @param acl: ACL to be set on resource as ACL object.
+        @param lockToken: If the resource has been locked this is the lock token (defaults to None).
+        @type  lockToken: L{LockToken}
+        """
+        assert lockToken == None or isinstance(lockToken, LockToken), \
+                "Invalid lockToken argument %s" % type(lockToken)
+        headers = {}
+        if lockToken:
+            headers = lockToken.toHeader()
+        headers['Content-Type'] = XML_CONTENT_TYPE
+        body                    = acl.toXML()
+        response = self.connection._request('ACL', self.path, body, headers)
+        return response
+        ## TODO: parse DAV:error response
+
+    def getAcl(self):
+        """
+        Returns this resource's ACL in an ACL instance.
+        
+        @return: Access Control List.
+        @rtype: L{ACL<webdav.acp.Acl.ACL>}
+        """
+        xmlAcl = self.readProperty(Constants.NS_DAV, Constants.TAG_ACL)
+        return ACL(xmlAcl)
+
+    def getCurrentUserPrivileges(self):
+        """
+        Returns a tuple of the current user privileges.
+        
+        @return: list of Privilege instances
+        @rtype: list of L{Privilege<webdav.acp.Privilege.Privilege>}
+        """
+        privileges = self.readProperty(Constants.NS_DAV, Constants.PROP_CURRENT_USER_PRIVILEGE_SET)
+        result = []
+        for child in privileges.children:
+            result.append(Privilege(domroot=child))
+        return result
+    
+    def getPrincipalCollections(self):
+        """
+        Returns a list principal collection URLs.
+        
+        @return: list of principal collection URLs
+        @rtype: C{list} of C{unicode} elements
+        """
+        webdavQueryResult = self.readProperty(Constants.NS_DAV, Constants.PROP_PRINCIPAL_COLLECTION_SET)
+        principalCollectionList = []
+        for child in webdavQueryResult.children:
+            principalCollectionList.append(child.first_cdata)            
+        return principalCollectionList
+    
+    def getOwnerUrl(self):
+        """ Explicitly retireve the Url of the owner. """
+        
+        result = self.readProperty(Constants.NS_DAV, Constants.PROP_OWNER)
+        if result and len(result.children):
+            return result.children[0].textof()
+        return None
+
+class CollectionStorer(ResourceStorer):
+    """
+    This class provides client access to a WebDAV collection resource identified by an URI.
+    This class does not cache resource data. This has to be performed by its clients.
+    
+    @author: Roland Betz
+    """
+        
+    def __init__(self, url, connection=None, validateResourceNames=True):
+        """
+        Creates a CollectionStorer instance for a URL and an optional Connection object.
+        User must invoke validate() after constuction to check the resource on the server.
+        
+        @see: L{webdav.WebdavClient.ResourceStorer.__init__}
+        @param url: unique resource location for this storer
+        @param connection: this optional parameter contains a Connection object for the host part
+            of the given URL. Passing a connection saves memory by sharing this connection.    
+        """
+        if  url[-1] != '/':     # Collection URL must end with slash
+            url += '/'
+        ResourceStorer.__init__(self, url, connection, validateResourceNames)
+    
+    def getResourceStorer(self, name):
+        """
+        Return a ResourceStorer instance for a child resource (member) of this Collection.
+        
+        @param name: leaf name of child resource
+        @return: L{ResourceStorer} instance
+        """
+        assert isinstance(name, types.StringType) or isinstance(name, types.UnicodeType)
+        return ResourceStorer(self.url + name, self.connection, self.validateResourceNames)
+             
+    def validate(self):
+        """
+        Check whether this URL contains a WebDAV collection.
+        Uses the WebDAV OPTION method.
+        
+        @raise WebdavError: L{WebdavError} if URL does not contain a WebDAV collection resource.
+        """
+        super(CollectionStorer, self).validate()
+        isCollection = self.readProperty(Constants.NS_DAV, Constants.PROP_RESOURCE_TYPE)
+        if not (isCollection and isCollection.children):
+            raise WebdavError("Not a collection URL.", 0)        
+        
+    def addCollection(self, name, lockToken=None):
+        """
+        Make a new WebDAV collection resource within this collection.
+        
+        @param name: of the new collection
+        @param lockToken: None or token returned by last lock operation
+        @type  lockToken: L{LockToken}
+        """
+        assert isinstance(name, types.StringType) or isinstance(name, types.UnicodeType)
+        assert lockToken == None or isinstance(lockToken, LockToken), \
+                "Invalid lockToken argument %s" % type(lockToken)
+        header = {}
+        if lockToken:
+            header = lockToken.toHeader()
+        if self.validateResourceNames:
+            validateResourceName(name)
+        if  name[-1] != '/':     # Collection URL must end with slash
+            name += '/'
+        self.connection.mkcol(self.path + name, header)
+        return CollectionStorer(self.url + name, self.connection, self.validateResourceNames) 
+        
+    def addResource(self, name, content=None, properties=None, lockToken=None):
+        """
+        Create a new empty WebDAV resource contained in this collection with the given
+        properties.
+        
+        @param name: leaf name of the new resource    
+        @param content: None or initial binary content of resource
+        @param properties: name/value-map containing properties
+        @param lockToken: None or token returned by last lock operation
+        @type  lockToken: L{LockToken}
+        """
+        assert isinstance(name, types.StringType) or isinstance(name, types.UnicodeType)
+        assert lockToken == None or isinstance(lockToken, LockToken), \
+                "Invalid lockToken argument %s" % type(lockToken)
+        if self.validateResourceNames:
+            validateResourceName(name) # check for invalid characters        
+        resource_ = ResourceStorer(self.url + name, self.connection, self.validateResourceNames)
+        resource_.uploadContent(content, lockToken)
+        if properties:
+            resource_.writeProperties(properties, lockToken)
+        return resource_
+        
+    def deleteResource(self, name, lockToken=None):
+        """
+        Delete a collection which is contained within this collection
+        
+        @param name: leaf name of a contained collection resource
+        @param lockToken: None or token returned by last lock operation
+        @type  lockToken: L{LockToken}
+        """
+        assert isinstance(name, types.StringType) or isinstance(name, types.UnicodeType)
+        assert lockToken == None or isinstance(lockToken, LockToken), \
+                "Invalid lockToken argument %s" % type(lockToken)
+        header = {}
+        if lockToken:
+            header = lockToken.toHeader()
+        if self.validateResourceNames:
+            validateResourceName(name)
+        response = self.connection.delete(self.path + name, header)
+        if  response.status == Constants.CODE_MULTISTATUS and response.msr.errorCount > 0:
+            raise WebdavError("Request failed: %s" % response.msr.reason, response.msr.code)        
+        
+    def lockAll(self, owner):
+        """
+        Locks this collection resource for exclusive write access. This means that for 
+        succeeding write operations the returned lock token has to be passed.
+        The operation is applied recursively to all contained resources.
+        If the methode does not throw an exception then the lock has been granted.
+        
+        @param owner: describes the lock holder
+        @return: Lock token string (automatically generated).
+        @rtype: L{LockToken}
+        """
+        assert isinstance(owner, types.StringType) or isinstance(owner, types.UnicodeType)
+        response = self.connection.lock(self.path, owner, depth=Constants.HTTP_HEADER_DEPTH_INFINITY)
+        return LockToken(self.url, response.locktoken)
+        
+    def listResources(self):
+        """
+        Describe all members within this collection.
+        
+        @return: map from URI to a L{LiveProperties} instance containing the WebDAV
+                 live attributes of the contained resource
+        """
+        # *LiveProperties.NAMES denotes the list of all live properties as an
+        # argument to the method call.
+        response = self.connection.getprops(self.path,
+                                            depth=1,
+                                            ns=Constants.NS_DAV,
+                                            *LiveProperties.NAMES)
+        result = {}
+        for path, properties in response.msr.items():
+            if path == self.path:      # omit this collection resource
+                continue
+            ## some servers do not append a trailing slash to collection paths
+            if self.path.endswith('/') and self.path[0:-1] == path:
+                continue
+            result[path] = LiveProperties(properties=properties)
+        return result
+
+    def getCollectionContents(self):
+        """
+        Return a list of the tuple (resources or collection) / properties)
+
+        @return: a list of the tuple (resources or collection) / properties)
+        @rtype: C{list} 
+        """
+        self.validate()
+        collectionContents = []
+        result = self.listResources()
+        for url, properties_ in result.items():
+            if not self.path == url:
+                if properties_.getResourceType() == 'resource':
+                    myWebDavStorer = ResourceStorer(url, self.connection, self.validateResourceNames)
+                else:
+                    myWebDavStorer = CollectionStorer(url, self.connection, self.validateResourceNames)
+                collectionContents.append((myWebDavStorer, properties_))
+        return collectionContents
+
+    def findProperties(self, *names):
+        """
+        Retrieve given properties for this collection and all directly contained resources.
+        
+        @param names: a list of property names
+        @return: a map from resource URI to a map from property name to value.
+        """
+        assert isinstance(names, types.ListType) or isinstance(names, types.TupleType), \
+                "Argument name has type %s" % str(type(names))
+        body = createFindBody(names, self.defaultNamespace)
+        response = self.connection.propfind(self.path, body, depth=1)
+        return response.msr
+        
+    def deepFindProperties(self, *names):
+        """
+        Retrieve given properties for this collection and all contained (nested) resources.
+        
+        Note:
+        =====
+          This operation can take a long time if used with recursive=true and is therefore
+          disabled on some WebDAV servers.
+        
+        @param names: a list of property names
+        @return: a map from resource URI to a map from property name to value.
+        """
+        assert isinstance(names, types.ListType.__class__) or isinstance(names, types.TupleType), \
+                "Argument name has type %s" % str(type(names))
+        body = createFindBody(names, self.defaultNamespace)
+        response = self.connection.propfind(self.path, body, depth=Constants.HTTP_HEADER_DEPTH_INFINITY)
+        return response.msr
+        
+    def findAllProperties(self):
+        """
+        Retrieve all properties for this collection and all directly contained resources.
+        
+        @return: a map from resource URI to a map from property name to value.
+        """
+        response = self.connection.allprops(self.path, depth=1)
+        return response.msr
+            
+        
+    # DASL extension
+    def search(self, conditions, selects):
+        """
+        Search for contained resources which match the given search condition.
+        
+        @param conditions: tree of ConditionTerm instances representing a logical search term
+        @param selects: list of property names to retrieve for the found resources
+        """
+        assert isinstance(conditions, ConditionTerm)
+        headers = { 'Content-Type' : XML_CONTENT_TYPE, "depth": Constants.HTTP_HEADER_DEPTH_INFINITY}
+        body = createSearchBody(selects, self.path, conditions)
+        response = self.connection._request('SEARCH', self.path, body, headers)
+        return response.msr
+        
+
+class LockToken(object):
+    """
+    This class provides help on handling WebDAV lock tokens.
+    
+    @author: Roland Betz
+    """
+    # restrict instance variables
+    __slots__ = ('url', 'token')
+
+    def __init__(self, url, token):
+        assert isinstance(url, types.StringType) or isinstance(url, types.UnicodeType), \
+            "Invalid url argument %s" % type(url)
+        assert isinstance(token, types.StringType) or isinstance(token, types.UnicodeType), \
+            "Invalid lockToken argument %s" % type(token)
+        self.url = url
+        self.token = token
+
+    def value(self):
+        """
+        Descriptive string containing the lock token's URL and the token itself.
+        
+        @return: Descriptive lock token with URL.
+        @rtype: C{string}
+        """
+        return "<" + self.url + "> (<" + self.token + ">)"
+
+    def toHeader(self):
+        """
+        Header fragment for WebDAV request.
+        
+        @return: Dictionary containing an entry for the lock token query.
+        @rtype: C{dictionary}
+        """
+        return {Constants.HTTP_HEADER_IF: self.value()}
+    
+    def __str__(self):
+        return self.value()
+
+
+def _blockCopyFile(source, dest, blockSize):
+    """
+    Copies a file in chunks of C{blockSize}.
+    
+    @param source: Source file.
+    @type  source: FileIO buffer.
+    @param dest: Destination file.
+    @type  dest: FileIO buffer.
+    @param blockSize: Size of block in bytes.
+    @type  blockSize: C{int}
+    """
+    transferedBytes = 0
+    block = source.read(blockSize)
+    while len(block):
+        dest.write(block)
+        transferedBytes += len(block);
+        block = source.read(blockSize)
+
+def _checkUrl(url):
+    """
+    Checks the given URL for validity.
+    
+    @param url: URL to check.
+    @type  url: C{string}
+    
+    @raise ValueError: If the URL does not contain valid/usable content.
+    """
+    
+    parts = urlsplit(url, allow_fragments=False)
+    if len(parts[0]) == 0 or len(parts[1]) == 0 or len(parts[2]) == 0:
+        raise ValueError("Invalid URL: " + repr(url))
diff --git a/src/webdav/WebdavRequests.py b/src/webdav/WebdavRequests.py
new file mode 100644
index 0000000..79e586a
--- /dev/null
+++ b/src/webdav/WebdavRequests.py
@@ -0,0 +1,205 @@
+# pylint: disable-msg=W0511,W0212,E1111
+#
+# Copyright 2008 German Aerospace Center (DLR)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+ 
+ 
+"""
+This module handles WebDav server requests.
+"""
+
+
+import types
+from webdav import Constants
+import qp_xml
+from tempfile import TemporaryFile
+
+from davlib import XML_DOC_HEADER
+
+from webdav.NameCheck import validatePropertyName
+
+
+__version__ = "$LastChangedRevision$"
+
+
+## TODO: create a property list class
+    
+class XmlNameSpaceMangler(object):
+    '''
+    Handles WebDav requests.
+    '''
+    
+    # restrict instance variables
+    __slots__ = ('shortcuts', 'defaultNameSpace')
+    
+    def __init__(self, nameList, defaultNameSpace = None):
+        '''
+        
+        @param nameList:
+        @param defaultNameSpace:
+        '''
+        
+        assert isinstance(nameList, types.ListType) or isinstance(nameList, types.TupleType), \
+            "1. argument has wrong type %s" % type(nameList)
+        self.shortcuts = {}
+        self.defaultNameSpace = defaultNameSpace
+        for name in nameList:
+            if  not isinstance(name, types.TupleType):
+                name = (defaultNameSpace, name)            
+            assert isinstance(name, types.TupleType) and len(name) == 2, \
+                         "Name is not a namespace, name tuple: %s" % type(name)
+            validatePropertyName(name[1])
+            if  name[0] and not self.shortcuts.has_key(name[0]):
+                self.shortcuts[name[0]] = 'ns%d' % len(self.shortcuts)
+    
+    def getNameSpaces(self):
+        '''
+        Returns the namespace.
+        '''
+        
+        result = ""        
+        for namespace, short in self.shortcuts.items():
+            result += ' xmlns:%s="%s"' % (short, namespace)
+        return result
+    
+    def getUpdateElements(self, valueMap):
+        '''
+        
+        @param valueMap:
+        '''
+        
+        elements = ""
+        for name in valueMap.keys():
+            fullname = name
+            if  isinstance(name, types.StringType):
+                fullname = (self.defaultNameSpace, name)        
+            if  not fullname[0]:
+                tag = fullname[1]        
+            else:
+                tag = self.shortcuts[fullname[0]] + ':' + fullname[1]
+            value = valueMap[name]
+            if value:
+                if isinstance(value, qp_xml._element):
+                    tmpFile = TemporaryFile('w+')
+                    value = qp_xml.dump(tmpFile, value)
+                    tmpFile.flush()
+                    tmpFile.seek(0)
+                    tmpFile.readline()
+                    value = tmpFile.read()
+                else:
+                    value = "<![CDATA[%s]]>" % value
+            else:
+                value = ""
+            elements += "<%s>%s</%s>" % (tag, value, tag)
+        return elements
+    
+    def getNameElements(self, nameList):
+        '''
+        
+        @param nameList:
+        '''
+        
+        elements = ""
+        for name in nameList:
+            if  isinstance(name, types.StringType):
+                name = (self.defaultNameSpace, name)        
+            if  not name[0]:
+                tag = name[1]        
+            else:
+                tag = self.shortcuts[name[0]] + ':' + name[1]
+            elements += "<%s />" % tag
+        return elements
+                         
+
+
+def createUpdateBody(propertyDict, defaultNameSpace = None):
+    '''
+    
+    @param propertyDict:
+    @param defaultNameSpace:
+    '''
+    
+    updateTag = 'D:' + Constants.TAG_PROPERTY_UPDATE
+    setTag = 'D:' + Constants.TAG_PROPERTY_SET
+    propTag = 'D:' + Constants.TAG_PROP
+    mangler = XmlNameSpaceMangler(propertyDict.keys(), defaultNameSpace)
+    return XML_DOC_HEADER + \
+        '<%s xmlns:D="DAV:"><%s><%s %s>' % (updateTag, setTag, propTag, mangler.getNameSpaces()) + \
+        mangler.getUpdateElements(propertyDict) + \
+        '</%s></%s></%s>' % (propTag, setTag, updateTag)
+
+        
+def createDeleteBody(nameList, defaultNameSpace = None):
+    '''
+    
+    @param nameList:
+    @param defaultNameSpace:
+    '''
+    
+    updateTag = 'D:' + Constants.TAG_PROPERTY_UPDATE
+    removeTag = 'D:' + Constants.TAG_PROPERTY_REMOVE
+    propTag = 'D:' + Constants.TAG_PROP
+    mangler = XmlNameSpaceMangler(nameList, defaultNameSpace)
+    return XML_DOC_HEADER + \
+        '<%s xmlns:D="DAV:"><%s><%s %s>' % (updateTag, removeTag, propTag, mangler.getNameSpaces()) + \
+        mangler.getNameElements(nameList) + \
+        '</%s></%s></%s>' % (propTag, removeTag, updateTag)
+        
+        
+def createFindBody(nameList, defaultNameSpace = None):
+    '''
+    
+    @param nameList:
+    @param defaultNameSpace:
+    '''
+    
+    findTag = 'D:' + Constants.TAG_PROPERTY_FIND
+    propTag = 'D:' + Constants.TAG_PROP
+    mangler = XmlNameSpaceMangler(nameList, defaultNameSpace)
+    return XML_DOC_HEADER + \
+        '<%s xmlns:D="DAV:"><%s %s>' % (findTag, propTag, mangler.getNameSpaces()) + \
+        mangler.getNameElements(nameList) + \
+        '</%s></%s>' % (propTag, findTag)
+        
+        
+def createSearchBody(selects, path, conditions, defaultNameSpace = None):
+    '''
+    Creates DASL XML body.
+    
+    @param selects: list of property names to retrieve for the found resources
+    @param path: list of conditions
+    @param conditions: tree of ConditionTerm instances representing a logical search term
+    @param defaultNameSpace: default namespace
+    '''
+    
+    searchTag = 'D:' + Constants.TAG_SEARCH_REQUEST
+    basicTag = 'D:' + Constants.TAG_SEARCH_BASIC
+    selectTag = 'D:' + Constants.TAG_SEARCH_SELECT
+    fromTag = 'D:' + Constants.TAG_SEARCH_FROM
+    scopeTag = 'D:' + Constants.TAG_SEARCH_SCOPE
+    whereTag = 'D:' + Constants.TAG_SEARCH_WHERE
+    propTag = 'D:' + Constants.TAG_PROP
+    hrefTag = 'D:' + Constants.TAG_HREF
+    depthTag = 'D:' + Constants.TAG_LOCK_DEPTH
+    depthValue = Constants.HTTP_HEADER_DEPTH_INFINITY
+    mangler = XmlNameSpaceMangler(selects, defaultNameSpace)
+    return XML_DOC_HEADER + \
+        '<%s xmlns:D="DAV:"><%s>' % (searchTag, basicTag) + \
+        '<%s><%s %s>%s</%s></%s>' % (selectTag, propTag, mangler.getNameSpaces(), 
+                                     mangler.getNameElements(selects), propTag, selectTag) + \
+        '<%s><%s><%s>%s</%s><%s>%s</%s></%s></%s>' % (fromTag, scopeTag, hrefTag, path, hrefTag, 
+                                                      depthTag, depthValue, depthTag, scopeTag, fromTag) + \
+        '<%s>%s</%s>' % (whereTag, conditions.toXML(),whereTag) + \
+        '</%s></%s>' % (basicTag, searchTag)
+        
\ No newline at end of file
diff --git a/src/webdav/WebdavResponse.py b/src/webdav/WebdavResponse.py
new file mode 100644
index 0000000..c84943d
--- /dev/null
+++ b/src/webdav/WebdavResponse.py
@@ -0,0 +1,525 @@
+# pylint: disable-msg=R0903,W0142,W0221,W0212,W0104,W0511,C0103,R0901
+#
+# Copyright 2008 German Aerospace Center (DLR)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+"""
+Handles WebDAV responses.
+"""
+
+
+from davlib import _parse_status
+import qp_xml
+from webdav import Constants
+import time
+import rfc822
+import urllib
+# Handling Jython 2.5 bug concerning the date pattern
+# conversion in time.strptime
+try:
+    from java.lang import IllegalArgumentException
+except ImportError:
+    class IllegalArgumentException(object):
+        pass
+
+
+__version__ = "$LastChangedRevision$"
+
+
+class HttpStatus(object):
+    """
+    TBD
+    
+    @ivar code:
+    @type code:
+    @ivar reason:
+    @type reason:
+    @ivar errorCount:
+    @type errorCount: int
+    """
+    
+    def __init__(self, elem):
+        """
+        TBD
+        
+        @param elem: ...
+        @type elem: instance of L{Element}
+        """
+        self.code, self.reason = _parse_status(elem)
+        self.errorCount = (self.code >= Constants.CODE_LOWEST_ERROR)
+    def __str__(self):
+        return "HTTP status %d: %s" % (self.code, self.reason)
+
+        
+class MultiStatusResponse(dict):
+    """
+    TBD
+    
+    @ivar status:
+    @type status:
+    @ivar reason:
+    @type reason:
+    @ivar errorCount:
+    @type errorCount:
+    """
+    
+    # restrict instance variables
+    __slots__ = ('errorCount', 'reason', 'status')
+
+    def __init__(self, domroot):
+        dict.__init__(self)
+        self.errorCount = 0
+        self.reason = None
+        self.status = Constants.CODE_MULTISTATUS
+        if (domroot.ns != Constants.NS_DAV) or (domroot.name != Constants.TAG_MULTISTATUS):
+            raise ResponseFormatError(domroot, 'Invalid response: <DAV:multistatus> expected.')
+        self._scan(domroot)
+    
+    def getCode(self):
+        if self.errorCount == 0:
+            return Constants.CODE_SUCCEEDED
+        if  len(self) > self.errorCount:
+            return Constants.CODE_MULTISTATUS
+        return self.values()[0].code
+
+    def getReason(self):
+        result = ""
+        for response in self.values():
+            if response.code > Constants.CODE_LOWEST_ERROR:
+                result += response.reason
+        return result                    
+    
+    def __str__(self):
+        result = ""
+        for key, value in self.items():
+            if  isinstance(value, PropertyResponse):
+                result += "Resource at %s has %d properties and %d errors.\n" % (key, len(value), value.errorCount)
+            else:
+                result += "Resource at %s returned " % key + str(value)
+        return result
+    
+    def _scan(self, root):
+        for child in root.children:
+            if child.ns != Constants.NS_DAV:
+                continue
+            if child.name == Constants.TAG_RESPONSEDESCRIPTION:
+                self.reason = child.textof()
+            elif child.name == Constants.TAG_RESPONSE:
+                self._scanResponse(child)
+            ### unknown child element
+        
+    def _scanResponse(self, elem):
+        hrefs = []
+        response = None
+        for child in elem.children:
+            if child.ns != Constants.NS_DAV:
+                continue
+            if child.name == Constants.TAG_HREF:
+                try:
+                    href = _unquoteHref(child.textof())
+                except UnicodeDecodeError:
+                    raise ResponseFormatError(child, "Invalid 'href' data encoding.")
+                hrefs.append(href)
+            elif child.name == Constants.TAG_STATUS:
+                self._scanStatus(child, *hrefs)
+            elif child.name == Constants.TAG_PROPERTY_STATUS:
+                if not response:
+                    if len(hrefs) != 1:
+                        raise ResponseFormatError(child, 'Invalid response: One <DAV:href> expected.')
+                    response = PropertyResponse()                    
+                    self[hrefs[0]] = response                    
+                response._scan(child)
+            elif child.name == Constants.TAG_RESPONSEDESCRIPTION:
+                for href in hrefs:
+                    self[href].reasons.append(child.textOf())            
+            ### unknown child element
+        if response and response.errorCount > 0:
+            self.errorCount += 1
+                                    
+    def _scanStatus(self, elem, *hrefs):
+        if  len(hrefs) == 0:
+            raise ResponseFormatError(elem, 'Invalid response: <DAV:href> expected.')
+        status = HttpStatus(elem)
+        for href in hrefs:
+            self[href] = status
+            if  status.errorCount:
+                self.errorCount += 1
+
+    # Instance properties
+    code = property(getCode, None, None, "HTTP response code")
+
+
+
+class PropertyResponse(dict):
+    """
+    TBD
+    
+    @ivar errors:
+    @type errors: list of ...
+    @ivar reasons:
+    @type reasons: list of ...
+    @ivar failedProperties:
+    @type failedProperties: dict of ...
+    """
+
+    # restrict instance variables
+    __slots__ = ('errors', 'reasons', 'failedProperties')
+
+    def __init__(self):
+        dict.__init__(self)
+        self.errors = []
+        self.reasons = []
+        self.failedProperties = {}
+
+    def __str__(self):
+        result = ""
+        for value in self.values():
+            result += value.name + '= ' + value.textof() + '\n'
+        result += self.getReason()
+        return result
+        
+    def getCode(self):
+        if  len(self.errors) == 0:
+            return Constants.CODE_SUCCEEDED
+        if  len(self) > 0:
+            return Constants.CODE_MULTISTATUS
+        return self.errors[-1].code       
+
+    def getReason(self):
+        result = ""
+        if len(self.errors) > 0:
+            result = "Failed for: "   + repr(self.failedProperties.keys()) + "\n"
+        for error in self.errors:
+            result += "%s (%d).  " % (error.reason, error.code)
+        for reason in self.reasons:
+            result += "%s.  " % reason
+        return result
+        
+    def _scan(self, element):
+        status = None
+        statusElement = element.find(Constants.TAG_STATUS, Constants.NS_DAV)
+        if statusElement:
+            status = HttpStatus(statusElement)
+            if status.errorCount:
+                self.errors.append(status)
+        
+        propElement = element.find(Constants.TAG_PROP, Constants.NS_DAV)
+        if propElement:
+            for prop in propElement.children:
+                if status.errorCount:
+                    self.failedProperties[(prop.ns, prop.name)]= status
+                else:
+                    prop.__class__ = Element     # bad, bad trick
+                    self[prop.fullname] = prop
+        reasonElement = element.find(Constants.TAG_RESPONSEDESCRIPTION, Constants.NS_DAV)
+        if reasonElement:
+            self.reasons.append(reasonElement.textOf())
+        
+    # Instance properties
+    code = property(getCode, None, None, "HTTP response code")
+    errorCount = property(lambda self: len(self.errors), None, None, "HTTP response code")
+    reason = property(getReason, None, None, "HTTP response code")
+
+
+
+        
+class LiveProperties(object):
+    """
+    This class provides convenient access to the WebDAV 'live' properties of a resource.
+    WebDav 'live' properties are defined in RFC 2518, Section 13. 
+    Each property is converted from string to its natural data type.
+    
+    @version: $Revision$
+    @author: Roland Betz
+    """
+    
+    # restrict instance variables
+    __slots__ = ('properties')
+
+    NAMES = (Constants.PROP_CREATION_DATE, Constants.PROP_DISPLAY_NAME,
+             Constants.PROP_CONTENT_LENGTH, Constants.PROP_CONTENT_TYPE, Constants.PROP_ETAG,
+             Constants.PROP_LAST_MODIFIED, Constants.PROP_OWNER,
+             Constants.PROP_LOCK_DISCOVERY, Constants.PROP_RESOURCE_TYPE, Constants.PROP_SUPPORTED_LOCK )
+     
+    def __init__(self, properties=None, propElement=None):
+        """
+        Construct <code>StandardProperties</code> from a map of properties containing
+        live properties or from a XML 'prop' element containing live properties
+        
+        @param properties: map as implemented by class L{PropertyResponse}
+        @param propElement: an C{Element} value
+        """
+        assert isinstance(properties, PropertyResponse) or \
+               isinstance(propElement, qp_xml._element), \
+                "Argument properties has type %s" % str(type(properties))
+        self.properties = {}
+        for name, value in properties.items():
+            if  name[0] == Constants.NS_DAV  and  name[1] in self.NAMES:
+                self.properties[name[1]] = value
+
+    def getContentLanguage(self):
+        """
+        Return the language of a resource's textual content or null
+        
+        @return: string
+        """
+        
+        result = ""
+        if not self.properties.get(Constants.PROP_CONTENT_LANGUAGE, None) is None:
+            result = self.properties.get(Constants.PROP_CONTENT_LANGUAGE).textof()
+        return result
+
+    def getContentLength(self):
+        """
+        Returns the length of the resource's content in bytes.
+        
+        @return: number of bytes
+        """
+        
+        result = 0
+        if not self.properties.get(Constants.PROP_CONTENT_LENGTH, None) is None:
+            result = int(self.properties.get(Constants.PROP_CONTENT_LENGTH).textof())
+        return result
+
+    def getContentType(self):
+        """
+        Return the resource's content MIME type.
+        
+        @return: MIME type string
+        """
+        
+        result = ""
+        if not self.properties.get(Constants.PROP_CONTENT_TYPE, None) is None:
+            result = self.properties.get(Constants.PROP_CONTENT_TYPE).textof()
+        return result
+
+    def getCreationDate(self):
+        """
+        Return date of creation as time tuple.
+                
+        @return: time tuple
+        @rtype: C{time.struct_time}
+        
+        @raise ValueError: If string is not in the expected format (ISO 8601).
+        """
+        
+        datetimeString = ""
+        if not self.properties.get(Constants.PROP_CREATION_DATE, None) is None:
+            datetimeString = self.properties.get(Constants.PROP_CREATION_DATE).textof()
+
+        result = rfc822.parsedate(datetimeString)
+        if result is None:
+            result = _parseIso8601String(datetimeString)
+
+        return time.mktime(result)
+    
+    def getEntityTag(self):
+        """
+        Return a entity tag which is unique for a particular version of a resource.
+        Different resources or one resource before and after modification have different etags. 
+        
+        @return: entity tag string
+        """
+        
+        result = ""
+        if not self.properties.get(Constants.PROP_ETAG, None) is None:
+            result = self.properties.get(Constants.PROP_ETAG).textof()
+        return result
+            
+    def getDisplayName(self):
+        """
+        Returns a resource's display name.
+        
+        @return: string
+        """
+        
+        result = ""
+        if not self.properties.get(Constants.PROP_DISPLAY_NAME, None) is None:
+            result = self.properties.get(Constants.PROP_DISPLAY_NAME).textof()
+        return result
+
+    def getLastModified(self):
+        """
+        Return last modification of resource as time tuple.
+        
+        @return: Modification date time.
+        @rtype:  C{time.struct_time}
+        
+        @raise ValueError: If the date time string is not in the expected format (RFC 822 / ISO 8601).
+        """
+        
+        datetimeString = None
+        if not self.properties.get(Constants.PROP_LAST_MODIFIED, None) is None:
+            datetimeString = self.properties.get(Constants.PROP_LAST_MODIFIED).textof()
+        result = rfc822.parsedate(datetimeString)
+        if result is None:
+            result = _parseIso8601String(datetimeString)
+        return time.mktime(result)
+
+    def getLockDiscovery(self):
+        """
+        Return all current lock's applied to a resource or null if it is not locked.
+        
+        @return: a lockdiscovery DOM element according to RFC 2815
+        """
+        
+        xml = self.properties.get(Constants.PROP_LOCK_DISCOVERY)
+        return _scanLockDiscovery(xml)
+
+    def getResourceType(self):
+        """
+        Return a resource's WebDAV type.
+        
+        @return: 'collection' or 'resource'
+        """
+        
+        xml = self.properties.get(Constants.PROP_RESOURCE_TYPE)
+        if xml and xml.children:
+            return xml.children[0].name
+        return "resource"
+
+    def getSupportedLock(self):
+        """
+        Return a DOM element describing all supported lock options for a resource.
+        Usually this is shared and exclusive write lock.
+        
+        @return: supportedlock DOM element according to RFC 2815
+        """
+        
+        xml = self.properties.get(Constants.PROP_SUPPORTED_LOCK)
+        return xml
+
+    def getOwnerAsUrl(self):
+        """
+        Return a resource's owner in form of a URL.
+        
+        @return: string
+        """
+        
+        xml = self.properties.get(Constants.PROP_OWNER)
+        if xml and len(xml.children):
+            return xml.children[0].textof()
+        return None
+
+    def __str__(self):
+        result = ""
+        result += " Name=" + self.getDisplayName()
+        result += "\n Type=" + self.getResourceType()
+        result += "\n Length=" + str(self.getContentLength())
+        result += "\n Content Type="+ self.getContentType()
+        result += "\n ETag=" + self.getEntityTag()
+        result += "\n Created=" + time.strftime("%c GMT", self.getCreationDate())
+        result += "\n Modified=" + time.strftime("%c GMT", self.getLastModified())
+        return result
+
+
+def _parseIso8601String(date):
+    """ 
+    Parses the given ISO 8601 string and returns a time tuple.
+    The strings should be formatted according to RFC 3339 (see section 5.6).
+    But currently there are two exceptions:
+        1. Time offset is limited to "Z".
+        2. Fragments of seconds are ignored.
+    """
+    
+    if "." in date and "Z" in date: # Contains fragments of second?
+        secondFragmentPos = date.rfind(".")
+        timeOffsetPos = date.rfind("Z")
+        date = date[:secondFragmentPos] + date[timeOffsetPos:]
+    try:
+        timeTuple = time.strptime(date, Constants.DATE_FORMAT_ISO8601)
+    except IllegalArgumentException: # Handling Jython 2.5 bug concerning the date pattern accordingly
+        import _strptime # Using the Jython fall back solution directly
+        timeTuple = _strptime.strptime(date, Constants.DATE_FORMAT_ISO8601)
+    return timeTuple
+
+
+class ResponseFormatError(IOError):
+    """
+    An instance of this class is raised when the web server returned a webdav
+    reply which does not adhere to the standard and cannot be recognized.
+    """
+    def __init__(self, element, message= None):
+        IOError.__init__(self, "ResponseFormatError at element %s: %s"  % (element.name, message))
+        self.element = element
+        self.message = message
+        
+    
+class Element(qp_xml._element):
+    """
+    This class improves the DOM interface (i.e. element interface) provided by the qp_xml module
+    TODO: substitute qp_xml by 'real' implementation. e.g. domlette
+    """
+    def __init__(self, namespace, name, cdata=''):
+        qp_xml._element.__init__(self, ns=namespace, name=name, lang=None, parent=None,
+                    children=[], ns_scope={}, attrs={},
+                    first_cdata=cdata, following_cdata='')
+                    
+    def __str__(self):
+        return self.textof()
+        
+    def __getattr__(self, name):
+        if  (name == 'fullname'):
+            return (self.__dict__['ns'], self.__dict__['name'])
+        raise AttributeError, name
+
+    def add(self, child):
+        self.children.append(child)
+        return child
+
+def _scanLockDiscovery(root):
+    assert root.name == Constants.PROP_LOCK_DISCOVERY, "Invalid lock discovery XML element"
+    active = root.find(Constants.TAG_ACTIVE_LOCK, Constants.NS_DAV)
+    if active:
+        return _scanActivelock(active)
+    return None
+    
+def _scanActivelock(root):
+    assert root.name == Constants.TAG_ACTIVE_LOCK, "Invalid active lock XML element"
+    token = _scanOrError(root, Constants.TAG_LOCK_TOKEN)
+    value = _scanOrError(token, Constants.TAG_HREF)
+    owner = _scanOwner(root)
+    depth = _scanOrError(root, Constants.TAG_LOCK_DEPTH)
+    return (value.textof(), owner, depth.textof())
+
+def _scanOwner(root):
+    owner = root.find(Constants.TAG_LOCK_OWNER, Constants.NS_DAV)
+    if owner:
+        href = owner.find(Constants.TAG_HREF, Constants.NS_DAV)
+        if href:
+            return href.textof()
+        return owner.textof()
+    return None
+    
+def _scanOrError(elem, childName):
+    child = elem.find(childName, Constants.NS_DAV)
+    if not child:
+        raise ResponseFormatError(elem, "Invalid response: <"+childName+"> expected")
+    return child
+    
+         
+def _unquoteHref(href):
+    #print "*** Response HREF=", repr(href)
+    if type(href) == type(u""):
+        try: 
+            href = href.encode('ascii')
+        except UnicodeError:    # URL contains unescaped non-ascii character
+            # handle bug in Tamino webdav server
+            return urllib.unquote(href)
+    href = urllib.unquote(href)
+    if Constants.CONFIG_UNICODE_URL:
+        return unicode(href, 'utf-8')
+    else:
+        return unicode(href, 'latin-1')
diff --git a/src/webdav/__init__.py b/src/webdav/__init__.py
new file mode 100644
index 0000000..3e46609
--- /dev/null
+++ b/src/webdav/__init__.py
@@ -0,0 +1,16 @@
+# Copyright 2008 German Aerospace Center (DLR)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+__version__ = "$LastChangedRevision$"
diff --git a/src/webdav/acp/Ace.py b/src/webdav/acp/Ace.py
new file mode 100644
index 0000000..8321d41
--- /dev/null
+++ b/src/webdav/acp/Ace.py
@@ -0,0 +1,293 @@
+# Copyright 2008 German Aerospace Center (DLR)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+"""
+ACE object handling according to WebDAV ACP specification.
+"""
+
+
+from webdav.acp.Principal import Principal
+from webdav.acp.GrantDeny import GrantDeny
+from webdav import Constants
+from webdav.Connection import WebdavError
+
+
+__version__ = "$LastChangedRevision$"
+
+
+class ACE(object):
+    """
+    This class provides functionality for handling ACEs
+    
+    @ivar principal:   A principal (user or group)
+    @type principal:   L{Principal} object
+    @ivar invert:      Flag indicating whether ACE should invert the principal.
+    @type invert:      C{bool}
+    @ivar grantDenies: Grant or deny clauses for privileges
+    @type grantDenies: C{list} of L{GrantDeny} objects
+    @ivar protected:   Flag indicating whether ACE is protected.
+    @type protected:   C{bool}
+    @ivar inherited:   URL indicating the source from where the ACE is inherited.
+    @type inherited:   C{string}
+    """
+    
+    # restrict instance variables
+    __slots__ = ('principal', 'invert', 'grantDenies', 'protected', 'inherited')
+    
+    def __init__(self, domroot=None, principal=None, grantDenies=None):
+        """
+        Constructor should be called with either no parameters (create blank ACE),
+        one parameter (a DOM tree or principal), or two parameters (principal and 
+        sequence of GrantDenies).
+        
+        @param domroot:     A DOM tree (default: None).
+        @type  domroot:     L{webdav.WebdavResponse.Element} object
+        @param principal:   A principal (user or group), (default: None).
+        @type  principal:   L{Principal} object
+        @param grantDenies: Grant and deny clauses for privileges (default: None).
+        @type  grantDenies: sequence of L{GrantDeny} objects
+        
+        @raise WebdavError: When non-valid parameters are passed a L{WebdavError} is raised.
+        """
+        self.principal   = Principal()
+        self.protected   = None
+        self.inherited   = None
+        self.invert      = None
+        self.grantDenies = []
+
+        if domroot:
+            self.principal   = Principal(domroot=domroot.find(Constants.TAG_PRINCIPAL, Constants.NS_DAV))
+            self.inherited   = domroot.find(Constants.TAG_INHERITED, Constants.NS_DAV)
+            if self.inherited:
+                self.inherited = self.inherited.children[0].textof()
+            if domroot.find(Constants.TAG_PROTECTED, Constants.NS_DAV):
+                self.protected = 1
+            for child in domroot.children:
+                if child.ns == Constants.NS_DAV \
+                        and (child.name == Constants.TAG_GRANT or child.name == Constants.TAG_DENY):
+                    self.grantDenies.append(GrantDeny(domroot=child))
+        elif isinstance(principal, Principal):
+            newPrincipal = Principal()
+            newPrincipal.copy(principal)
+            self.principal = newPrincipal
+            if (isinstance(grantDenies, list) or isinstance(grantDenies, tuple)):
+                self.addGrantDenies(grantDenies)
+        elif domroot == None and grantDenies == None:
+            # no param ==> blank ACE
+            pass
+        else:
+            # This shouldn't happen, someone screwed up with the params ...
+            raise WebdavError('non-valid parameters handed to ACE constructor')
+
+    def __cmp__(self, other):
+        if not isinstance(other, ACE):
+            return 1
+        if self.principal == other.principal \
+                and self.invert == other.invert \
+                and self.protected == other.protected \
+                and self.inherited == other.inherited:
+            equal = 1
+            for grantDeny in self.grantDenies:
+                inList = 0
+                for otherGrantDeny in other.grantDenies:
+                    if grantDeny == otherGrantDeny:
+                        inList = 1
+                if inList == 0:
+                    equal = 0
+            return not equal
+        else:
+            return 1
+
+    def __repr__(self):
+        repr = '<class ACE: '
+        if self.invert:
+            repr += 'inverted principal, ' % (self.invert)
+        if self.principal:
+            repr += 'principal: %s, ' % (self.principal)
+        if self.protected:
+            repr += 'protected, '
+        if self.inherited:
+            repr += 'inherited href: %s, ' % (self.inherited)
+        first = 1
+        repr += 'grantDenies: ['
+        for grantDeny in self.grantDenies:
+            if first:
+                repr += '%s' % grantDeny
+                first = 0
+            else:
+                repr += ', %s' % grantDeny
+        return '%s]>' % (repr)
+
+    def copy(self, other):
+        '''Copy an ACE object.
+        
+        @param other: Another ACE to copy.
+        @type  other: L{ACE} object
+        
+        @raise WebdavError: When an object that is not an L{ACE} is passed 
+            a L{WebdavError} is raised.
+        '''
+        if not isinstance(other, ACE):
+            raise WebdavError('Non-ACE object passed to copy method: %s.' % other.__class__)
+        self.invert    = other.invert
+        self.protected = other.protected
+        self.inherited = other.inherited
+        self.principal = Principal()
+        if other.principal:
+            self.principal.copy(other.principal)
+        if other.grantDenies:
+            self.addGrantDenies(other.grantDenies)
+
+    def isValid(self):
+        """
+        Returns true/false (1/0) whether necessarry props 
+        principal and grantDenies are set and whether the ACE contains one 
+        grant or deny clauses.
+        
+        @return: Validity of ACE.
+        @rtype:  C{bool}
+        """
+        return self.principal and len(self.grantDenies) == 1
+
+    def isGrant(self):
+        '''
+        Returns true/false (1/0) if ACE contains only grant clauses.
+        
+        @return: Value whether the ACE is of grant type.
+        @rtype:  C{bool}
+        '''
+        if self.isMixed() or len(self.grantDenies) < 1:
+            return 0
+        else:
+            return self.grantDenies[0].isGrant()
+
+    def isDeny(self):
+        '''
+        Returns true/false (1/0) if ACE contains only deny clauses.
+        
+        @return: Value whether the ACE is of deny type.
+        @rtype:  C{bool}
+        '''
+        if self.isMixed() or len(self.grantDenies) < 1:
+            return 0
+        else:
+            return self.grantDenies[0].isDeny()
+
+    def isMixed(self):
+        '''
+        Returns true/false (1/0) if ACE contains both types (grant and deny) of clauses.
+        
+        @return: Value whether the ACE is of mixed (grant and deny) type.
+        @rtype:  C{bool}
+        '''
+        mixed = 0
+        if len(self.grantDenies):
+            first = self.grantDenies[0].grantDeny
+            for grantDeny in self.grantDenies:
+                if grantDeny.grantDeny != first:
+                    mixed = 1
+        return mixed
+
+    def toXML(self, defaultNameSpace=None):
+        """
+        Returns ACE content as a string of valid XML as described in WebDAV ACP.
+        
+        @param defaultNameSpace: Name space (default: None).
+        @type  defaultNameSpace: C(string)
+        """
+        assert self.isValid(), "ACE is not initialized or does not contain valid content!"
+        
+        ACE = 'D:' + Constants.TAG_ACE
+        res = self.principal.toXML(self.invert)
+        for grantDeny in self.grantDenies:
+            res += grantDeny.toXML()
+        if self.protected:
+            res += '<D:protected/>'
+        if self.inherited:
+            res += '<D:inherited><D:href>%s</D:href></D:inherited>' % (self.inherited)
+        return '<%s>%s</%s>' % (ACE, res, ACE)
+
+    def setPrincipal(self, principal):
+        '''
+        Sets the passed principal on the ACE.
+        
+        @param principal: A principal.
+        @type  principal: L{Principal} object
+        '''
+        self.principal = Principal()
+        self.principal.copy(principal)
+
+    def setInherited(self, href):
+        '''
+        Sets the passed URL on the ACE to denote from where it is inherited.
+        
+        @param href: A URL.
+        @type  href: C{string}
+        '''
+        self.inherited = href
+
+    def addGrantDeny(self, grantDeny):
+        '''
+        Adds the passed GrantDeny object to list if it's not in it, yet.
+        
+        @param grantDeny: A grant or deny clause.
+        @type  grantDeny: L{GrantDeny} object
+        '''
+        # only add it if it's not in the list, yet ...
+        inList = 0
+        for element in self.grantDenies:
+            if element == grantDeny:
+                inList = 1
+        if not inList:
+            newGrantDeny = GrantDeny()
+            newGrantDeny.copy(grantDeny)
+            self.grantDenies.append(newGrantDeny)
+
+    def addGrantDenies(self, grantDenies):
+        '''Adds the list of passed grant/deny objects to list.
+        
+        @param grantDenies: Grant or deny clauses.
+        @type  grantDenies: sequence of L{GrantDeny} objects
+        '''
+        map(lambda grantDeny: self.addGrantDeny(grantDeny), grantDenies)
+
+    def delGrantDeny(self, grantDeny):
+        '''Deletes the passed GrantDeny object from list.
+        
+        @param grantDeny: A grant or deny clause.
+        @type  grantDeny: L{GrantDeny} object
+        
+        @raise WebdavError: A L{WebdavError} is raised if the clause to be 
+            deleted is not present.
+        '''
+        # only add it if it's not in the list, yet ...
+        count = 0
+        index = 0
+        for element in self.grantDenies:
+            count += 1
+            if element == grantDeny:
+                index = count
+        if index:
+            self.grantDenies.pop(index - 1)
+        else:
+            raise WebdavError('GrantDeny to be deleted not in list: %s.' % grantDeny)
+
+    def delGrantDenies(self, grantDenies):
+        '''Deletes the list of passed grant/deny objects from list.
+        
+        @param grantDenies: Grant or deny clauses.
+        @type  grantDenies: sequence of L{GrantDeny} objects
+        '''
+        map(lambda grantDeny: self.delGrantDeny(grantDeny), grantDenies)
diff --git a/src/webdav/acp/AceHandler.py b/src/webdav/acp/AceHandler.py
new file mode 100644
index 0000000..e07b74d
--- /dev/null
+++ b/src/webdav/acp/AceHandler.py
@@ -0,0 +1,182 @@
+# Copyright 2008 German Aerospace Center (DLR)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+"""
+Handling of WebDAV Access Protocol Extensions and ACL preparation for UI.
+"""
+
+
+from webdav import Constants
+from webdav.WebdavClient import ResourceStorer
+from webdav.Connection import WebdavError
+
+
+__version__ = "$LastChangedRevision$"
+
+
+def extractSupportedPrivilegeSet(userPrivileges):
+    """
+    Returns a dictionary of supported privileges.
+    
+    @param userPrivileges: A DOM tree.
+    @type  userPrivileges: L{webdav.WebdavResponse.Element} object
+    
+    @raise WebdavError: When unknown elements appear in the 
+        C{DAV:supported-privilege} appear a L{WebdavError} is raised.
+    
+    @return: A dictionary with privilege names as keys and privilege descriptions as values.
+    @rtype:  C{dictionary}
+    """
+    result = {}
+    for element in userPrivileges.children:
+        if element.name == Constants.TAG_SUPPORTED_PRIVILEGE:
+            privName        = ''
+            privDescription = ''
+            for privilege in element.children:
+                if privilege.name == Constants.TAG_PRIVILEGE:
+                    privName = privilege.children[0].name
+                elif privilege.name == Constants.TAG_DESCRIPTION:
+                    privDescription = privilege.textof()
+                else:
+                    raise WebdavError('Unknown element in DAV:supported-privilege: ' + privilege.name)
+                
+                if privName and privDescription:
+                    result[privName] = privDescription
+                    privName        = ''
+                    privDescription = ''
+        else:
+            raise WebdavError('Invalid element tag in DAV:supported-privilege-set: ' + element.name)
+    return result
+
+
+def _insertAclDisplaynames(acl):
+    """
+    Modifies the ACL by adding the human readable names 
+    (DAV:displayname property) of each principal found in an ACL.
+    
+    This should be done with the REPORT method, but it is not supported by 
+    Jacarta Slide, yet. (As of Aug. 1, 2003 in CVS repository)
+    
+    So we are going to do it differently by foot the harder way ...
+    
+    @param acl: An ACL object for which the displaynames should be retrieved.
+    @type  acl: L{ACL} object
+    """
+    ## This is redundant code to be still kept for the REPORT method way of doing it ...
+    ## property = '''<D:prop><D:displayname/></D:prop>'''
+    ## return self.getReport(REPORT_ACL_PRINCIPAL_PROP_SET, property)
+    for ace in acl.aces:
+        if not ace.principal.property:
+            principalConnection = \
+                ResourceStorer(ace.principal.principalURL)
+            ace.principal.displayname = \
+                principalConnection.readProperty(Constants.NS_DAV, Constants.PROP_DISPLAY_NAME)
+
+
+def prepareAcls(acls):
+    """
+    Returns all ACLs describing the behaviour of the resource. The information 
+    in the ACL is modified to contain all information needed to display in the UI.
+    
+    @param acls: ACL objects.
+    @type  acls: C{list} of L{ACL} objects
+    
+    @return: (non-valid) ACLs that contain both grant and deny clauses in an ACE.
+        Displaynames are added to the Principals where needed.
+    @rtype:  C{list} of L{ACL} objects
+    """
+    for acl in acls.keys():
+        acls[acl] = acls[acl].joinGrantDeny()
+        _insertAclDisplaynames(acls[acl])
+    return acls
+
+
+def prepareAcl(acl):
+    """
+    Returns an ACL describing the behaviour of the resource. The information 
+    in the ACL is modified to contain all information needed to display in the UI.
+    
+    @param acl: An ACL object.
+    @type  acl: L{ACL} object
+    
+    @return: A (non-valid) ACL that contains both grant and deny clauses in an ACE.
+        Displaynames are added to the Principals where needed.
+    @rtype:  L{ACL} object
+    """
+    acl = acl.joinGrantDeny()
+    _insertAclDisplaynames(acl)
+    return acl
+
+
+def refineAclForSet(acl):
+    """
+    Sets the ACL composed from the UI on the WebDAV server. For that purpose the 
+    ACL object gets refined first to form a well accepted ACL to be set by the 
+    ACL WebDAV method.
+
+    @param acl: An ACL object to be refined.
+    @type  acl: L{ACL} object
+    
+    @return: A valid ACL that contains only grant or deny clauses in an ACE.
+        Inherited and protected ACEs are stripped out.
+    @rtype:  L{ACL} object
+    """
+    acl = acl.splitGrantDeny()
+    acl = acl.stripAces()
+    return acl
+
+
+##~ unsupported or unfinished methods:
+##~ 
+##~ def report(self, report, request=None, lockToken=None):
+##~     """
+##~     This method implements the WebDAV ACP method: REPORT for given report 
+##~     types.
+##~     
+##~     Parameters:
+##~     
+##~       'report' -- Report type as a string.
+##~       
+##~       'request' -- XML content of the request for the report (defaults to None).
+##~       
+##~       'lockToken' -- Lock token to be set (defaults to None).
+##~     """
+##~     raise WebdavError('Reports are not supported by our Jacarta Slide, yet (as of Aug. 1, 2003 in CVS).')
+##~     
+##~     headers                 = createCondition(lockToken)
+##~     headers['Content-Type'] = XML_CONTENT_TYPE
+##~     body                    = '<D:%s xmlns:D="DAV:">%s</D:%s>' % (report, request, report)
+##~     #print "Body: ", body
+##~     response = self.connection._request('REPORT', self.path, body, headers)
+##~     return response
+##~     ## TODO: parse DAV:error response
+##~ 
+##~ 
+##~ def getAllAcls(self):
+##~    """
+##~     Returns a dictionary of ACL resources with respective ACL objects 
+##~     that apply to the given resource.
+##~     
+##~     ### This method needs to be extended for inherited ACLs when Tamino
+##~     support tells me (Guy) how to get to them.
+##~     """
+##~     acls = {self.path: self.getAcl()}
+##~     for ace in acls[self.path].aces:
+##~         if ace.inherited:
+##~             if not ace.inherited in acls:
+##~                 acls[ace.inherited] = self.getAcl()
+##~    
+##~     # append some more stuff here to acls for possible inherited ACLs
+##~     return acls
diff --git a/src/webdav/acp/Acl.py b/src/webdav/acp/Acl.py
new file mode 100644
index 0000000..8f2b36f
--- /dev/null
+++ b/src/webdav/acp/Acl.py
@@ -0,0 +1,311 @@
+# pylint: disable-msg=W0622
+#
+# Copyright 2008 German Aerospace Center (DLR)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+
+"""
+ACL object handling according to WebDAV ACP specification.
+"""
+
+
+from webdav.acp.Ace import ACE
+from webdav import Constants
+from webdav.Connection import WebdavError
+from webdav.davlib import XML_DOC_HEADER
+
+
+__version__ = "$LastChangedRevision$"
+
+
+class ACL(object):
+    """
+    This class provides access to Access Control List funcionality
+    as specified in the WebDAV ACP.
+    
+    @ivar aces:          ACEs in ACL
+    @type aces:          C{list} of L{ACE} objects
+    @ivar withInherited: Flag indicating whether ACL contains inherited ACEs.
+    @type withInherited: C{bool}
+    """
+
+    # restrict instance variables
+    __slots__ = ('aces', 'withInherited')
+    
+    def __init__(self, domroot=None, aces=None):
+        """
+        Constructor should be called with either no parameters (create blank ACE),
+        or one parameter (a DOM tree or ACE list).
+        
+        @param domroot: A DOM tree (default: None).
+        @type  domroot: L{webdav.WebdavResponse.Element} object
+        @param aces:    ACE objects (default: None)
+        @type  aces:    C{list} of L{ACE} objects
+        
+        @raise WebdavError: When non-valid parameters are passed a L{WebdavError} is raised.
+        """
+        self.withInherited = None
+        self.aces          = []
+        
+        if domroot:
+            for child in domroot.children:
+                if child.name == Constants.TAG_ACE and child.ns == Constants.NS_DAV:
+                    self.addAce(ACE(child))
+                else:
+                    # This shouldn't happen, someone screwed up with the params ...
+                    raise WebdavError('Non-ACE tag handed to ACL constructor: ' + child.ns + child.name)
+        elif isinstance(aces, list) or isinstance(aces, tuple):
+            self.addAces(aces)
+        elif domroot == None and aces == None:
+            # no param ==> blank object
+            pass
+        else:
+            # This shouldn't happen, someone screwed up with the params ...
+            raise WebdavError('non-valid parameters handed to ACL constructor')
+
+    def __cmp__(self, other):
+        if not isinstance(other, ACL):
+            return 1
+        if self.withInherited == other.withInherited:
+            equal = 1
+            for ace in self.aces:
+                inList = 0
+                for otherAce in other.aces:
+                    if ace == otherAce:
+                        inList = 1
+                if inList == 0:
+                    equal = 0
+            return not equal
+        else:
+            return 1
+
+    def __repr__(self):
+        repr = '<class ACL: '
+        if self.withInherited:
+            repr += 'with inherited, '
+        first = 1
+        repr += 'aces: ['
+        for ace in self.aces:
+            if first:
+                repr += '%s' % ace
+                first = 0
+            else:
+                repr += ', %s' % ace
+        return '%s]>' % (repr)
+
+    def copy(self, other):
+        '''Copy an ACL object.
+        
+        @param other: Another ACL to copy.
+        @type  other: L{ACL} object
+        
+        @raise WebdavError: When an object that is not an L{ACL} is passed 
+            a L{WebdavError} is raised.
+        '''
+        if not isinstance(other, ACL):
+            raise WebdavError('Non-ACL object passed to copy method: %s' % other.__class__)
+        self.withInherited = other.withInherited
+        if other.aces:
+            self.addAces(other.aces)
+
+    def toXML(self):
+        """
+        Returns ACL content as a string of valid XML as described in WebDAV ACP.
+        """
+        aclTag = 'D:' + Constants.TAG_ACL
+        return XML_DOC_HEADER +\
+            '<' + aclTag + ' xmlns:D="DAV:">' + reduce(lambda xml, ace: xml + ace.toXML() + '\n', [''] + self.aces) +\
+            '</' + aclTag + '>'
+
+    def addAce(self, ace):
+        '''
+        Adds the passed ACE object to list if it's not in it, yet.
+        
+        @param ace: An ACE.
+        @type  ace: L{ACE} object
+        '''
+        newAce = ACE()
+        newAce.copy(ace)
+        # only add it if it's not in the list, yet ...
+        inList = 0
+        for element in self.aces:
+            if element == ace:
+                inList = 1
+        if not inList:
+            self.aces.append(newAce)
+
+    def addAces(self, aces):
+        '''Adds the list of passed ACE objects to list.
+        
+        @param aces: ACEs
+        @type  aces: sequence of L{ACE} objects
+        '''
+        for ace in aces:
+            self.addAce(ace)
+
+    def delAce(self, ace):
+        '''Deletes the passed ACE object from list.
+        
+        @param ace: An ACE.
+        @type  ace: L{ACE} object
+        
+        @raise WebdavError: When the ACE to be deleted is not within the ACL 
+            a L{WebdavError} is raised.
+        '''
+        # find where it is and delete it ...
+        count = 0
+        index = 0
+        for element in self.aces:
+            count += 1
+            if element == ace:
+                index = count
+        if index:
+            self.aces.pop(index - 1)
+        else:
+            raise WebdavError('ACE to be deleted not in list: %s.' % ace)
+
+    def delAces(self, aces):
+        '''Deletes the list of passed ACE objects from list.
+        
+        @param aces: ACEs
+        @type  aces: sequence of L{ACE} objects
+        '''
+        for ace in aces:
+            self.delAce(ace)
+
+    def delPrincipalsAces(self, principal):
+        """
+        Deletes all ACEs in ACL by given principal.
+        
+        @param principal: A principal.
+        @type  principal: L{Principal} object
+        """
+        # find where it is and delete it ...
+        index = 0
+        while index < len(self.aces):
+            if self.aces[index].principal.principalURL == principal.principalURL:
+                self.aces.pop(index)
+            else:
+                index += 1
+
+    def joinGrantDeny(self):
+        """
+        Returns a "refined" ACL of the ACL for ease of use in the UI. 
+        The purpose is to post the user an ACE that can contain both, granted 
+        and denied, privileges. So possible pairs of grant and deny ACEs are joined 
+        to return them in one ACE. This resulting ACE then of course IS NOT valid 
+        for setting ACLs anymore. They will have to be reconverted to yield valid 
+        ACLs for the ACL method.
+        
+        @return: A (non-valid) ACL that contains both grant and deny clauses in an ACE.
+        @rtype:  L{ACL} object
+        """
+        joinedAces = {}
+        for ace in self.aces:
+            if not ace.principal.principalURL is None:
+                principalKey = ace.principal.principalURL
+            elif not ace.principal.property is None:
+                principalKey = ace.principal.property
+            else:
+                principalKey = None
+            if ace.inherited:
+                principalKey = ace.inherited + ":" + principalKey
+            if principalKey in joinedAces:
+                joinedAces[principalKey].addGrantDenies(ace.grantDenies)
+            else:
+                joinedAces[principalKey] = ACE()
+                joinedAces[principalKey].copy(ace)
+        newAcl = ACL()
+        newAcl.addAces(joinedAces.values())
+        return newAcl
+
+    def splitGrantDeny(self):
+        """
+        Returns a "refined" ACL of the ACL for ease of use in the UI. 
+        The purpose is to post the user an ACE that can contain both, granted 
+        and denied, privileges. So possible joined grant and deny clauses in ACEs 
+        splitted to return them in separate ACEs. This resulting ACE then is valid 
+        for setting ACLs again. This method is to be seen in conjunction with the 
+        method joinGrantDeny as it reverts its effect.
+        
+        @return: A valid ACL that contains only ACEs with either grant or deny clauses.
+        @rtype:  L{ACL} object
+        """
+        acesGrant = {}
+        acesDeny  = {}
+        for ace in self.aces:
+            for grantDeny in ace.grantDenies:
+                if grantDeny.isGrant():
+                    if ace.principal.principalURL in acesGrant:
+                        ace.addGrantDeny(grantDeny)
+                    else:
+                        acesGrant[ace.principal.principalURL] = ACE()
+                        acesGrant[ace.principal.principalURL].copy(ace)
+                        acesGrant[ace.principal.principalURL].grantDenies = []
+                        acesGrant[ace.principal.principalURL].addGrantDeny(grantDeny)
+                else:
+                    if ace.principal.principalURL in acesDeny:
+                        ace.addGrantDeny(grantDeny)
+                    else:
+                        acesDeny[ace.principal.principalURL] = ACE()
+                        acesDeny[ace.principal.principalURL].copy(ace)
+                        acesDeny[ace.principal.principalURL].grantDenies = []
+                        acesDeny[ace.principal.principalURL].addGrantDeny(grantDeny)
+        newAcl = ACL()
+        newAcl.addAces(acesGrant.values())
+        newAcl.addAces(acesDeny.values())
+        return newAcl
+
+    def isValid(self):
+        """
+        Returns true (1) if all contained ACE objects are valid, 
+        otherwise false (0) is returned.
+        
+        @return: Validity of ACL.
+        @rtype:  C{bool}
+        """
+        valid = 1
+        if len(self.aces):
+            for ace in self.aces:
+                if not ace.isValid():
+                    valid = 0
+        return valid
+
+    def stripAces(self, inherited=True, protected=True):
+        """
+        Returns an ACL object with all ACEs stripped that are inherited 
+        and/or protected.
+        
+        @param inherited: Flag to indicate whether inherited ACEs should 
+            be stripped (default: True).
+        @type  inherited: C{bool}
+        @param protected: Flag to indicate whether protected ACEs should 
+            be stripped (default: True).
+        @type  protected: C{bool}
+        
+        @return: An ACL without the stripped ACEs.
+        @rtype:  L{ACL} object
+        """
+        newAcl = ACL()
+        if len(self.aces):
+            for ace in self.aces:
+                keep = 1
+                if inherited and ace.inherited:
+                    keep = 0
+                elif protected and ace.protected:
+                    keep = 0
+                if keep:
+                    newAcl.addAce(ace)
+        return newAcl
diff --git a/src/webdav/acp/GrantDeny.py b/src/webdav/acp/GrantDeny.py
new file mode 100644
index 0000000..52c9b93
--- /dev/null
+++ b/src/webdav/acp/GrantDeny.py
@@ -0,0 +1,241 @@
+# Copyright 2008 German Aerospace Center (DLR)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+"""
+Handling of grant and deny clauses in ACEs according to WebDAV ACP specification.
+"""
+
+
+from webdav.acp.Privilege import Privilege
+from webdav import Constants
+from webdav.Connection import WebdavError
+
+
+__version__ = "$LastChangedRevision$"
+
+
+class GrantDeny(object):
+    """
+    This class provides functionality for handling
+    grant and deny clauses in ACEs.
+    
+    @ivar grantDeny:  Flag indicating whether clause grants or denies.
+    @type grantDeny:  C{bool}
+    @ivar privileges: Privileges to be granted or denied.
+    @type privileges: C{list} of L{Privilege} objects
+    """
+    
+    def __init__(self, domroot=None):
+        """
+        Constructor should be called with either no parameters 
+        (create blank GrantDeny), or one parameter (a DOM tree).
+        
+        @param domroot:     A DOM tree (default: None).
+        @type  domroot:     L{webdav.WebdavResponse.Element} object
+        
+        @raise WebdavError: When non-valid parameters are passed a L{WebdavError} is raised.
+        """
+        self.grantDeny  = 0   # 0: deny, 1: grant
+        self.privileges = []
+        
+        if domroot:
+            self.grantDeny = (domroot.name == Constants.TAG_GRANT)
+            for child in domroot.children:
+                if child.name == Constants.TAG_PRIVILEGE and child.ns == Constants.NS_DAV:
+                    self.privileges.append(Privilege(domroot=child))
+                else:
+                    # This shouldn't happen, someone screwed up with the params ...
+                    raise WebdavError('Non-privilege tag handed to GrantDeny constructor: %s' \
+                        % child.name)
+        elif domroot == None:
+            # no param ==> blank object
+            pass
+        else:
+            # This shouldn't happen, someone screwed up with the params ...
+            raise WebdavError('Non-valid parameters handed to GrantDeny constructor.')
+
+    def __cmp__(self, other):
+        """ Compares two GrantDeny instances. """
+        if not isinstance(other, GrantDeny):
+            return 1
+        if self.grantDeny == other.grantDeny:
+            equal = 1
+            for priv in self.privileges:
+                inList = 0
+                for otherPriv in other.privileges:
+                    if priv == otherPriv:
+                        inList = 1
+                if inList == 0:
+                    equal = 0
+            return not equal
+        else:
+            return 1
+
+    def __repr__(self):
+        """ Returns the representation of an instance. """
+        representation = '<class GrantDeny: '
+        if self.grantDeny:
+            representation += 'grant privileges: ['
+        else:
+            representation += 'deny privileges: ['
+        first = 1
+        for priv in self.privileges:
+            if first:
+                representation += '%s' % priv
+                first = 0
+            else:
+                representation += ', %s' % priv
+        return '%s]>' % (representation)
+
+    def copy(self, other):
+        """
+        Copy a GrantDeny object.
+        
+        @param other: Another grant or deny clause to copy.
+        @type  other: L{GrantDeny} object
+        
+        @raise WebdavError: When an object that is not an L{GrantDeny} is passed 
+            a L{WebdavError} is raised.
+        """
+        if not isinstance(other, GrantDeny):
+            raise WebdavError('Non-GrantDeny object passed to copy method: %s' \
+                % other)
+        self.grantDeny = other.grantDeny
+        if other.privileges:
+            self.addPrivileges(other.privileges)
+
+    def isGrant(self):
+        """
+        Returns whether the set of privileges is of type "grant"
+        indicating true or false.
+        
+        @return: Value whether the clause is of grant type.
+        @rtype:  C{bool}
+        """
+        return self.grantDeny
+
+    def isDeny(self):
+        """
+        Returns whether the set of privileges is of type "deny"
+        indicating true or false.
+        
+        @return: Value whether the clause is of deny type.
+        @rtype:  C{bool}
+        """
+        return not self.grantDeny
+
+    def setGrantDeny(self, grantDeny):
+        """
+        Sets the set of privileges to given value for grantDeny.
+        
+        @param grantDeny: Grant/deny value for clause (grant: True/1, deny: False/0).
+        @type  grantDeny: C{bool}
+        """
+        if grantDeny == 0 or grantDeny == 1:
+            self.grantDeny = grantDeny
+
+    def setGrant(self):
+        """ Sets the set of privileges to type "grant". """
+        self.grantDeny = 1
+
+    def setDeny(self):
+        """ Sets the set of privileges to type "deny". """
+        self.grantDeny = 0
+
+    def isAll(self):
+        """
+        Checks whether the privileges contained are equal
+        to aggregate DAV:all privilege.
+        
+        @return: Value whether all un-aggregated privileges are present.
+        @rtype:  C{bool}
+        """
+        
+        if len(self.privileges) == 1 and self.privileges[0].name == Constants.TAG_ALL:
+            return 1
+        return 0
+
+    def addPrivilege(self, privilege):
+        """
+        Adds the passed privilege to list if it's not in it, yet.
+        
+        @param privilege: A privilege.
+        @type  privilege: L{Privilege} object
+        """
+        inList = False
+        for priv in self.privileges:
+            if priv == privilege:
+                inList = True
+        if not inList:
+            newPrivilege = Privilege()
+            newPrivilege.copy(privilege)
+            self.privileges.append(newPrivilege)
+
+    def addPrivileges(self, privileges):
+        """
+        Adds the list of passed privileges to list.
+        
+        @param privileges: Several privileges.
+        @type  privileges: sequence of L{Privilege} objects
+        """
+        for priv in privileges:
+            self.addPrivilege(priv)
+
+    def delPrivilege(self, privilege):
+        """
+        Deletes the passed privilege from list if it's in it.
+        
+        @param privilege: A privilege.
+        @type  privilege: L{Privilege} object
+        
+        @raise WebdavError: A L{WebdavError} is raised if the privilege to be 
+            deleted is not present.
+        """
+        count = 0
+        index = 0
+        for priv in self.privileges:
+            count += 1
+            if priv == privilege:
+                index = count
+        if index:
+            self.privileges.pop(index - 1)
+        else:
+            raise WebdavError('Privilege to be deleted not in list: %s' % privilege)
+
+    def delPrivileges(self, privileges):
+        """
+        Deletes the list of passed privileges from list.
+        
+        @param privileges: Several privileges.
+        @type  privileges: sequence of L{Privilege} objects
+        """
+        for priv in privileges:
+            self.delPrivilege(priv)
+
+    def toXML(self):
+        """
+        Returns string of GrantDeny content to valid XML as described in WebDAV ACP.
+        """
+        assert self.privileges, "GrantDeny object is not initialized or does not contain content!"
+        
+        if self.isGrant():
+            tag = 'D:' + Constants.TAG_GRANT
+        else:
+            tag = 'D:' + Constants.TAG_DENY
+            
+        res = ''
+        for privilege in self.privileges:
+            res += privilege.toXML()
+        return '<%s>%s</%s>' % (tag, res, tag)
diff --git a/src/webdav/acp/Makefile.am b/src/webdav/acp/Makefile.am
new file mode 100644
index 0000000..506eb92
--- /dev/null
+++ b/src/webdav/acp/Makefile.am
@@ -0,0 +1,12 @@
+sugardir = $(pythondir)/webdav/acp
+sugar_PYTHON =                  \
+             AceHandler.py      \
+             Ace.py             \
+             Acl.py             \
+             GrantDeny.py       \
+             __init__.py        \
+             Principal.py       \
+             Privilege.py
+             
+
+
diff --git a/src/webdav/acp/Principal.py b/src/webdav/acp/Principal.py
new file mode 100644
index 0000000..a0d5ec9
--- /dev/null
+++ b/src/webdav/acp/Principal.py
@@ -0,0 +1,189 @@
+# Copyright 2008 German Aerospace Center (DLR)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+"""
+Handling of principals for ACEs according to WebDAV ACP specification.
+"""
+
+
+from webdav import Constants
+from webdav.Connection import WebdavError
+
+
+__version__ = "$LastChangedRevision$"
+
+
+class Principal(object):
+    """
+    This class provides functionality for handling
+    principals according to the WebDAV ACP.
+     
+    @ivar displayname:  Name of the principal for output
+    @type displayname:  C{string}
+    @ivar principalURL: URL under which the principal can be referenced on the server.
+    @type principalURL: C{string}
+    @ivar property:     Information on type of a pseudo/jproperty principal, e. g. 
+        DAV:owner, DAV:authenticated, etc.
+    @type property:     C{string}
+    
+    @cvar _TAG_LIST_PRINCIPALS: List of allowed XML tags within a principal declaration.
+    @type _TAG_LIST_PRINCIPALS: C{tuple} of C{string}s
+    @cvar _TAG_LIST_STATUS:     List of XML tags for the status of a pseudo principal.
+    @type _TAG_LIST_STATUS:     C{tuple} of C{string}s
+    """
+    
+    # some local constants for this class to make things easier/more readable:
+    _TAG_LIST_PRINCIPALS = (Constants.TAG_HREF,     # directly by URL
+                            Constants.TAG_ALL, Constants.TAG_AUTHENTICATED, Constants.TAG_UNAUTHENTICATED, 
+                                                    # by log-in status
+                            Constants.TAG_PROPERTY, # for property info, e. g. 'owner'
+                            Constants.TAG_SELF,     # only if the resource is the principal itself
+                            Constants.TAG_PROP)     # contains property info like 'displayname'
+    _TAG_LIST_STATUS     = (Constants.TAG_ALL, Constants.TAG_AUTHENTICATED, Constants.TAG_UNAUTHENTICATED)
+    
+    # restrict instance variables
+    __slots__ = ('displayname', 'principalURL', 'property')
+    
+    def __init__(self, domroot=None, displayname=None, principalURL=None):
+        """
+        Constructor should be called with either no parameters (create blank Principal),
+        one parameter (a DOM tree), or two parameters (displayname and URL or property tag).
+        
+        @param domroot:      A DOM tree (default: None).
+        @type  domroot:      L{webdav.WebdavResponse.Element} object
+        @param displayname:  The display name of a principal (default: None).
+        @type  displayname:  C{string}
+        @param principalURL: The URL representing a principal (default: None).
+        @type  principalURL: C{string}
+        
+        @raise WebdavError: When non-valid parameters or sets of parameters are 
+            passed a L{WebdavError} is raised.
+        """
+        self.displayname  = None
+        self.principalURL = None
+        self.property     = None
+
+        if domroot:
+            for child in domroot.children:
+                if child.ns == Constants.NS_DAV and (child.name in self._TAG_LIST_PRINCIPALS):
+                    if child.name == Constants.TAG_PROP:
+                        self.displayname = \
+                            child.find(Constants.PROP_DISPLAY_NAME, Constants.NS_DAV)
+                    elif child.name == Constants.TAG_HREF:
+                        self.principalURL = child.textof()
+                        if self.principalURL and self.property in self._TAG_LIST_STATUS:
+                            raise WebdavError('Principal cannot contain a URL and "%s"' % (self.property))
+                    elif child.name == Constants.TAG_PROPERTY:
+                        if child.count() == 1:
+                            if self.property:
+                                raise WebdavError('Property for principal has already been set: old "%s", new "%s"' \
+                                    % (self.property, child.pop().name))
+                            elif self.principalURL:
+                                raise WebdavError('Principal cannot contain a URL and "%s"' % (self.property))
+                            else:
+                                self.property = child.pop().name
+                        else:
+                            raise WebdavError("There should be only one value in the property for a principal, we have: %s" \
+                                % child.name)
+                    else:
+                        if self.property:
+                            raise WebdavError('Property for principal has already been set: old "%s", new "%s"' \
+                                % (self.property, child.name))
+                        else:
+                            self.property = child.name
+                        if self.principalURL and self.property in self._TAG_LIST_STATUS:
+                            raise WebdavError('Principal cannot contain a URL and "%s"' % (self.property))
+                else: # This shouldn't happen, something's wrong with the DOM tree
+                    raise WebdavError('Non-valid tag in principal DOM tree for constructor: %s' % child.name)
+        elif displayname == None or principalURL == None:
+            if displayname:
+                self.displayname  = displayname
+            if principalURL:
+                self.principalURL = principalURL
+        else:
+            # This shouldn't happen, someone screwed up with the params ...
+            raise WebdavError('Non-valid parameters handed to Principal constructor.')
+
+    def __cmp__(self, other):
+        if not isinstance(other, Principal):
+            return 1
+        if self.displayname == other.displayname \
+                and self.principalURL == other.principalURL \
+                and self.property == other.property:
+            return 0
+        else:
+            return 1
+
+    def __repr__(self):
+        return '<class Principal: displayname: "%s", principalURL: "%s", property: "%s">' \
+            % (self.displayname, self.principalURL, self.property)
+
+    def copy(self, other):
+        """Copy Principal object.
+        
+        @param other: Another principal to copy.
+        @type  other: L{Principal} object
+        
+        @raise WebdavError: When an object that is not a L{Principal} is passed 
+            a L{WebdavError} is raised.
+        """
+        if not isinstance(other, Principal):
+            raise WebdavError('Non-Principal object passed to copy method: ' % other.__class__)
+        self.displayname  = other.displayname
+        self.principalURL = other.principalURL
+        self.property     = other.property
+
+    def isValid(self):
+        """
+        Checks whether necessarry props for principal are set.
+        
+        @return: Validity of principal.
+        @rtype:  C{bool}
+        """
+        return (self.displayname and
+                (self.principalURL or self.property) and
+                not (self.principalURL and self.property))
+        
+    def toXML(self, invert=False, displayname=False, defaultNameSpace=None):
+        """Returns string of Principal content in valid XML as described in WebDAV ACP.
+        
+        @param defaultNameSpace: Name space (default: None).
+        @type  defaultNameSpace: C(string)
+        @param invert:           True if principal should be inverted (default: False).
+        @type  invert:           C{bool}
+        @param displayname:      True if displayname should be in output (default: False).
+        @type  displayname:      C{bool}
+        """
+        # this check is needed for setting principals only:
+        # assert self.isValid(), "principal is not initialized or does not contain valid content!"
+        
+        PRINCIPAL = 'D:' + Constants.TAG_PRINCIPAL
+        res = ''
+        if self.principalURL:
+            res += '<D:%s>%s</D:%s>' % (Constants.TAG_HREF, self.principalURL, Constants.TAG_HREF)
+        elif self.property in self._TAG_LIST_STATUS \
+                or self.property == Constants.TAG_SELF:
+            res += '<D:%s/>' % (self.property)
+        elif self.property:
+            res += '<D:%s><D:%s/></D:%s>' \
+                % (Constants.TAG_PROPERTY, self.property, Constants.TAG_PROPERTY)
+        if self.displayname and displayname:
+            res += '<D:%s><D:%s>%s</D:%s></D:%s>' \
+                % (Constants.TAG_PROP, Constants.PROP_DISPLAY_NAME,
+                    self.displayname,
+                    Constants.PROP_DISPLAY_NAME, Constants.TAG_PROP)
+        if invert:
+            res = '<D:invert>%s</D:invert>' % (res)
+        return '<%s>%s</%s>' % (PRINCIPAL, res, PRINCIPAL)
diff --git a/src/webdav/acp/Privilege.py b/src/webdav/acp/Privilege.py
new file mode 100644
index 0000000..abfdcf9
--- /dev/null
+++ b/src/webdav/acp/Privilege.py
@@ -0,0 +1,125 @@
+# Copyright 2008 German Aerospace Center (DLR)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+"""
+Handling for privileges for grant and deny clauses in ACEs 
+according to WebDAV ACP specification.
+"""
+
+
+from webdav import Constants
+from webdav.Connection import WebdavError
+
+
+__version__ = "$LastChangedRevision$"
+
+
+class Privilege(object):
+    """This class provides functionality for handling privileges for ACEs.
+     
+    @ivar name: Name of the privilege.
+    @type name: C{string}
+    
+    @cvar __privileges: List of allowed XML tags for privileges.
+    @type __privileges: C{tuple} of C{string}s
+    """
+
+
+    __privileges = list()
+        
+    
+    def __init__(self, privilege=None, domroot=None):
+        """
+        Constructor should be called with either no parameters (create blank Privilege),
+        one parameter (a DOM tree or privilege name to initialize it directly).
+        
+        @param domroot: A DOM tree (default: None).
+        @type  domroot: L{webdav.WebdavResponse.Element} object
+        @param privilege: The valid name of a privilege (default: None).
+        @type  privilege: C{string}
+        
+        @raise WebdavError: When non-valid parameters or sets of parameters are 
+                            passed a L{WebdavError} is raised.
+        """
+        
+        self.name = None
+        
+        if domroot:
+            if len(domroot.children) != 1:
+                raise WebdavError('Wrong number of elements for Privilege constructor, we have: %i' \
+                    % (len(domroot.children)))
+            else:
+                child = domroot.children[0]
+                if child.ns == Constants.NS_DAV and child.name in self.__privileges:
+                    self.name = child.name
+                else:
+                    raise WebdavError('Not a valid privilege tag, we have: %s%s' \
+                        % (child.ns, child.name))
+        elif privilege:
+            if privilege in self.__privileges:
+                self.name = privilege
+            else:
+                raise WebdavError('Not a valid privilege tag, we have: %s.' % str(privilege))
+
+    @classmethod
+    def registerPrivileges(cls, privileges):
+        """
+        Registers supported privilege tags.
+        
+        @param privileges: List of privilege tags.
+        @type privileges: C{list} of C{unicode}
+        """
+        
+        for privilege in privileges:
+            cls.__privileges.append(privilege)
+    
+    def __cmp__(self, other):
+        """ Compares two Privilege instances. """
+        if not isinstance(other, Privilege):
+            return 1
+        if self.name != other.name:
+            return 1
+        else:
+            return 0
+
+    def __repr__(self):
+        """ Returns the string representation of an instance. """
+        return '<class Privilege: name: "%s">' % (self.name)
+
+    def copy(self, other):
+        """
+        Copy Privilege object.
+        
+        @param other: Another privilege to copy.
+        @type  other: L{Privilege} object
+        
+        @raise WebdavError: When an object that is not a L{Privilege} is passed 
+            a L{WebdavError} is raised.
+        """
+        if not isinstance(other, Privilege):
+            raise WebdavError('Non-Privilege object passed to copy method: %s' % other.__class__)
+        self.name = other.name
+
+    def toXML(self):
+        """
+        Returns privilege content as string in valid XML as described in WebDAV ACP.
+        
+        @param defaultNameSpace: Name space (default: None).
+        @type  defaultNameSpace: C(string)
+        """
+        assert self.name != None, "privilege is not initialized or does not contain valid content!"
+        
+        privilege = 'D:' + Constants.TAG_PRIVILEGE
+        return '<%s><D:%s/></%s>' % (privilege, self.name, privilege)
diff --git a/src/webdav/acp/__init__.py b/src/webdav/acp/__init__.py
new file mode 100644
index 0000000..b5af299
--- /dev/null
+++ b/src/webdav/acp/__init__.py
@@ -0,0 +1,33 @@
+# Copyright 2008 German Aerospace Center (DLR)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from webdav import Constants 
+from webdav.acp.Acl import ACL
+from webdav.acp.Ace import ACE
+from webdav.acp.GrantDeny import GrantDeny
+from webdav.acp.Privilege import Privilege
+from webdav.acp.Principal import Principal
+
+
+__version__ = "$LastChangedRevision$"
+
+
+privileges = [Constants.TAG_READ, Constants.TAG_WRITE, Constants.TAG_WRITE_PROPERTIES, 
+              Constants.TAG_WRITE_CONTENT, Constants.TAG_UNLOCK, Constants.TAG_READ_ACL, 
+              Constants.TAG_READ_CURRENT_USER_PRIVILEGE_SET, Constants.TAG_WRITE_ACL, Constants.TAG_ALL, 
+              Constants.TAG_BIND, Constants.TAG_UNBIND, Constants.TAG_TAMINO_SECURITY,
+              Constants.TAG_BIND_COLLECTION, Constants.TAG_UNBIND_COLLECTION, Constants.TAG_READ_PRIVATE_PROPERTIES,
+              Constants.TAG_WRITE_PRIVATE_PROPERTIES]
+Privilege.registerPrivileges(privileges)
diff --git a/src/webdav/davlib.py b/src/webdav/davlib.py
new file mode 100644
index 0000000..f4dac91
--- /dev/null
+++ b/src/webdav/davlib.py
@@ -0,0 +1,336 @@
+# pylint: disable-msg=W0402,W0231,W0141,R0903,C0321,W0701,R0904,C0103,W0201,W0102,R0913,W0622,E1101,C0111,C0121,R0901
+# DAV client library
+#
+# Copyright (C) 1998-2000 Guido van Rossum. All Rights Reserved.
+# Written by Greg Stein. Given to Guido. Licensed using the Python license.
+#
+# This module is maintained by Greg and is available at:
+#    http://www.lyra.org/greg/python/davlib.py
+#
+# Since this isn't in the Python distribution yet, we'll use the CVS ID
+# for tracking:
+#   $Id: davlib.py 3182 2008-02-22 15:57:55 +0000 (Fr, 22 Feb 2008) schlauch $
+#
+
+import httplib
+import urllib
+import string
+import types
+import mimetypes
+import qp_xml
+
+
+INFINITY = 'infinity'
+XML_DOC_HEADER = '<?xml version="1.0" encoding="utf-8"?>'
+XML_CONTENT_TYPE = 'text/xml; charset="utf-8"'
+
+# block size for copying files up to the server
+BLOCKSIZE = 16384
+
+
+class HTTPProtocolChooser(httplib.HTTPSConnection):
+    def __init__(self, *args, **kw):
+        self.protocol = kw.pop('protocol')
+        if self.protocol == "https":
+            self.default_port = 443
+        else:
+            self.default_port = 80
+            
+        apply(httplib.HTTPSConnection.__init__, (self,) + args, kw)
+
+    def connect(self):
+        if self.protocol == "https":
+            httplib.HTTPSConnection.connect(self)
+        else:
+            httplib.HTTPConnection.connect(self)
+
+
+class HTTPConnectionAuth(HTTPProtocolChooser):
+    def __init__(self, *args, **kw):
+        apply(HTTPProtocolChooser.__init__, (self,) + args, kw)
+
+        self.__username = None
+        self.__password = None
+        self.__nonce = None
+        self.__opaque = None
+
+    def setauth(self, username, password):
+        self.__username = username
+        self.__password = password
+
+
+def _parse_status(elem):
+    text = elem.textof()
+    idx1 = string.find(text, ' ')
+    idx2 = string.find(text, ' ', idx1+1)
+    return int(text[idx1:idx2]), text[idx2+1:]
+
+class _blank:
+    def __init__(self, **kw):
+        self.__dict__.update(kw)
+class _propstat(_blank): pass
+class _response(_blank): pass
+class _multistatus(_blank): pass
+
+def _extract_propstat(elem):
+    ps = _propstat(prop={}, status=None, responsedescription=None)
+    for child in elem.children:
+        if child.ns != 'DAV:':
+            continue
+        if child.name == 'prop':
+            for prop in child.children:
+                ps.prop[(prop.ns, prop.name)] = prop
+        elif child.name == 'status':
+            ps.status = _parse_status(child)
+        elif child.name == 'responsedescription':
+            ps.responsedescription = child.textof()
+        ### unknown element name
+
+    return ps
+
+def _extract_response(elem):
+    resp = _response(href=[], status=None, responsedescription=None, propstat=[])
+    for child in elem.children:
+        if child.ns != 'DAV:':
+            continue
+        if child.name == 'href':
+            resp.href.append(child.textof())
+        elif child.name == 'status':
+            resp.status = _parse_status(child)
+        elif child.name == 'responsedescription':
+            resp.responsedescription = child.textof()
+        elif child.name == 'propstat':
+            resp.propstat.append(_extract_propstat(child))
+        ### unknown child element
+
+    return resp
+
+def _extract_msr(root):
+    if root.ns != 'DAV:' or root.name != 'multistatus':
+        raise 'invalid response: <DAV:multistatus> expected'
+
+    msr = _multistatus(responses=[ ], responsedescription=None)
+
+    for child in root.children:
+        if child.ns != 'DAV:':
+            continue
+        if child.name == 'responsedescription':
+            msr.responsedescription = child.textof()
+        elif child.name == 'response':
+            msr.responses.append(_extract_response(child))
+        ### unknown child element
+
+    return msr
+
+def _extract_locktoken(root):
+    if root.ns != 'DAV:' or root.name != 'prop':
+        raise 'invalid response: <DAV:prop> expected'
+    elem = root.find('lockdiscovery', 'DAV:')
+    if not elem:
+        raise 'invalid response: <DAV:lockdiscovery> expected'
+    elem = elem.find('activelock', 'DAV:')
+    if not elem:
+        raise 'invalid response: <DAV:activelock> expected'
+    elem = elem.find('locktoken', 'DAV:')
+    if not elem:
+        raise 'invalid response: <DAV:locktoken> expected'
+    elem = elem.find('href', 'DAV:')
+    if not elem:
+        raise 'invalid response: <DAV:href> expected'
+    return elem.textof()
+
+
+class DAVResponse(httplib.HTTPResponse):
+    def parse_multistatus(self):
+        self.root = qp_xml.Parser().parse(self)
+        self.msr = _extract_msr(self.root)
+
+    def parse_lock_response(self):
+        self.root = qp_xml.Parser().parse(self)
+        self.locktoken = _extract_locktoken(self.root)
+
+
+class DAV(HTTPConnectionAuth):
+
+    response_class = DAVResponse
+
+    def get(self, url, extra_hdrs={ }):
+        return self._request('GET', url, extra_hdrs=extra_hdrs)
+
+    def head(self, url, extra_hdrs={ }):
+        return self._request('HEAD', url, extra_hdrs=extra_hdrs)
+
+    def post(self, url, data={ }, body=None, extra_hdrs={ }):
+        headers = extra_hdrs.copy()
+
+        assert body or data, "body or data must be supplied"
+        assert not (body and data), "cannot supply both body and data"
+        if data:
+            body = ''
+            for key, value in data.items():
+                if isinstance(value, types.ListType):
+                    for item in value:
+                        body = body + '&' + key + '=' + urllib.quote(str(item))
+                else:
+                    body = body + '&' + key + '=' + urllib.quote(str(value))
+            body = body[1:]
+            headers['Content-Type'] = 'application/x-www-form-urlencoded'
+
+        return self._request('POST', url, body, headers)
+
+    def options(self, url='*', extra_hdrs={ }):
+        return self._request('OPTIONS', url, extra_hdrs=extra_hdrs)
+
+    def trace(self, url, extra_hdrs={ }):
+        return self._request('TRACE', url, extra_hdrs=extra_hdrs)
+
+    def put(self, url, contents,
+            content_type=None, content_enc=None, extra_hdrs={ }):
+
+        if not content_type:
+            content_type, content_enc = mimetypes.guess_type(url)
+
+        headers = extra_hdrs.copy()
+        if content_type:
+            headers['Content-Type'] = content_type
+        if content_enc:
+            headers['Content-Encoding'] = content_enc
+        return self._request('PUT', url, contents, headers)
+
+    def delete(self, url, extra_hdrs={ }):
+        return self._request('DELETE', url, extra_hdrs=extra_hdrs)
+
+    def propfind(self, url, body=None, depth=None, extra_hdrs={ }):
+        headers = extra_hdrs.copy()
+        headers['Content-Type'] = XML_CONTENT_TYPE
+        if depth is not None:
+            headers['Depth'] = str(depth)
+        return self._request('PROPFIND', url, body, headers)
+
+    def proppatch(self, url, body, extra_hdrs={ }):
+        headers = extra_hdrs.copy()
+        headers['Content-Type'] = XML_CONTENT_TYPE
+        return self._request('PROPPATCH', url, body, headers)
+
+    def mkcol(self, url, extra_hdrs={ }):
+        return self._request('MKCOL', url, extra_hdrs=extra_hdrs)
+
+    def move(self, src, dst, extra_hdrs={ }):
+        headers = extra_hdrs.copy()
+        headers['Destination'] = dst
+        return self._request('MOVE', src, extra_hdrs=headers)
+
+    def copy(self, src, dst, depth=None, extra_hdrs={ }):
+        headers = extra_hdrs.copy()
+        headers['Destination'] = dst
+        if depth is not None:
+            headers['Depth'] = str(depth)
+        return self._request('COPY', src, extra_hdrs=headers)
+
+    def lock(self, url, owner='', timeout=None, depth=None,
+             scope='exclusive', type='write', extra_hdrs={ }):
+        headers = extra_hdrs.copy()
+        headers['Content-Type'] = XML_CONTENT_TYPE
+        if depth is not None:
+            headers['Depth'] = str(depth)
+        if timeout is not None:
+            headers['Timeout'] = timeout
+        body = XML_DOC_HEADER + \
+               '<DAV:lockinfo xmlns:DAV="DAV:">' + \
+               '<DAV:lockscope><DAV:%s/></DAV:lockscope>' % scope + \
+               '<DAV:locktype><DAV:%s/></DAV:locktype>' % type + \
+               '<DAV:owner>' + owner + '</DAV:owner>' + \
+               '</DAV:lockinfo>'
+        return self._request('LOCK', url, body, extra_hdrs=headers)
+
+    def unlock(self, url, locktoken, extra_hdrs={ }):
+        headers = extra_hdrs.copy()
+        if locktoken[0] != '<':
+            locktoken = '<' + locktoken + '>'
+        headers['Lock-Token'] = locktoken
+        return self._request('UNLOCK', url, extra_hdrs=headers)
+
+    def _request(self, method, url, body=None, extra_hdrs={}):
+        "Internal method for sending a request."
+
+        self.request(method, url, body, extra_hdrs)
+        return self.getresponse()
+
+
+    #
+    # Higher-level methods for typical client use
+    #
+
+    def allprops(self, url, depth=None):
+        body = XML_DOC_HEADER + \
+               '<DAV:propfind xmlns:DAV="DAV:"><DAV:allprop/></DAV:propfind>'
+        return self.propfind(url, body, depth=depth)
+
+    def propnames(self, url, depth=None):
+        body = XML_DOC_HEADER + \
+               '<DAV:propfind xmlns:DAV="DAV:"><DAV:propname/></DAV:propfind>'
+        return self.propfind(url, body, depth)
+
+    def getprops(self, url, *names, **kw):
+        assert names, 'at least one property name must be provided'
+        if kw.has_key('ns'):
+            xmlns = ' xmlns:NS="' + kw['ns'] + '"'
+            ns = 'NS:'
+            del kw['ns']
+        else:
+            xmlns = ns = ''
+        if kw.has_key('depth'):
+            depth = kw['depth']
+            del kw['depth']
+        else:
+            depth = 0
+        assert not kw, 'unknown arguments'
+        body = XML_DOC_HEADER + \
+               '<DAV:propfind xmlns:DAV="DAV:"' + xmlns + '><DAV:prop><' + ns + \
+               string.joinfields(names, '/><' + ns) + \
+               '/></DAV:prop></DAV:propfind>'
+        return self.propfind(url, body, depth)
+
+    def delprops(self, url, *names, **kw):
+        assert names, 'at least one property name must be provided'
+        if kw.has_key('ns'):
+            xmlns = ' xmlns:NS="' + kw['ns'] + '"'
+            ns = 'NS:'
+            del kw['ns']
+        else:
+            xmlns = ns = ''
+        assert not kw, 'unknown arguments'
+        body = XML_DOC_HEADER + \
+               '<DAV:propertyupdate xmlns:DAV="DAV:"' + xmlns + \
+               '><DAV:remove><DAV:prop><' + ns + \
+               string.joinfields(names, '/><' + ns) + \
+               '/></DAV:prop></DAV:remove></DAV:propertyupdate>'
+        return self.proppatch(url, body)
+
+    def setprops(self, url, *xmlprops, **props):
+        assert xmlprops or props, 'at least one property must be provided'
+        xmlprops = list(xmlprops)
+        if props.has_key('ns'):
+            xmlns = ' xmlns:NS="' + props['ns'] + '"'
+            ns = 'NS:'
+            del props['ns']
+        else:
+            xmlns = ns = ''
+        for key, value in props.items():
+            if value:
+                xmlprops.append('<%s%s>%s</%s%s>' % (ns, key, value, ns, key))
+            else:
+                xmlprops.append('<%s%s/>' % (ns, key))
+        elems = string.joinfields(xmlprops, '')
+        body = XML_DOC_HEADER + \
+               '<DAV:propertyupdate xmlns:DAV="DAV:"' + xmlns + \
+               '><DAV:set><DAV:prop>' + \
+               elems + \
+               '</DAV:prop></DAV:set></DAV:propertyupdate>'
+        return self.proppatch(url, body)
+
+    def get_lock(self, url, owner='', timeout=None, depth=None):
+        response = self.lock(url, owner, timeout, depth)
+        response.parse_lock_response()
+        return response.locktoken
+    
\ No newline at end of file
diff --git a/src/webdav/logger.py b/src/webdav/logger.py
new file mode 100644
index 0000000..d2538ef
--- /dev/null
+++ b/src/webdav/logger.py
@@ -0,0 +1,51 @@
+# Copyright 2008 German Aerospace Center (DLR)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+"""" 
+Module provides access to a configured logger instance.
+The logger writes C{sys.stdout}.
+"""
+
+
+import logging
+import sys
+
+
+__version__ = "$LastChangedRevision$"[11:-2]
+
+
+_defaultLoggerName = "webdavLogger"
+_fileLogFormat = "%(asctime)s: %(levelname)s: %(message)s"
+    
+
+def getDefaultLogger(handler=None):
+    """ 
+    Returns a configured logger object.
+    
+    @return: Logger instance.
+    @rtype: C{logging.Logger}
+    """
+    
+    myLogger = logging.getLogger(_defaultLoggerName)
+    if len(myLogger.handlers) == 0: 
+        myLogger.level = logging.DEBUG
+        formatter = logging.Formatter(_fileLogFormat)
+        if handler is None:
+            stdoutHandler = logging.StreamHandler(sys.stdout)
+            stdoutHandler.setFormatter(formatter)
+            myLogger.addHandler(stdoutHandler)
+        else:
+            myLogger.addHandler(handler)
+    return myLogger
diff --git a/src/webdav/qp_xml.py b/src/webdav/qp_xml.py
new file mode 100644
index 0000000..f167e1b
--- /dev/null
+++ b/src/webdav/qp_xml.py
@@ -0,0 +1,240 @@
+# pylint: disable-msg=W0311,E1101,E1103,W0201,C0103,W0622,W0402,W0706,R0911,W0613,W0612,R0912,W0141,C0111,C0121
+
+# qp_xml: Quick Parsing for XML
+#
+# Written by Greg Stein. Public Domain.
+# No Copyright, no Rights Reserved, and no Warranties.
+#
+# This module is maintained by Greg and is available as part of the XML-SIG
+# distribution. This module and its changelog can be fetched at:
+#    http://www.lyra.org/cgi-bin/viewcvs.cgi/xml/xml/utils/qp_xml.py
+#
+# Additional information can be found on Greg's Python page at:
+#    http://www.lyra.org/greg/python/
+#
+# This module was added to the XML-SIG distribution on February 14, 2000.
+# As part of that distribution, it falls under the XML distribution license.
+#
+
+import string
+from xml.parsers import expat
+
+
+error = __name__ + '.error'
+
+
+#
+# The parsing class. Instantiate and pass a string/file to .parse()
+#
+class Parser:
+  def __init__(self):
+    self.reset()
+
+  def reset(self):
+    self.root = None
+    self.cur_elem = None
+
+  def find_prefix(self, prefix):
+    elem = self.cur_elem
+    while elem:
+      if elem.ns_scope.has_key(prefix):
+        return elem.ns_scope[prefix]
+      elem = elem.parent
+
+    if prefix == '':
+      return ''        # empty URL for "no namespace"
+
+    return None
+
+  def process_prefix(self, name, use_default):
+    idx = string.find(name, ':')
+    if idx == -1:
+      if use_default:
+        return self.find_prefix(''), name
+      return '', name    # no namespace
+
+    if string.lower(name[:3]) == 'xml':
+      return '', name    # name is reserved by XML. don't break out a NS.
+
+    ns = self.find_prefix(name[:idx])
+    if ns is None:
+      raise error, 'namespace prefix ("%s") not found' % name[:idx]
+
+    return ns, name[idx+1:]
+
+  def start(self, name, attrs):
+    elem = _element(name=name, lang=None, parent=None,
+                    children=[], ns_scope={}, attrs={},
+                    first_cdata='', following_cdata='')
+
+    if self.cur_elem:
+      elem.parent = self.cur_elem
+      elem.parent.children.append(elem)
+      self.cur_elem = elem
+    else:
+      self.cur_elem = self.root = elem
+
+    work_attrs = [ ]
+
+    # scan for namespace declarations (and xml:lang while we're at it)
+    for name, value in attrs.items():
+      if name == 'xmlns':
+        elem.ns_scope[''] = value
+      elif name[:6] == 'xmlns:':
+        elem.ns_scope[name[6:]] = value
+      elif name == 'xml:lang':
+        elem.lang = value
+      else:
+        work_attrs.append((name, value))
+
+    # inherit xml:lang from parent
+    if elem.lang is None and elem.parent:
+      elem.lang = elem.parent.lang
+
+    # process prefix of the element name
+    elem.ns, elem.name = self.process_prefix(elem.name, 1)
+
+    # process attributes' namespace prefixes
+    for name, value in work_attrs:
+      elem.attrs[self.process_prefix(name, 0)] = value
+
+  def end(self, name):
+    parent = self.cur_elem.parent
+
+    del self.cur_elem.ns_scope
+    del self.cur_elem.parent
+
+    self.cur_elem = parent
+
+  def cdata(self, data):
+    elem = self.cur_elem
+    if elem.children:
+      last = elem.children[-1]
+      last.following_cdata = last.following_cdata + data
+    else:
+      elem.first_cdata = elem.first_cdata + data
+
+  def parse(self, input):
+    self.reset()
+
+    p = expat.ParserCreate()
+    p.StartElementHandler = self.start
+    p.EndElementHandler = self.end
+    p.CharacterDataHandler = self.cdata
+
+    try:
+      if type(input) == type(''):
+        p.Parse(input, 1)
+      else:
+        while 1:
+          s = input.read(_BLOCKSIZE)
+          if not s:
+            p.Parse('', 1)
+            break
+
+          p.Parse(s, 0)
+
+    finally:
+      if self.root:
+        _clean_tree(self.root)
+
+    return self.root
+
+
+#
+# handy function for dumping a tree that is returned by Parser
+#
+def dump(f, root):
+  f.write('<?xml version="1.0"?>\n')
+  namespaces = _collect_ns(root)
+  _dump_recurse(f, root, namespaces, dump_ns=1)
+  f.write('\n')
+
+
+#
+# This function returns the element's CDATA. Note: this is not recursive --
+# it only returns the CDATA immediately within the element, excluding the
+# CDATA in child elements.
+#
+def textof(elem):
+  return elem.textof()
+
+
+#########################################################################
+#
+# private stuff for qp_xml
+#
+
+_BLOCKSIZE = 16384    # chunk size for parsing input
+
+class _element:
+  def __init__(self, **kw):
+    self.__dict__.update(kw)
+
+  def textof(self):
+    '''Return the CDATA of this element.
+
+    Note: this is not recursive -- it only returns the CDATA immediately
+    within the element, excluding the CDATA in child elements.
+    '''
+    s = self.first_cdata
+    for child in self.children:
+      s = s + child.following_cdata
+    return s
+
+  def find(self, name, ns=''):
+    for elem in self.children:
+      if elem.name == name and elem.ns == ns:
+        return elem
+    return None
+
+
+def _clean_tree(elem):
+  elem.parent = None
+  del elem.parent
+  map(_clean_tree, elem.children)
+
+
+def _collect_recurse(elem, dict):
+  dict[elem.ns] = None
+  for ns, name in elem.attrs.keys():
+    dict[ns] = None
+  for child in elem.children:
+    _collect_recurse(child, dict)
+
+def _collect_ns(elem):
+  "Collect all namespaces into a NAMESPACE -> PREFIX mapping."
+  d = { '' : None }
+  _collect_recurse(elem, d)
+  del d['']    # make sure we don't pick up no-namespace entries
+  keys = d.keys()
+  for i in range(len(keys)):
+    d[keys[i]] = i
+  return d
+
+def _dump_recurse(f, elem, namespaces, lang=None, dump_ns=0):
+  if elem.ns:
+    f.write('<ns%d:%s' % (namespaces[elem.ns], elem.name))
+  else:
+    f.write('<' + elem.name)
+  for (ns, name), value in elem.attrs.items():
+    if ns:
+      f.write(' ns%d:%s="%s"' % (namespaces[ns], name, value))
+    else:
+      f.write(' %s="%s"' % (name, value))
+  if dump_ns:
+    for ns, id in namespaces.items():
+      f.write(' xmlns:ns%d="%s"' % (id, ns))
+  if elem.lang != lang:
+    f.write(' xml:lang="%s"' % elem.lang)
+  if elem.children or elem.first_cdata:
+    f.write('>' + elem.first_cdata)
+    for child in elem.children:
+      _dump_recurse(f, child, namespaces, elem.lang)
+      f.write(child.following_cdata)
+    if elem.ns:
+      f.write('</ns%d:%s>' % (namespaces[elem.ns], elem.name))
+    else:
+      f.write('</%s>' % elem.name)
+  else:
+    f.write('/>')
diff --git a/src/webdav/uuid_.py b/src/webdav/uuid_.py
new file mode 100644
index 0000000..3b590e8
--- /dev/null
+++ b/src/webdav/uuid_.py
@@ -0,0 +1,476 @@
+r"""UUID objects (universally unique identifiers) according to RFC 4122.
+
+This module provides immutable UUID objects (class UUID) and the functions
+uuid1(), uuid3(), uuid4(), uuid5() for generating version 1, 3, 4, and 5
+UUIDs as specified in RFC 4122.
+
+If all you want is a unique ID, you should probably call uuid1() or uuid4().
+Note that uuid1() may compromise privacy since it creates a UUID containing
+the computer's network address.  uuid4() creates a random UUID.
+
+Typical usage:
+
+    >>> import uuid
+
+    # make a UUID based on the host ID and current time
+    >>> uuid.uuid1()
+    UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')
+
+    # make a UUID using an MD5 hash of a namespace UUID and a name
+    >>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
+    UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')
+
+    # make a random UUID
+    >>> uuid.uuid4()
+    UUID('16fd2706-8baf-433b-82eb-8c7fada847da')
+
+    # make a UUID using a SHA-1 hash of a namespace UUID and a name
+    >>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
+    UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')
+
+    # make a UUID from a string of hex digits (braces and hyphens ignored)
+    >>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}')
+
+    # convert a UUID to a string of hex digits in standard form
+    >>> str(x)
+    '00010203-0405-0607-0809-0a0b0c0d0e0f'
+
+    # get the raw 16 bytes of the UUID
+    >>> x.bytes
+    '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'
+
+    # make a UUID from a 16-byte string
+    >>> uuid.UUID(bytes=x.bytes)
+    UUID('00010203-0405-0607-0809-0a0b0c0d0e0f')
+"""
+
+__author__ = 'Ka-Ping Yee <ping@zesty.ca>'
+__date__ = '$Date: 2006/06/12 23:15:40 $'.split()[1].replace('/', '-')
+__version__ = '$Revision: 1.30 $'.split()[1]
+
+RESERVED_NCS, RFC_4122, RESERVED_MICROSOFT, RESERVED_FUTURE = [
+    'reserved for NCS compatibility', 'specified in RFC 4122',
+    'reserved for Microsoft compatibility', 'reserved for future definition']
+
+class UUID(object):
+    """Instances of the UUID class represent UUIDs as specified in RFC 4122.
+    UUID objects are immutable, hashable, and usable as dictionary keys.
+    Converting a UUID to a string with str() yields something in the form
+    '12345678-1234-1234-1234-123456789abc'.  The UUID constructor accepts
+    four possible forms: a similar string of hexadecimal digits, or a
+    string of 16 raw bytes as an argument named 'bytes', or a tuple of
+    six integer fields (with 32-bit, 16-bit, 16-bit, 8-bit, 8-bit, and
+    48-bit values respectively) as an argument named 'fields', or a single
+    128-bit integer as an argument named 'int'.
+
+    UUIDs have these read-only attributes:
+
+        bytes       the UUID as a 16-byte string
+
+        fields      a tuple of the six integer fields of the UUID,
+                    which are also available as six individual attributes
+                    and two derived attributes:
+
+            time_low                the first 32 bits of the UUID
+            time_mid                the next 16 bits of the UUID
+            time_hi_version         the next 16 bits of the UUID
+            clock_seq_hi_variant    the next 8 bits of the UUID
+            clock_seq_low           the next 8 bits of the UUID
+            node                    the last 48 bits of the UUID
+
+            time                    the 60-bit timestamp
+            clock_seq               the 14-bit sequence number
+
+        hex         the UUID as a 32-character hexadecimal string
+
+        int         the UUID as a 128-bit integer
+
+        urn         the UUID as a URN as specified in RFC 4122
+
+        variant     the UUID variant (one of the constants RESERVED_NCS,
+                    RFC_4122, RESERVED_MICROSOFT, or RESERVED_FUTURE)
+
+        version     the UUID version number (1 through 5, meaningful only
+                    when the variant is RFC_4122)
+    """
+
+    def __init__(self, hex=None, bytes=None, fields=None, int=None,
+                       version=None):
+        r"""Create a UUID from either a string of 32 hexadecimal digits,
+        a string of 16 bytes as the 'bytes' argument, a tuple of six
+        integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version,
+        8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as
+        the 'fields' argument, or a single 128-bit integer as the 'int'
+        argument.  When a string of hex digits is given, curly braces,
+        hyphens, and a URN prefix are all optional.  For example, these
+        expressions all yield the same UUID:
+
+        UUID('{12345678-1234-5678-1234-567812345678}')
+        UUID('12345678123456781234567812345678')
+        UUID('urn:uuid:12345678-1234-5678-1234-567812345678')
+        UUID(bytes='\x12\x34\x56\x78'*4)
+        UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678))
+        UUID(int=0x12345678123456781234567812345678)
+
+        Exactly one of 'hex', 'bytes', 'fields', or 'int' must be given.
+        The 'version' argument is optional; if given, the resulting UUID
+        will have its variant and version number set according to RFC 4122,
+        overriding bits in the given 'hex', 'bytes', 'fields', or 'int'.
+        """
+
+        if [hex, bytes, fields, int].count(None) != 3:
+            raise TypeError('need just one of hex, bytes, fields, or int')
+        if hex is not None:
+            hex = hex.replace('urn:', '').replace('uuid:', '')
+            hex = hex.strip('{}').replace('-', '')
+            if len(hex) != 32:
+                raise ValueError('badly formed hexadecimal UUID string')
+            int = long(hex, 16)
+        if bytes is not None:
+            if len(bytes) != 16:
+                raise ValueError('bytes is not a 16-char string')
+            int = long(('%02x'*16) % tuple(map(ord, bytes)), 16)
+        if fields is not None:
+            if len(fields) != 6:
+                raise ValueError('fields is not a 6-tuple')
+            (time_low, time_mid, time_hi_version,
+             clock_seq_hi_variant, clock_seq_low, node) = fields
+            if not 0 <= time_low < 1<<32L:
+                raise ValueError('field 1 out of range (need a 32-bit value)')
+            if not 0 <= time_mid < 1<<16L:
+                raise ValueError('field 2 out of range (need a 16-bit value)')
+            if not 0 <= time_hi_version < 1<<16L:
+                raise ValueError('field 3 out of range (need a 16-bit value)')
+            if not 0 <= clock_seq_hi_variant < 1<<8L:
+                raise ValueError('field 4 out of range (need an 8-bit value)')
+            if not 0 <= clock_seq_low < 1<<8L:
+                raise ValueError('field 5 out of range (need an 8-bit value)')
+            if not 0 <= node < 1<<48L:
+                raise ValueError('field 6 out of range (need a 48-bit value)')
+            clock_seq = (clock_seq_hi_variant << 8L) | clock_seq_low
+            int = ((time_low << 96L) | (time_mid << 80L) |
+                   (time_hi_version << 64L) | (clock_seq << 48L) | node)
+        if int is not None:
+            if not 0 <= int < 1<<128L:
+                raise ValueError('int is out of range (need a 128-bit value)')
+        if version is not None:
+            if not 1 <= version <= 5:
+                raise ValueError('illegal version number')
+            # Set the variant to RFC 4122.
+            int &= ~(0xc000 << 48L)
+            int |= 0x8000 << 48L
+            # Set the version number.
+            int &= ~(0xf000 << 64L)
+            int |= version << 76L
+        self.__dict__['int'] = int
+
+    def __cmp__(self, other):
+        if isinstance(other, UUID):
+            return cmp(self.int, other.int)
+        return NotImplemented
+
+    def __hash__(self):
+        return hash(self.int)
+
+    def __int__(self):
+        return self.int
+
+    def __repr__(self):
+        return 'UUID(%r)' % str(self)
+
+    def __setattr__(self, name, value):
+        raise TypeError('UUID objects are immutable')
+
+    def __str__(self):
+        hex = '%032x' % self.int
+        return '%s-%s-%s-%s-%s' % (
+            hex[:8], hex[8:12], hex[12:16], hex[16:20], hex[20:])
+
+    def get_bytes(self):
+        bytes = ''
+        for shift in range(0, 128, 8):
+            bytes = chr((self.int >> shift) & 0xff) + bytes
+        return bytes
+
+    bytes = property(get_bytes)
+
+    def get_fields(self):
+        return (self.time_low, self.time_mid, self.time_hi_version,
+                self.clock_seq_hi_variant, self.clock_seq_low, self.node)
+
+    fields = property(get_fields)
+
+    def get_time_low(self):
+        return self.int >> 96L
+
+    time_low = property(get_time_low)
+
+    def get_time_mid(self):
+        return (self.int >> 80L) & 0xffff
+
+    time_mid = property(get_time_mid)
+
+    def get_time_hi_version(self):
+        return (self.int >> 64L) & 0xffff
+
+    time_hi_version = property(get_time_hi_version)
+
+    def get_clock_seq_hi_variant(self):
+        return (self.int >> 56L) & 0xff
+
+    clock_seq_hi_variant = property(get_clock_seq_hi_variant)
+
+    def get_clock_seq_low(self):
+        return (self.int >> 48L) & 0xff
+
+    clock_seq_low = property(get_clock_seq_low)
+
+    def get_time(self):
+        return (((self.time_hi_version & 0x0fffL) << 48L) |
+                (self.time_mid << 32L) | self.time_low)
+
+    time = property(get_time)
+
+    def get_clock_seq(self):
+        return (((self.clock_seq_hi_variant & 0x3fL) << 8L) |
+                self.clock_seq_low)
+
+    clock_seq = property(get_clock_seq)
+
+    def get_node(self):
+        return self.int & 0xffffffffffff
+
+    node = property(get_node)
+
+    def get_hex(self):
+        return '%032x' % self.int
+
+    hex = property(get_hex)
+
+    def get_urn(self):
+        return 'urn:uuid:' + str(self)
+
+    urn = property(get_urn)
+
+    def get_variant(self):
+        if not self.int & (0x8000 << 48L):
+            return RESERVED_NCS
+        elif not self.int & (0x4000 << 48L):
+            return RFC_4122
+        elif not self.int & (0x2000 << 48L):
+            return RESERVED_MICROSOFT
+        else:
+            return RESERVED_FUTURE
+
+    variant = property(get_variant)
+
+    def get_version(self):
+        # The version bits are only meaningful for RFC 4122 UUIDs.
+        if self.variant == RFC_4122:
+            return int((self.int >> 76L) & 0xf)
+
+    version = property(get_version)
+
+def _ifconfig_getnode():
+    """Get the hardware address on Unix by running ifconfig."""
+    import os
+    for dir in ['', '/sbin/', '/usr/sbin']:
+        try:
+            pipe = os.popen(os.path.join(dir, 'ifconfig'))
+        except IOError:
+            continue
+        for line in pipe:
+            words = line.lower().split()
+            for i in range(len(words)):
+                if words[i] in ['hwaddr', 'ether']:
+                    return int(words[i + 1].replace(':', ''), 16)
+
+def _ipconfig_getnode():
+    """Get the hardware address on Windows by running ipconfig.exe."""
+    import os, re
+    dirs = ['', r'c:\windows\system32', r'c:\winnt\system32']
+    try:
+        import ctypes
+        buffer = ctypes.create_string_buffer(300)
+        ctypes.windll.kernel32.GetSystemDirectoryA(buffer, 300)
+        dirs.insert(0, buffer.value.decode('mbcs'))
+    except:
+        pass
+    for dir in dirs:
+        try:
+            pipe = os.popen(os.path.join(dir, 'ipconfig') + ' /all')
+        except IOError:
+            continue
+        for line in pipe:
+            value = line.split(':')[-1].strip().lower()
+            if re.match('([0-9a-f][0-9a-f]-){5}[0-9a-f][0-9a-f]', value):
+                return int(value.replace('-', ''), 16)
+
+def _netbios_getnode():
+    """Get the hardware address on Windows using NetBIOS calls.
+    See http://support.microsoft.com/kb/118623 for details."""
+    import win32wnet, netbios
+    ncb = netbios.NCB()
+    ncb.Command = netbios.NCBENUM
+    ncb.Buffer = adapters = netbios.LANA_ENUM()
+    adapters._pack()
+    if win32wnet.Netbios(ncb) != 0:
+        return
+    adapters._unpack()
+    for i in range(adapters.length):
+        ncb.Reset()
+        ncb.Command = netbios.NCBRESET
+        ncb.Lana_num = ord(adapters.lana[i])
+        if win32wnet.Netbios(ncb) != 0:
+            continue
+        ncb.Reset()
+        ncb.Command = netbios.NCBASTAT
+        ncb.Lana_num = ord(adapters.lana[i])
+        ncb.Callname = '*'.ljust(16)
+        ncb.Buffer = status = netbios.ADAPTER_STATUS()
+        if win32wnet.Netbios(ncb) != 0:
+            continue
+        status._unpack()
+        bytes = map(ord, status.adapter_address)
+        return ((bytes[0]<<40L) + (bytes[1]<<32L) + (bytes[2]<<24L) +
+                (bytes[3]<<16L) + (bytes[4]<<8L) + bytes[5])
+
+# Thanks to Thomas Heller for ctypes and for his help with its use here.
+
+# If ctypes is available, use it to find system routines for UUID generation.
+_uuid_generate_random = _uuid_generate_time = _UuidCreate = None
+try:
+    import ctypes, ctypes.util
+    _buffer = ctypes.create_string_buffer(16)
+
+    # The uuid_generate_* routines are provided by libuuid on at least
+    # Linux and FreeBSD, and provided by libc on Mac OS X.
+    for libname in ['uuid', 'c']:
+        try:
+            lib = ctypes.CDLL(ctypes.util.find_library(libname))
+        except:
+            continue
+        if hasattr(lib, 'uuid_generate_random'):
+            _uuid_generate_random = lib.uuid_generate_random
+        if hasattr(lib, 'uuid_generate_time'):
+            _uuid_generate_time = lib.uuid_generate_time
+
+    # On Windows prior to 2000, UuidCreate gives a UUID containing the
+    # hardware address.  On Windows 2000 and later, UuidCreate makes a
+    # random UUID and UuidCreateSequential gives a UUID containing the
+    # hardware address.  These routines are provided by the RPC runtime.
+    try:
+        lib = ctypes.windll.rpcrt4
+    except:
+        lib = None
+    _UuidCreate = getattr(lib, 'UuidCreateSequential',
+                          getattr(lib, 'UuidCreate', None))
+except:
+    pass
+
+def _unixdll_getnode():
+    """Get the hardware address on Unix using ctypes."""
+    _uuid_generate_time(_buffer)
+    return UUID(bytes=_buffer.raw).node
+
+def _windll_getnode():
+    """Get the hardware address on Windows using ctypes."""
+    if _UuidCreate(_buffer) == 0:
+        return UUID(bytes=_buffer.raw).node
+
+def _random_getnode():
+    """Get a random node ID, with eighth bit set as suggested by RFC 4122."""
+    import random
+    return random.randrange(0, 1<<48L) | 0x010000000000L
+
+_node = None
+
+def getnode():
+    """Get the hardware address as a 48-bit integer.  The first time this
+    runs, it may launch a separate program, which could be quite slow.  If
+    all attempts to obtain the hardware address fail, we choose a random
+    48-bit number with its eighth bit set to 1 as recommended in RFC 4122."""
+
+    global _node
+    if _node is not None:
+        return _node
+
+    import sys
+    if sys.platform == 'win32':
+        getters = [_windll_getnode, _netbios_getnode, _ipconfig_getnode]
+    else:
+        getters = [_unixdll_getnode, _ifconfig_getnode]
+
+    for getter in getters + [_random_getnode]:
+        try:
+            _node = getter()
+        except:
+            continue
+        if _node is not None:
+            return _node
+
+def uuid1(node=None, clock_seq=None):
+    """Generate a UUID from a host ID, sequence number, and the current time.
+    If 'node' is not given, getnode() is used to obtain the hardware
+    address.  If 'clock_seq' is given, it is used as the sequence number;
+    otherwise a random 14-bit sequence number is chosen."""
+
+    # When the system provides a version-1 UUID generator, use it (but don't
+    # use UuidCreate here because its UUIDs don't conform to RFC 4122).
+    if _uuid_generate_time and node is clock_seq is None:
+        _uuid_generate_time(_buffer)
+        return UUID(bytes=_buffer.raw)
+
+    import time
+    nanoseconds = int(time.time() * 1e9)
+    # 0x01b21dd213814000 is the number of 100-ns intervals between the
+    # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00.
+    timestamp = int(nanoseconds/100) + 0x01b21dd213814000L
+    if clock_seq is None:
+        import random
+        clock_seq = random.randrange(1<<14L) # instead of stable storage
+    time_low = timestamp & 0xffffffffL
+    time_mid = (timestamp >> 32L) & 0xffffL
+    time_hi_version = (timestamp >> 48L) & 0x0fffL
+    clock_seq_low = clock_seq & 0xffL
+    clock_seq_hi_variant = (clock_seq >> 8L) & 0x3fL
+    if node is None:
+        node = getnode()
+    return UUID(fields=(time_low, time_mid, time_hi_version,
+                        clock_seq_hi_variant, clock_seq_low, node), version=1)
+
+def uuid3(namespace, name):
+    """Generate a UUID from the MD5 hash of a namespace UUID and a name."""
+    import md5
+    hash = md5.md5(namespace.bytes + name).digest()
+    return UUID(bytes=hash[:16], version=3)
+
+def uuid4():
+    """Generate a random UUID."""
+
+    # When the system provides a version-4 UUID generator, use it.
+    if _uuid_generate_random:
+        _uuid_generate_random(_buffer)
+        return UUID(bytes=_buffer.raw)
+
+    # Otherwise, get randomness from urandom or the 'random' module.
+    try:
+        import os
+        return UUID(bytes=os.urandom(16), version=4)
+    except:
+        import random
+        bytes = [chr(random.randrange(256)) for i in range(16)]
+        return UUID(bytes=bytes, version=4)
+
+def uuid5(namespace, name):
+    """Generate a UUID from the SHA-1 hash of a namespace UUID and a name."""
+    import sha
+    hash = sha.sha(namespace.bytes + name).digest()
+    return UUID(bytes=hash[:16], version=5)
+
+# The following standard UUIDs are for use with uuid3() or uuid5().
+
+NAMESPACE_DNS = UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8')
+NAMESPACE_URL = UUID('6ba7b811-9dad-11d1-80b4-00c04fd430c8')
+NAMESPACE_OID = UUID('6ba7b812-9dad-11d1-80b4-00c04fd430c8')
+NAMESPACE_X500 = UUID('6ba7b814-9dad-11d1-80b4-00c04fd430c8')
-- 
1.7.4.4