code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
# Copyright (C) 2007 Alexandre Conrad, alexandre (dot) conrad (at) gmail (dot) com
#
# This module is part of FormAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import helpers as h
from formalchemy import config
from formalchemy import base
from tempita import Template as TempitaTemplate # must import after base
__all__ = ["Grid"]
def _validate_iterable(o):
try:
iter(o)
except:
raise Exception('instances must be an iterable, not %s' % o)
class Grid(base.EditableRenderer):
"""
Besides `FieldSet`, `FormAlchemy` provides `Grid` for editing and
rendering multiple instances at once. Most of what you know about
`FieldSet` applies to `Grid`, with the following differences to
accomodate being bound to multiple objects:
The `Grid` constructor takes the following arguments:
* `cls`: the class type that the `Grid` will render (NOT an instance)
* `instances=[]`: the instances to render as grid rows
* `session=None`: as in `FieldSet`
* `data=None`: as in `FieldSet`
`bind` and `rebind` take the last 3 arguments (`instances`, `session`,
and `data`); you may not specify a different class type than the one
given to the constructor.
The `Grid` `errors` attribute is a dictionary keyed by bound instance,
whose value is similar to the `errors` from a `FieldSet`, that is, a
dictionary whose keys are `Field`s, and whose values are
`ValidationError` instances.
"""
engine = _render = _render_readonly = None
def __init__(self, cls, instances=[], session=None, data=None, prefix=None):
from sqlalchemy.orm import class_mapper
if not class_mapper(cls):
raise Exception('Grid must be bound to an SA mapped class')
base.EditableRenderer.__init__(self, cls, session, data, prefix)
self.rows = instances
self.readonly = False
self.errors = {}
def configure(self, pk=False, exclude=[], include=[], options=[], readonly=False):
"""
The `Grid` `configure` method takes the same arguments as `FieldSet`
(`pk`, `exclude`, `include`, `options`, `readonly`), except there is
no `focus` argument.
"""
base.EditableRenderer.configure(self, pk, exclude, include, options)
self.readonly = readonly
def bind(self, instances, session=None, data=None):
"""bind to instances"""
_validate_iterable(instances)
if not session:
i = iter(instances)
try:
instance = i.next()
except StopIteration:
pass
else:
from sqlalchemy.orm import object_session
session = object_session(instance)
mr = base.EditableRenderer.bind(self, self.model, session, data)
mr.rows = instances
return mr
def rebind(self, instances=None, session=None, data=None):
"""rebind to instances"""
if instances is not None:
_validate_iterable(instances)
base.EditableRenderer.rebind(self, self.model, session, data)
if instances is not None:
self.rows = instances
def render(self, **kwargs):
engine = self.engine or config.engine
if self._render or self._render_readonly:
import warnings
warnings.warn(DeprecationWarning('_render and _render_readonly are deprecated and will be removed in 1.5. Use a TemplateEngine instead'))
if self.readonly:
if self._render_readonly is not None:
engine._update_args(kwargs)
return self._render_readonly(collection=self, **kwargs)
return engine('grid_readonly', collection=self, **kwargs)
if self._render is not None:
engine._update_args(kwargs)
return self._render(collection=self, **kwargs)
return engine('grid', collection=self, **kwargs)
def _set_active(self, instance, session=None):
base.EditableRenderer.rebind(self, instance, session or self.session, self.data)
def get_errors(self, row):
if self.errors:
return self.errors.get(row, {})
return {}
def validate(self):
"""These are the same as in `FieldSet`"""
if self.data is None:
raise Exception('Cannot validate without binding data')
if self.readonly:
raise Exception('Cannot validate a read-only Grid')
self.errors.clear()
success = True
for row in self.rows:
self._set_active(row)
row_errors = {}
for field in self.render_fields.itervalues():
success = field._validate() and success
if field.errors:
row_errors[field] = field.errors
self.errors[row] = row_errors
return success
def sync_one(self, row):
"""
Use to sync a single one of the instances that are
bound to the `Grid`.
"""
# we want to allow the user to sync just rows w/o errors, so this is public
if self.readonly:
raise Exception('Cannot sync a read-only Grid')
self._set_active(row)
base.EditableRenderer.sync(self)
def sync(self):
"""These are the same as in `FieldSet`"""
for row in self.rows:
self.sync_one(row)
| Python |
import os
import sys
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
requires = [
'pyramid',
'SQLAlchemy',
'transaction',
'repoze.tm2',
'zope.sqlalchemy',
'WebError',
]
if sys.version_info[:3] < (2,5,0):
requires.append('pysqlite')
setup(name='pyramidapp',
version='0.0',
description='pyramidapp',
long_description=README + '\n\n' + CHANGES,
classifiers=[
"Programming Language :: Python",
"Framework :: Pylons",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author='',
author_email='',
url='',
keywords='web wsgi bfg pylons pyramid',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
test_suite='pyramidapp',
install_requires = requires,
entry_points = """\
[paste.app_factory]
main = pyramidapp:main
""",
paster_plugins=['pyramid'],
)
| Python |
# -*- coding: utf-8 -*-
| Python |
import transaction
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import Unicode
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import sessionmaker
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
class MyModel(Base):
__tablename__ = 'models'
id = Column(Integer, primary_key=True)
name = Column(Unicode(255), unique=True)
value = Column(Integer)
class Foo(Base):
__tablename__ = 'foo'
id = Column(Integer, primary_key=True)
bar = Column(Unicode(255))
def populate():
session = DBSession()
model = MyModel(name=u'root',value=55)
session.add(model)
session.flush()
for i in range(50):
model = MyModel(name=u'root%i' % i,value=i)
session.add(model)
session.flush()
transaction.commit()
def initialize_sql(engine):
DBSession.configure(bind=engine)
Base.metadata.bind = engine
Base.metadata.create_all(engine)
try:
populate()
except IntegrityError:
DBSession.rollback()
| Python |
import unittest
from pyramid.config import Configurator
from pyramid import testing
import os
from webtest import TestApp
from pyramidapp import main
from paste.deploy import loadapp
dirname = os.path.abspath(__file__)
dirname = os.path.dirname(dirname)
dirname = os.path.dirname(dirname)
def _initTestingDB():
from sqlalchemy import create_engine
from pyramidapp.models import initialize_sql
session = initialize_sql(create_engine('sqlite://'))
return session
class TestController(unittest.TestCase):
def setUp(self):
app = loadapp('config:%s' % os.path.join(dirname, 'development.ini'))
self.app = TestApp(app)
self.config = Configurator(autocommit=True)
self.config.begin()
#_initTestingDB()
def tearDown(self):
self.config.end()
def test_index(self):
# index
resp = self.app.get('/admin/')
resp.mustcontain('/admin/Foo')
resp = resp.click('Foo')
## Simple model
# add page
resp.mustcontain('/admin/Foo/new')
resp = resp.click('New Foo')
resp.mustcontain('/admin/Foo"')
form = resp.forms[0]
form['Foo--bar'] = 'value'
resp = form.submit()
assert resp.headers['location'] == 'http://localhost/admin/Foo', resp
# model index
resp = resp.follow()
resp.mustcontain('<td>value</td>')
# edit page
form = resp.forms[0]
resp = form.submit()
form = resp.forms[0]
form['Foo-1-bar'] = 'new value'
#form['_method'] = 'PUT'
resp = form.submit()
resp = resp.follow()
# model index
resp.mustcontain('<td>new value</td>')
# delete
resp = self.app.get('/admin/Foo')
resp.mustcontain('<td>new value</td>')
resp = resp.forms[1].submit()
resp = resp.follow()
assert 'new value' not in resp, resp
def test_json(self):
# index
response = self.app.get('/admin/json')
response.mustcontain('{"models": {', '"Foo": "http://localhost/admin/Foo/json"')
## Simple model
# add page
response = self.app.post('/admin/Foo/json',
{'Foo--bar': 'value'})
data = response.json
id = data['item_url'].split('/')[-1]
response.mustcontain('"Foo-%s-bar": "value"' % id)
# get data
response = self.app.get(str(data['item_url']))
response.mustcontain('"Foo-%s-bar": "value"' % id)
# edit page
response = self.app.post(str(data['item_url']), {'Foo-%s-bar' % id: 'new value'})
response.mustcontain('"Foo-%s-bar": "new value"' % id)
# delete
response = self.app.delete(str(data['item_url']))
| Python |
from pyramidapp.models import DBSession
from pyramidapp.models import MyModel
def my_view(request):
dbsession = DBSession()
root = dbsession.query(MyModel).filter(MyModel.name==u'root').first()
return {'root':root, 'project':'pyramidapp'}
| Python |
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from pyramidapp.models import initialize_sql
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
initialize_sql(engine)
config = Configurator(settings=settings)
config.add_static_view('static', 'pyramidapp:static')
config.add_route('home', '/', view='pyramidapp.views.my_view',
view_renderer='templates/mytemplate.pt')
config.load_zcml('formalchemy:configure.zcml')
config.add_route('fa_admin', '/admin/*traverse',
factory='formalchemy.ext.pyramid.admin.AdminView')
config.registry.settings.update({
'fa.models': config.maybe_dotted('pyramidapp.models'),
'fa.forms': config.maybe_dotted('pyramidapp.forms'),
'fa.session_factory': config.maybe_dotted('pyramidapp.models.DBSession'),
})
return config.make_wsgi_app()
| Python |
#!/usr/bin/env python
#
# Copyright 2006, 2007 Google Inc. All Rights Reserved.
# Author: danderson@google.com (David Anderson)
#
# Script for uploading files to a Google Code project.
#
# This is intended to be both a useful script for people who want to
# streamline project uploads and a reference implementation for
# uploading files to Google Code projects.
#
# To upload a file to Google Code, you need to provide a path to the
# file on your local machine, a small summary of what the file is, a
# project name, and a valid account that is a member or owner of that
# project. You can optionally provide a list of labels that apply to
# the file. The file will be uploaded under the same name that it has
# in your local filesystem (that is, the "basename" or last path
# component). Run the script with '--help' to get the exact syntax
# and available options.
#
# Note that the upload script requests that you enter your
# googlecode.com password. This is NOT your Gmail account password!
# This is the password you use on googlecode.com for committing to
# Subversion and uploading files. You can find your password by going
# to http://code.google.com/hosting/settings when logged in with your
# Gmail account. If you have already committed to your project's
# Subversion repository, the script will automatically retrieve your
# credentials from there (unless disabled, see the output of '--help'
# for details).
#
# If you are looking at this script as a reference for implementing
# your own Google Code file uploader, then you should take a look at
# the upload() function, which is the meat of the uploader. You
# basically need to build a multipart/form-data POST request with the
# right fields and send it to https://PROJECT.googlecode.com/files .
# Authenticate the request using HTTP Basic authentication, as is
# shown below.
#
# Licensed under the terms of the Apache Software License 2.0:
# http://www.apache.org/licenses/LICENSE-2.0
#
# Questions, comments, feature requests and patches are most welcome.
# Please direct all of these to the Google Code users group:
# http://groups.google.com/group/google-code-hosting
"""Google Code file uploader script.
"""
__author__ = 'danderson@google.com (David Anderson)'
import httplib
import os.path
import optparse
import getpass
import base64
import sys
def upload(file, project_name, user_name, password, summary, labels=None):
"""Upload a file to a Google Code project's file server.
Args:
file: The local path to the file.
project_name: The name of your project on Google Code.
user_name: Your Google account name.
password: The googlecode.com password for your account.
Note that this is NOT your global Google Account password!
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
Returns: a tuple:
http_status: 201 if the upload succeeded, something else if an
error occured.
http_reason: The human-readable string associated with http_status
file_url: If the upload succeeded, the URL of the file on Google
Code, None otherwise.
"""
# The login is the user part of user@gmail.com. If the login provided
# is in the full user@domain form, strip it down.
if user_name.endswith('@gmail.com'):
user_name = user_name[:user_name.index('@gmail.com')]
form_fields = [('summary', summary)]
if labels is not None:
form_fields.extend([('label', l.strip()) for l in labels])
content_type, body = encode_upload_request(form_fields, file)
upload_host = '%s.googlecode.com' % project_name
upload_uri = '/files'
auth_token = base64.b64encode('%s:%s'% (user_name, password))
headers = {
'Authorization': 'Basic %s' % auth_token,
'User-Agent': 'Googlecode.com uploader v0.9.4',
'Content-Type': content_type,
}
server = httplib.HTTPSConnection(upload_host)
server.request('POST', upload_uri, body, headers)
resp = server.getresponse()
server.close()
if resp.status == 201:
location = resp.getheader('Location', None)
else:
location = None
return resp.status, resp.reason, location
def encode_upload_request(fields, file_path):
"""Encode the given fields and file into a multipart form body.
fields is a sequence of (name, value) pairs. file is the path of
the file to upload. The file will be uploaded to Google Code with
the same file name.
Returns: (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla'
CRLF = '\r\n'
body = []
# Add the metadata about the upload first
for key, value in fields:
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="%s"' % key,
'',
value,
])
# Now add the file itself
file_name = os.path.basename(file_path)
f = open(file_path, 'rb')
file_content = f.read()
f.close()
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="filename"; filename="%s"'
% file_name,
# The upload server determines the mime-type, no need to set it.
'Content-Type: application/octet-stream',
'',
file_content,
])
# Finalize the form body
body.extend(['--' + BOUNDARY + '--', ''])
return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
def upload_find_auth(file_path, project_name, summary, labels=None,
user_name=None, password=None, tries=3):
"""Find credentials and upload a file to a Google Code project's file server.
file_path, project_name, summary, and labels are passed as-is to upload.
Args:
file_path: The local path to the file.
project_name: The name of your project on Google Code.
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
config_dir: Path to Subversion configuration directory, 'none', or None.
user_name: Your Google account name.
tries: How many attempts to make.
"""
while tries > 0:
if user_name is None:
# Read username if not specified or loaded from svn config, or on
# subsequent tries.
sys.stdout.write('Please enter your googlecode.com username: ')
sys.stdout.flush()
user_name = sys.stdin.readline().rstrip()
if password is None:
# Read password if not loaded from svn config, or on subsequent tries.
print 'Please enter your googlecode.com password.'
print '** Note that this is NOT your Gmail account password! **'
print 'It is the password you use to access Subversion repositories,'
print 'and can be found here: http://code.google.com/hosting/settings'
password = getpass.getpass()
status, reason, url = upload(file_path, project_name, user_name, password,
summary, labels)
# Returns 403 Forbidden instead of 401 Unauthorized for bad
# credentials as of 2007-07-17.
if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
# Rest for another try.
user_name = password = None
tries = tries - 1
else:
# We're done.
break
return status, reason, url
def main():
parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY '
'-p PROJECT [options] FILE')
parser.add_option('-s', '--summary', dest='summary',
help='Short description of the file')
parser.add_option('-p', '--project', dest='project',
help='Google Code project name')
parser.add_option('-u', '--user', dest='user',
help='Your Google Code username')
parser.add_option('-w', '--password', dest='password',
help='Your Google Code password')
parser.add_option('-l', '--labels', dest='labels',
help='An optional list of comma-separated labels to attach '
'to the file')
options, args = parser.parse_args()
if not options.summary:
parser.error('File summary is missing.')
elif not options.project:
parser.error('Project name is missing.')
elif len(args) < 1:
parser.error('File to upload not provided.')
elif len(args) > 1:
parser.error('Only one file may be specified.')
file_path = args[0]
if options.labels:
labels = options.labels.split(',')
else:
labels = None
status, reason, url = upload_find_auth(file_path, options.project,
options.summary, labels,
options.user, options.password)
if url:
print 'The file was uploaded successfully.'
print 'URL: %s' % url
return 0
else:
print 'An error occurred. Your file was not uploaded.'
print 'Google Code upload server said: %s (%s)' % (reason, status)
return 1
if __name__ == '__main__':
sys.exit(main())
| Python |
#! /usr/bin/python
import glob
import shutil
import sys
import subprocess
import os
if 'linux' in sys.platform:
platform = 'linux'
else:
platform = 'darwin'
toolchain = "%s/android-toolchain" % os.getenv("HOME")
openssl_version = "1.0.0n"
encfs_version = "1.7.5"
def cpfile(src, target):
sys.stdout.write("Copying %s to %s\n" % (src, target))
shutil.copy(src, target)
archs = ["armeabi","armeabi-v7a"]
if encfs_version != "svn":
encfs_dir = "encfs-%s/encfs-%s" % (encfs_version, encfs_version)
else:
encfs_dir = "encfs-svn"
for arch in archs:
try:
os.makedirs("./obj/local/%s" % arch)
except os.error:
pass
target_dir = "./obj/local/%s/" % arch
if encfs_version != "svn":
cpfile("../boost/boost_1_46_1/android/lib/libboost_filesystem.a", target_dir)
cpfile("../boost/boost_1_46_1/android/lib/libboost_serialization.a", target_dir)
cpfile("../boost/boost_1_46_1/android/lib/libboost_system.a", target_dir)
else:
cpfile("../protobuf/protobuf-2.4.1/%s/lib/libprotobuf.a" % arch, target_dir)
cpfile("../tinyxml/tinyxml/%s/libtinyxml.a" % arch, target_dir)
cpfile("../fuse28/obj/local/%s/libfuse.a" % arch, target_dir)
cpfile("../rlog/rlog-1.4/%s/lib/librlog.a" % arch, target_dir)
cpfile("../%s/%s/lib/libencfs.a" % (encfs_dir, arch), target_dir)
cpfile("../openssl/openssl-%s/%s/libssl.a" % (openssl_version, arch), target_dir)
cpfile("../openssl/openssl-%s/%s/libcrypto.a" % (openssl_version, arch), target_dir)
if arch=="armeabi":
arch_subdir = ""
elif arch == "armeabi-v7a":
arch_subdir = "armv7-a/"
cpfile("%s/arm-linux-androideabi/lib/%slibstdc++.a" % (toolchain, arch_subdir), target_dir)
cpfile("%s/lib/gcc/arm-linux-androideabi/4.8/%slibgcc.a" % (toolchain, arch_subdir), target_dir)
arch = "armeabi"
try:
os.makedirs("./assets/%s" % arch)
except os.error:
pass
# Split into 1M chunks for Android <= 2.2:
# truecrypt
p = subprocess.Popen("/usr/bin/split -b 1m truecrypt truecrypt.split",
cwd="../tc/truecrypt-7.1a-source/Main",
shell=True)
p.wait()
splitfiles = glob.glob("../tc/truecrypt-7.1a-source/Main/truecrypt.split*")
print(splitfiles)
for splitfile in splitfiles:
cpfile(splitfile, "./assets/%s/" % arch)
| Python |
#! /usr/bin/python
import glob
import shutil
import sys
import subprocess
import os
def cpfile(src, target):
sys.stdout.write("Copying %s to %s\n" % (src, target))
shutil.copy(src, target)
# We only copy the armeabi version of the binary
archs = ["armeabi"]
for arch in archs:
try:
os.makedirs("../cryptonite/assets/%s" % arch)
except os.error:
pass
# Split into 1M chunks for Android <= 2.2:
# encfs
p = subprocess.Popen("/usr/bin/split -b 1m encfs encfs.split",
cwd="./encfs-1.7.5/%s/bin" % arch,
shell=True)
p.wait()
splitfiles = glob.glob("./encfs-1.7.5/%s/bin/encfs.split*" % arch)
print splitfiles
for splitfile in splitfiles:
cpfile(splitfile, "../cryptonite/assets/%s/" % arch)
# encfsctl
# p = subprocess.Popen("/usr/bin/split -b 1m encfsctl encfsctl.split",
# cwd="./encfs-1.7.5/%s/bin" % arch,
# shell=True)
# p.wait()
# splitfiles = glob.glob("./encfs-1.7.5/%s/bin/encfsctl.split*" % arch)
# print splitfiles
# for splitfile in splitfiles:
# cpfile(splitfile, "../cryptonite/assets/%s/" % arch)
| Python |
#! /usr/bin/python
import glob
import shutil
import sys
import subprocess
import os
def cpfile(src, target):
sys.stdout.write("Copying %s to %s\n" % (src, target))
shutil.copy(src, target)
# We only copy the armeabi version of the binary
archs = ["armeabi"]
for arch in archs:
try:
os.makedirs("../cryptonite/assets/%s" % arch)
except os.error:
pass
# Split into 1M chunks for Android <= 2.2:
# encfs
p = subprocess.Popen("/usr/bin/split -b 1m encfs encfs.split",
cwd="./%s/bin" % arch,
shell=True)
p.wait()
splitfiles = glob.glob("./%s/bin/encfs.split*" % arch)
print splitfiles
for splitfile in splitfiles:
cpfile(splitfile, "../cryptonite/assets/%s/" % arch)
# encfsctl
# p = subprocess.Popen("/usr/bin/split -b 1m encfsctl encfsctl.split",
# cwd="./%s/bin" % arch,
# shell=True)
# p.wait()
# splitfiles = glob.glob("./%s/bin/encfsctl.split*" % arch)
# print splitfiles
# for splitfile in splitfiles:
# cpfile(splitfile, "../cryptonite/assets/%s/" % arch)
| Python |
#! /usr/bin/python
import glob
import shutil
import sys
import subprocess
import os
def cpfile(src, target):
sys.stdout.write("Copying %s to %s\n" % (src, target))
shutil.copy(src, target)
# We only copy the armeabi version of the binary
archs = ["armeabi"]
for arch in archs:
try:
os.makedirs("../cryptonite/assets/%s" % arch)
except os.error:
pass
# Split into 1M chunks for Android <= 2.2:
# encfs
p = subprocess.Popen("/usr/bin/split -b 1m encfs encfs.split",
cwd="./encfs-1.7.4/%s/bin" % arch,
shell=True)
p.wait()
splitfiles = glob.glob("./encfs-1.7.4/%s/bin/encfs.split*" % arch)
print splitfiles
for splitfile in splitfiles:
cpfile(splitfile, "../cryptonite/assets/%s/" % arch)
# encfsctl
# p = subprocess.Popen("/usr/bin/split -b 1m encfsctl encfsctl.split",
# cwd="./encfs-1.7.4/%s/bin" % arch,
# shell=True)
# p.wait()
# splitfiles = glob.glob("./encfs-1.7.4/%s/bin/encfsctl.split*" % arch)
# print splitfiles
# for splitfile in splitfiles:
# cpfile(splitfile, "../cryptonite/assets/%s/" % arch)
| Python |
import string
#headingDict = {}
class ircstuff:
pass
#1 ,2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13
#type, lots, currency , dateopen , dateclose , open , close ,high , low , pips , Dollar, pipstotal ,dollarTotal
headingDict = {
1 : '''{|cellspacing="0" border="1" style="background:#eeeeee;" class="pair_2"''',
2 : "!Nr.",
3 : "!Type",
4 : "!Lots",
5 : "!Ticker",
6 : "!DateOpen",
7 : "!DateClosed",
8 : "!Open",
9 : "!Close",
10 : "!High",
11 : "!Pip drawdown nominal",
12 : "!Nominal movement",
13 : "!Dollar",
14 : "!PipsTotal",
15 : "!DollarTotal" ,
16 : "|-"
}
class WikiaHeader:
def __init__(self, irclibobj):
self.tickerDict = {}
def GenerateHeader(self):
file = open("wikia.txt",'w')
tradenr = headingDict.items()
#hosts.sort()
for iter,count in tradenr:
x = headingDict[iter]
x = x + '\r\n'
file.write(x)
# templist = self.tickerDict[iter]
#print templist
# print host, ":", count
file.close()
def formatZulu_File(self):
tempstring = ''
try:
file = open("zulutemp.txt")
filewrite = open("zuluformat.txt",'w')
except:
print ("file not opening")
sys.exit(1)
for x in range(50000000):
line = file.readline()
if line:
pass
else:
file.close()
filewrite.close()
break
if line:
temp = string.strip(line)
if temp == '': #if empty line not yet read, still busy with same dataset.
for x in range(13):
line = file.readline() # will be buy or sell
line = string.strip(line)
tempstring = tempstring + line + ','
tempstring = tempstring[:-1]
tempstring = tempstring + "\n"
# tempstring = tempstring + "\r\n" #CHANGED THIS LINE
if "Pips" in tempstring:
filewrite.write(tempstring)
tempstring = ''
else:
file.close()
filewrite.close()
break
def thefileread(self):
try:
file = open("zuluformat.txt")
except:
print ("file not opening")
sys.exit(1)
for x in range(5000000):
# while 1:
line = file.readline()
if line:
mytemp = string.split(line,",")
temp = mytemp[0]
self.tickerDict[x] = mytemp
else:
break
| Python |
#! /usr/bin/env python
import string
import sys
import math
from zuluDicts import*
'''Provider
Type
Sand Lots
Currency
Date Open
Date Closed
Open
Close
High
Low
Pips/$
Total'''
class Zuluread(WikiaHeader):
def __init__(self):
self.tickerDict = {}
self.wikialist = []
self.templist = []
self.formatZulu_File() #get into comma list
self.thefileread() # read into tickerDict
self.Wikiaformat2() #LIST wikialist has correct wikia code
self.winners = 0
#self.templist = []
def printstuff(self):
hosts = self.tickerDict.items()
#hosts.sort()
for host,count in hosts:
print host, ":", count
def formattingStringForWikia(self,item,color):
#brackets the - sign because it means line break in
#in wikia tables
greenColor = '''|style="background:#88ee22;"'''
redColor = '''|style="background:#f0ee22;"'''
if color == "green":
item = string.strip(item)
item = greenColor + "|" + item + "\n"
# self.winners = self.winners + 1
# print self.winners
return item
if color == "red":
item = string.strip(item)
item = redColor + "|" + item + "\n"
return item
# item = "|" + item + "\n"
# |style="background:#88ee22;"| data
###############################################################
if "-" in item:
item = string.strip(item)
item = "|" + "(" + item + ")"+ "\n"
else:
item = "|" + item + "\n"
return item
def ScaleList_for_correct_pips(self):
print "aldfjl"
#BUY,0.5,EUR/USD,2010/01/14 16:11:37,2010/01/14 16:12:55,1.44540,1.44590,25,0,25 Pips,$18.80,342 Pips,$123.00
def Wikiaformat2(self):
########################
file = open("wikia.txt",'w')
headerGeneration = headingDict.items()
for iter,count in headerGeneration:
x = headingDict[iter]
x = x + "\n"
file.write(x)
file.write("\n")
#######################
trades = self.tickerDict.items()
for iter,count in trades:
# print self.tickerDict[tradenr]
self.templist = self.tickerDict[iter]
self.ScaleList_for_correct_pips()
print (self.templist)
###################
#self.printcall()
temp1 = ''
temp1 = "!" + str(iter) + "\n"
file.write(temp1)
for x in range(len(self.templist)):
temp1 = ''
item = self.templist[x]
self.wikialist.append(temp1)
if x == 0: #BUY OR SELL
color =''
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 1: #LOTS
color = ''
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 2: #TICKER
color = ''
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 3: #opendate
color = ''
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 4: #closedate
color = ''
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 5: #open
color = ''
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 6: #close
color = ''
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 7: #High in pips
color = ''
item = "|" + item + "\n"
file.write(item)
self.wikialist.append(item)
if x == 8: #Low in pips
#SCALE FOR CORRECT NUMERICAL VALUE
color = ''
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 9: #pips per lot
#SCALE PIPS TO GET CORRECT NUMERICAL RISE
color = ''
if "-" in item:
color = "red"
else:
color = "green"
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 10: #Dollar
color = ''
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 11: #pipstotal
color = ''
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 12: #dollarTotal
color = ''
item = self.formattingStringForWikia(item,color) #already has linefeed
file.write(item)
self.wikialist.append(item)
temp1 = "|-" + "\n"
file.write(temp1)
self.wikialist.append(temp1)
file.write(" " + "\n")
temp1 = " " + "\n"
self.wikialist.append(temp1)
#############################################
# print templist
temp1 = ''
for x in range(len(self.wikialist)):
temp1 = self.wikialist[x]
# file.write(temp1)
file.close()
#####################################################################################
#####################################################################################
#####################################################################################
class ZuluPipsScale(Zuluread):
def __init__(self):
self.tickerDict = {}
self.wikialist = []
self.templist = []
self.formatZulu_File() #get into comma list
self.thefileread() # read into tickerDict
self.Wikiaformat2() #LIST wikialist has correct wikia code
#self.templist = []
self.winners = 0
def scaleZulu_Pips_to_get_correct_Nominal_movement(self):
lots = self.templist[1]
bulkpips = self.templist[9]
bulkpips = string.split(bulkpips)
# print bulkpips
bulkpips = float(bulkpips[0])
minilots = 10 * float(lots)
numericalPip = bulkpips/minilots
# item = "%.2f" % numericalPip
item = int(numericalPip)
item = str(item)
return(item)
def scaleZulu_Pips_Nominal_movement_LOW(self):
lots = self.templist[1]
bulkpips = self.templist[8]
bulkpips = string.split(bulkpips)
# print bulkpips
bulkpips = float(bulkpips[0])
minilots = 10 * float(lots)
numericalPip = bulkpips/minilots
# item = "%.2f" % numericalPip
item = int(numericalPip)
item = str(item)
return(item)
def scaleZulu_Pips_Nominal_movement_HIGH(self):
lots = self.templist[1]
bulkpips = self.templist[7]
bulkpips = string.split(bulkpips)
# print bulkpips
bulkpips = float(bulkpips[0])
minilots = 10 * float(lots)
numericalPip = bulkpips/minilots
# item = "%.2f" % numericalPip
item = int(numericalPip)
item = str(item)
return(item)
def Wikiaformat2(self):
########################
file = open("wikia.txt",'w')
headerGeneration = headingDict.items()
for iter,count in headerGeneration:
x = headingDict[iter]
x = x + "\n"
file.write(x)
file.write("\n")
#######################
trades = self.tickerDict.items()
for iter,count in trades:
# print self.tickerDict[tradenr]
self.templist = self.tickerDict[iter]
# self.ScaleList_for_correct_pips() notimplemented
if "Pips" in (self.templist[9]):
pass
else:
break
###################
#self.printcall()
temp1 = ''
temp1 = "!" + str(iter) + "\n"
file.write(temp1)
for x in range(len(self.templist)):
temp1 = ''
item = self.templist[x]
self.wikialist.append(temp1)
temp = self.wikialist
if x == 0: #BUY OR SELL
color = ''
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 1: #LOTS
color = ''
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 2: #TICKER
color = ''
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 3: #opendate
color = ''
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 4: #closedate
color = ''
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 5: #open
color = ''
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 6: #close
color = ''
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 7: #High in pips
color = ''
item = self.scaleZulu_Pips_Nominal_movement_HIGH()
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 8: #Low in pips
#SCALE FOR CORRECT NUMERICAL VALUE
color = ''
item = self.scaleZulu_Pips_Nominal_movement_LOW()
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 9: #pips per lot
###########################################################
#SCALE PIPS TO GET CORRECT NUMERICAL NOMINAL MOVEMENT(x==1)
color = ''
item = self.scaleZulu_Pips_to_get_correct_Nominal_movement()
if "-" in item:
color = "red"
else:
color = "green"
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
###########################################################
if x == 10: #Dollar
color = ''
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 11: #pipstotal
color = ''
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 12: #dollarTotal
color = ''
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
temp1 = "|-" + "\n"
file.write(temp1)
self.wikialist.append(temp1)
file.write(" " + "\n")
temp1 = " " + "\n"
self.wikialist.append(temp1)
#############################################
# print templist
temp1 = ''
for x in range(len(self.wikialist)):
temp1 = self.wikialist[x]
# file.write(temp1)
file.close()
#####################################################################################
#####################################################################################
#####################################################################################
class ZuluPipsScale_and_timeHELD(ZuluPipsScale):
def __init__(self):
self.tickerDict = {}
self.wikialist = []
self.templist = []
self.formatZulu_File() #get into comma list
self.thefileread() # read into tickerDict
self.Wikiaformat2() #LIST wikialist has correct wikia code
#self.templist = []
self.winners = 0
def Wikiaformat2(self):
########################
file = open("wikia.txt",'w')
headerGeneration = headingDict.items()
for iter,count in headerGeneration:
x = headingDict[iter]
x = x + "\n"
file.write(x)
file.write("\n")
#######################
trades = self.tickerDict.items()
for iter,count in trades:
# print self.tickerDict[tradenr]
self.templist = self.tickerDict[iter]
# self.ScaleList_for_correct_pips() notimplemented
if "Pips" in (self.templist[9]):
pass
else:
break
###################
#self.printcall()
temp1 = ''
temp1 = "!" + str(iter) + "\n"
file.write(temp1)
for x in range(len(self.templist)):
temp1 = ''
item = self.templist[x]
self.wikialist.append(temp1)
temp = self.wikialist
if x == 0: #BUY OR SELL
color = ''
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 1: #LOTS
color = ''
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 2: #TICKER
color = ''
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 3: #opendate
color = ''
item = '#'
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 4: #closedate
color = ''
item = '#' #blank out open
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 5: #open
color = ''
item = '#' #blank out open
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 6: #close
color = ''
item = '#'
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 7: #High in pips
color = ''
item = self.scaleZulu_Pips_Nominal_movement_HIGH()
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 8: #Low in pips
#SCALE FOR CORRECT NUMERICAL VALUE
color = ''
item = self.scaleZulu_Pips_Nominal_movement_LOW()
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 9: #pips per lot
###########################################################
#SCALE PIPS TO GET CORRECT NUMERICAL NOMINAL MOVEMENT(x==1)
color = ''
item = self.scaleZulu_Pips_to_get_correct_Nominal_movement()
if "-" in item:
color = "red"
else:
color = "green"
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
###########################################################
if x == 10: #Dollar
color = ''
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 11: #pipstotal
color = ''
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
if x == 12: #dollarTotal
color = ''
item = self.formattingStringForWikia(item,color)
file.write(item)
self.wikialist.append(item)
temp1 = "|-" + "\n"
file.write(temp1)
self.wikialist.append(temp1)
file.write(" " + "\n")
temp1 = " " + "\n"
self.wikialist.append(temp1)
#############################################
# print templist
temp1 = ''
for x in range(len(self.wikialist)):
temp1 = self.wikialist[x]
# file.write(temp1)
file.close()
def main():
channel = "#forextiming"
nickname = "zimba23"
server = "irc.freenode.net"
port = 6667
# bot = Zuluread()
bot = ZuluPipsScale()
# bot = ZuluPipsScale_and_timeHELD()
# bot.printstuff()
# bot.GenerateHeader() #Generate wikia code
if __name__ == "__main__":
main()
| Python |
import hashlib
import hmac
import struct
from util.tlv import loopTLVBlocks, tlvToDict
from crypto.aeswrap import AESUnwrap
from pprint import pprint
from crypto.PBKDF2 import PBKDF2
from util.bplist import BPlistReader
from crypto.aes import AESdecryptCBC
from crypto.curve25519 import curve25519
from hashlib import sha256
KEYBAG_TAGS = ["VERS", "TYPE", "UUID", "HMCK", "WRAP", "SALT", "ITER", "PBKY"]
CLASSKEY_TAGS = ["CLAS","WRAP","WPKY", "KTYP"] #UUID
KEYBAG_TYPES = ["System", "Backup", "Escrow"]
SYSTEM_KEYBAG = 0
BACKUP_KEYBAG = 1
ESCROW_KEYBAG = 2
WRAP_DEVICE = 1
WRAP_PASSCODE = 2
"""
device key : key 0x835
"""
class Keybag(object):
def __init__(self, data):
self.type = None
self.uuid = None
self.wrap = None
self.deviceKey = None
self.unlocked = False
self.attrs = {}
self.classKeys = {}
self.parseBinaryBlob(data)
@staticmethod
def getSystemkbfileWipeID(filename):
mkb = BPlistReader.plistWithFile(filename)
return mkb["_MKBWIPEID"]
@staticmethod
def createWithPlist(pldict):
k835 = pldict.key835.decode("hex")
data = ""
if pldict.has_key("KeyBagKeys"):
data = pldict["KeyBagKeys"].data
keystore = Keybag.createWithDataSignBlob(data, k835)
if pldict.has_key("passcodeKey"):
if keystore.unlockWithPasscodeKey(pldict["passcodeKey"].decode("hex")):
print "Keybag unlocked with passcode key"
else:
print "FAILed to unlock keybag with passcode key"
#HAX: inject DKey
keystore.classKeys[4] = {"KEY": pldict["DKey"].decode("hex")}
return keystore
@staticmethod
def createWithSystemkbfile(filename, wipeablekey, deviceKey=None):
mkb = BPlistReader.plistWithFile(filename)
decryptedPlist = AESdecryptCBC(mkb["_MKBPAYLOAD"], wipeablekey, mkb["_MKBIV"], padding=True)
decryptedPlist = BPlistReader.plistWithString(decryptedPlist)
blob = decryptedPlist["KeyBagKeys"]
return Keybag.createWithDataSignBlob(blob, deviceKey)
@staticmethod
def createWithDataSignBlob(blob, deviceKey=None):
keybag = tlvToDict(blob)
kb = Keybag(keybag["DATA"])
kb.deviceKey = deviceKey
if len(keybag.get("SIGN", "")):
hmackey = AESUnwrap(deviceKey, kb.attrs["HMCK"])
#hmac key and data are swapped (on purpose or by mistake ?)
sigcheck = hmac.new(keybag["DATA"], hmackey, hashlib.sha1).digest()
if sigcheck == keybag.get("SIGN", ""):
print "Keybag: SIGN check OK"
else:
print "Keybag: SIGN check FAIL"
return kb
def parseBinaryBlob(self, data):
currentClassKey = None
for tag, data in loopTLVBlocks(data):
if len(data) == 4:
data = struct.unpack(">L", data)[0]
if tag == "TYPE":
self.type = data
if self.type > 2:
print "FAIL: keybag type > 2"
elif tag == "UUID" and self.uuid is None:
self.uuid = data
elif tag == "WRAP" and self.wrap is None:
self.wrap = data
elif tag == "UUID":
if currentClassKey:
self.classKeys[currentClassKey["CLAS"]] = currentClassKey
currentClassKey = {"UUID": data}
elif tag in CLASSKEY_TAGS:
currentClassKey[tag] = data
else:
self.attrs[tag] = data
if currentClassKey:
self.classKeys[currentClassKey["CLAS"]] = currentClassKey
def getPasscodekeyFromPasscode(self, passcode):
if self.type == BACKUP_KEYBAG:
return PBKDF2(passcode, self.attrs["SALT"], iterations=self.attrs["ITER"]).read(32)
else:
#Warning, need to run derivation on device with this result
return PBKDF2(passcode, self.attrs["SALT"], iterations=1).read(32)
def unlockBackupKeybagWithPasscode(self, passcode):
if self.type != BACKUP_KEYBAG:
print "unlockBackupKeybagWithPasscode: not a backup keybag"
return False
return self.unlockWithPasscodeKey(self.getPasscodekeyFromPasscode(passcode))
def unlockWithPasscodeKey(self, passcodekey):
if self.type != BACKUP_KEYBAG:
if not self.deviceKey:
print "ERROR, need device key to unlock keybag"
return False
for classkey in self.classKeys.values():
k = classkey["WPKY"]
if classkey["WRAP"] & WRAP_PASSCODE:
k = AESUnwrap(passcodekey, classkey["WPKY"])
if not k:
return False
if classkey["WRAP"] & WRAP_DEVICE:
if not self.deviceKey:
continue
k = AESdecryptCBC(k, self.deviceKey)
classkey["KEY"] = k
self.unlocked = True
return True
def unwrapCurve25519(self, persistent_class, persistent_key):
assert len(persistent_key) == 0x48
assert persistent_class == 2 #NSFileProtectionCompleteUnlessOpen
mysecret = self.classKeys[persistent_class]["KEY"]
mypublic = self.attrs["PBKY"]
hispublic = persistent_key[:32]
shared = curve25519(mysecret, hispublic)
md = sha256('\x00\x00\x00\x01' + shared + hispublic + mypublic).digest()
return AESUnwrap(md, persistent_key[32:])
def unwrapKeyForClass(self, clas, persistent_key):
if not self.classKeys.has_key(clas) or not self.classKeys[clas].has_key("KEY"):
print "Keybag key %d missing or locked" % clas
return ""
ck = self.classKeys[clas]["KEY"]
if self.attrs["VERS"] >= 3 and clas == 2:
return self.unwrapCurve25519(clas, persistent_key)
if len(persistent_key) == 0x28:
return AESUnwrap(ck, persistent_key)
return
def printClassKeys(self):
print "Keybag type : %s keybag (%d)" % (KEYBAG_TYPES[self.type], self.type)
print "Keybag version : %d" % self.attrs["VERS"]
print "Class\tWRAP\tType\tKey"
for k, ck in self.classKeys.items():
print "%s\t%s\t%s\t%s" % (k, ck.get("WRAP"), ck.get("KTYP",""), ck.get("KEY","").encode("hex"))
print ""
def getClearClassKeysDict(self):
if self.unlocked:
d = {}
for ck in self.classKeys.values():
d["%d" % ck["CLAS"]] = ck.get("KEY","").encode("hex")
return d
| Python |
#HAX
d=open("redsn0w_win_0.9.9b4/redsn0w.exe", "rb").read()
i = d.find("<key>IV</key>")
i = d.rfind("<?xml",0,i)
j = d.find("</plist>", i)
assert i != -1
assert j != -1
open("Keys.plist", "wb").write(d[i:j+8])
| Python |
"""
0
1:MCSHA256DigestWithSalt
2:SecKeyFromPassphraseDataHMACSHA1
"""
from crypto.PBKDF2 import PBKDF2
import plistlib
import hashlib
SALT1 = "F92F024CA2CB9754".decode("hex")
hashMethods={
1: (lambda p,salt:hashlib.sha256(SALT1 + p)),
2: (lambda p,salt:PBKDF2(p, salt, iterations=1000).read(20))
}
def bruteforce_old_pass(h):
salt = h["salt"].data
hash = h["hash"].data
f = hashMethods.get(h["hashMethod"])
if f:
print "Bruteforcing hash %s (4 digits)" % hash.encode("hex")
for i in xrange(10000):
p = "%04d" % (i % 10000)
if f(p,salt) == hash:
return p
| Python |
from keychain import Keychain
from crypto.aes import AESdecryptCBC
import hashlib
from Crypto.Cipher import AES
class Keychain3(Keychain):
def __init__(self, filename, key835=None):
Keychain.__init__(self, filename)
self.key835 = key835
def decrypt_data(self, data):
if data == None:
return ""
data = str(data)
if not self.key835:
print "Key 835 not availaible"
return ""
data = AESdecryptCBC(data[16:], self.key835, data[:16], padding=True)
#data_column = iv + AES128_K835(iv, data + sha1(data))
if hashlib.sha1(data[:-20]).digest() != data[-20:]:
print "data field hash mismatch : bad key ?"
return "ERROR decrypting data : bad key ?"
return data[:-20]
def change_key835(self, newkey):
tables = {"genp": "SELECT rowid, data FROM genp",
"inet": "SELECT rowid, data FROM inet",
"cert": "SELECT rowid, data FROM cert",
"keys": "SELECT rowid, data FROM keys"}
for t in tables.keys():
for row in self.conn.execute(tables[t]):
rowid = row["rowid"]
data = str(row["data"])
iv = data[:16]
data = AES.new(self.key835, AES.MODE_CBC, iv).decrypt(data[16:])
data = AES.new(newkey, AES.MODE_CBC, iv).encrypt(data)
data = iv + data
data = buffer(data)
self.conn.execute("UPDATE %s SET data=? WHERE rowid=?" % t, (data, rowid))
self.conn.commit() | Python |
from crypto.aes import AESdecryptCBC
import struct
import sqlite3
import M2Crypto
from util import write_file
from util.bplist import BPlistReader
import plistlib
import hashlib
import string
from util.cert import RSA_KEY_DER_to_PEM
printset = set(string.printable)
def render_password(p):
data = p["data"]
if data != None and data.startswith("bplist") and data.find("\x00") != -1:
pl = BPlistReader.plistWithString(p["data"])
filename = "%s_%s_%d.plist" % (p["svce"],p["acct"],p["rowid"])
plistlib.writePlist(pl, filename)
#write_file("bin_"+filename, p["data"])
data = filename
if p.has_key("srvr"):
return "%s:%d;%s;%s" % (p["srvr"],p["port"],p["acct"],data)
else:
return "%s;%s;%s" % (p["svce"],p["acct"],data)
class Keychain:
def __init__(self, filename):
self.conn = sqlite3.connect(filename)
self.conn.row_factory = sqlite3.Row
self.bsanitize = True
def decrypt_data(self, data):
return data #override this method
def decrypt_item(self, row):
res = {}
for k in row.keys():
if type(row[k]) == buffer:
res[k] = str(row[k])
else:
res[k] = row[k]
res["data"] = self.decrypt_data(row["data"])
return res
def get_passwords(self):
return map(self.decrypt_item, self.conn.execute("SELECT rowid, data, svce, acct, agrp FROM genp"))
def get_inet_passwords(self):
return map(self.decrypt_item, self.conn.execute("SELECT rowid, data, acct, srvr, port, agrp FROM inet"))
def get_certs(self):
certs = {}
pkeys = {}
for row in self.conn.execute("SELECT cert.data, keys.data, cert.agrp FROM cert LEFT OUTER JOIN keys ON keys.klbl=cert.pkhh AND keys.agrp=cert.agrp"):
cert_der = self.decrypt_data(row[0])
#conn.execute("UPDATE cert SET data= WHERE rowid")
cert = M2Crypto.X509.load_cert_der_string(cert_der)
subject = cert.get_subject().as_text()
subject = str(cert.get_subject().get_entries_by_nid(M2Crypto.X509.X509_Name.nid['CN'])[0].get_data())
certs[subject+ "_%s" % row[2]] = cert
if row[1]:
pkey_der = self.decrypt_data(row[1])
pkey_der = RSA_KEY_DER_to_PEM(pkey_der)
pkeys[subject + "_%s" % row[2]] = pkey_der
return certs, pkeys
def save_passwords(self):
passwords = "\n".join(map(render_password, self.get_passwords()))
inetpasswords = "\n".join(map(render_password, self.get_inet_passwords()))
print "Writing passwords to keychain.csv"
write_file("keychain.csv", "Passwords;;\n"+passwords+"\nInternet passwords;;\n"+ inetpasswords)
def save_certs_keys(self):
certs, pkeys = self.get_certs()
for c in certs:
filename = (c)
certs[c].save_pem(filename + ".crt")
for k in pkeys:
filename = (k)
write_file(filename + ".key", pkeys[k])
def sanitize(self, pw):
if pw.startswith("bplist"):
return "<binary plist data>"
elif not set(pw).issubset(printset):
pw = "<binary data> : " + pw.encode("hex")
if self.bsanitize:
return pw[:2] + ("*" * (len(pw) - 2))
return pw
def print_all(self, sanitize=True):
self.bsanitize = sanitize
print "-"*60
print " " * 20 + "Passwords"
print "-"*60
for p in self.get_passwords():
print "Service :\t" + p["svce"]
print "Account :\t" + p["acct"]
print "Password :\t" + self.sanitize(p["data"])
print "Agrp :\t" + p["agrp"]
print "-"*60
for p in self.get_inet_passwords():
print "Server : \t" + p["srvr"] + ":" + str(p["port"])
print "Account : \t" + p["acct"]
print "Password : \t" + self.sanitize(p["data"])
print "-"*60
certs, pkeys = self.get_certs()
print " " * 20 + "Certificates"
print "-"*60
for c in sorted(certs.keys()):
print c
print "-"*60
print " " * 20 + "Private keys"
for k in sorted(pkeys.keys()):
print k
print "-"*60
def get_push_token(self):
for row in self.conn.execute("SELECT data FROM genp WHERE svce='push.apple.com'"):
return self.decrypt_data(row["data"])
def get_managed_configuration(self):
for row in self.conn.execute("SELECT data FROM genp WHERE acct='Private' AND svce='com.apple.managedconfiguration' AND agrp='apple'"):
return BPlistReader.plistWithString(self.decrypt_data(row["data"]))
#HAX iOS 5
h1 = sqlite3.Binary(hashlib.sha1("Private").digest())
h2 = sqlite3.Binary(hashlib.sha1("com.apple.managedconfiguration").digest())
for row in self.conn.execute("SELECT data FROM genp WHERE acct=? AND svce=? AND agrp='apple'", (h1, h2)):
return BPlistReader.plistWithString(self.decrypt_data(row["data"])) | Python |
from crypto.aes import AESdecryptCBC
import struct
"""
iOS 4 keychain-2.db data column format
version 0x00000000
key class 0x00000008
kSecAttrAccessibleWhenUnlocked 6
kSecAttrAccessibleAfterFirstUnlock 7
kSecAttrAccessibleAlways 8
kSecAttrAccessibleWhenUnlockedThisDeviceOnly 9
kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly 10
kSecAttrAccessibleAlwaysThisDeviceOnly 11
wrapped AES256 key 0x28 bytes (passed to kAppleKeyStoreKeyUnwrap)
encrypted data (AES 256 CBC zero IV)
"""
from keychain import Keychain
from crypto.gcm import gcm_decrypt
from util.bplist import BPlistReader
KSECATTRACCESSIBLE = {
6: "kSecAttrAccessibleWhenUnlocked",
7: "kSecAttrAccessibleAfterFirstUnlock",
8: "kSecAttrAccessibleAlways",
9: "kSecAttrAccessibleWhenUnlockedThisDeviceOnly",
10: "kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly",
11: "kSecAttrAccessibleAlwaysThisDeviceOnly"
}
class Keychain4(Keychain):
def __init__(self, filename, keybag):
if not keybag.unlocked:
raise Exception("Keychain4 object created with locked keybag")
Keychain.__init__(self, filename)
self.keybag = keybag
def decrypt_item(self, row):
version, clas = struct.unpack("<LL", row["data"][0:8])
if version >= 2:
dict = self.decrypt_blob(row["data"])
dict["data"] = dict["v_Data"].data
dict["rowid"] = row["rowid"]
return dict
return Keychain.decrypt_item(self, row)
def decrypt_data(self, data):
data = self.decrypt_blob(data)
if type(data) == dict:
return data["v_Data"].data
return data
def decrypt_blob(self, blob):
if blob == None:
return ""
if len(blob) < 48:
print "keychain blob length must be >= 48"
return
version, clas = struct.unpack("<LL",blob[0:8])
if version == 0:
wrappedkey = blob[8:8+40]
encrypted_data = blob[48:]
elif version == 2:
wrappedkey = blob[12:12+40]
encrypted_data = blob[52:-16]
else:
raise Exception("unknown keychain verson ", version)
return
unwrappedkey = self.keybag.unwrapKeyForClass(clas, wrappedkey)
if not unwrappedkey:
print "keychain unwrap fail for item with class=%d (%s)" % (clas, KSECATTRACCESSIBLE.get(clas))
return
if version == 0:
return AESdecryptCBC(encrypted_data, unwrappedkey, padding=True)
elif version == 2:
binaryplist = gcm_decrypt(unwrappedkey, "", encrypted_data, "", blob[-16:])
return BPlistReader(binaryplist).parse()
| Python |
import sqlite3
from keychain3 import Keychain3
from keychain4 import Keychain4
def keychain_load(filename, keybag, key835):
version = sqlite3.connect(filename).execute("SELECT version FROM tversion").fetchone()[0]
print "Keychain version : %d" % version
if version == 3:
return Keychain3(filename, key835)
elif version >= 4:
return Keychain4(filename, keybag)
raise Exception("Unknown keychain version %d" % version)
| Python |
from keychain4 import Keychain4
from util.bplist import BPlistReader
class KeychainBackup4(Keychain4):
def __init__(self, filename, keybag):
self.keychain = BPlistReader.plistWithFile(filename)
self.keybag = keybag
def get_passwords(self):
res = []
genps = self.keychain['genp']
for genp in genps:
password = {}
password['svce'] = genp['svce']
password['acct'] = genp['acct']
password['agrp'] = genp['agrp']
password['data'] = self.decrypt_data(genp['v_Data'].data)
res.append(password)
return res
def get_inet_passwords(self):
res = []
inets = self.keychain['inet']
for inet in inets:
password = {}
password['acct'] = inet['acct']
password['srvr'] = inet['srvr']
password['port'] = inet['port']
password['data'] = self.decrypt_data(inet['v_Data'].data)
password['agrp'] = inet['agrp']
res.append(password)
return res
| Python |
#!/usr/bin/python
import plistlib
import zipfile
import struct
import sys
from Crypto.Cipher import AES
from util.lzss import decompress_lzss
devices = {"n88ap": "iPhone2,1",
"n90ap": "iPhone3,1",
"n92ap": "iPhone3,3",
"n18ap": "iPod3,1",
"n81ap": "iPod4,1",
"k48ap": "iPad1,1"
}
h=lambda x:x.replace(" ","").decode("hex")
#https://github.com/comex/datautils0/blob/master/make_kernel_patchfile.c
patchs_ios5 = {
"CSED" : (h("df f8 88 33 1d ee 90 0f a2 6a 1b 68"), h("df f8 88 33 1d ee 90 0f a2 6a 01 23")),
"AMFI" : (h("D0 47 01 21 40 B1 13 35"), h("00 20 01 21 40 B1 13 35")),
"_PE_i_can_has_debugger" : (h("38 B1 05 49 09 68 00 29"), h("01 20 70 47 09 68 00 29")),
"IOAESAccelerator enable UID" : (h("67 D0 40 F6"), h("00 20 40 F6")),
#not stritcly required, usefull for testing
"getxattr system": ("com.apple.system.\x00", "com.apple.aaaaaa.\x00"),
}
#grab keys from redsn0w Keys.plist
class IPSWkeys(object):
def __init__(self, manifest):
self.keys = {}
buildi = manifest["BuildIdentities"][0]
dc = buildi["Info"]["DeviceClass"]
build = "%s_%s_%s" % (devices.get(dc,dc), manifest["ProductVersion"], manifest["ProductBuildVersion"])
try:
rs = plistlib.readPlist("Keys.plist")
except:
raise Exception("Get Keys.plist from redsn0w and place it in the current directory")
for k in rs["Keys"]:
if k["Build"] == build:
self.keys = k
break
def getKeyIV(self, filename):
if not self.keys.has_key(filename):
return None, None
k = self.keys[filename]
return k["Key"], k["IV"]
def decryptImg3(blob, key, iv):
assert blob[:4] == "3gmI", "Img3 magic tag"
data = ""
for i in xrange(20, len(blob)):
tag = blob[i:i+4]
size, real_size = struct.unpack("<LL", blob[i+4:i+12])
if tag[::-1] == "DATA":
assert size >= real_size, "Img3 length check"
data = blob[i+12:i+size]
break
i += size
return AES.new(key, AES.MODE_CBC, iv).decrypt(data)[:real_size]
def main(ipswname):
ipsw = zipfile.ZipFile(ipswname)
manifest = plistlib.readPlistFromString(ipsw.read("BuildManifest.plist"))
kernelname = manifest["BuildIdentities"][0]["Manifest"]["KernelCache"]["Info"]["Path"]
kernel = ipsw.read(kernelname)
keys = IPSWkeys(manifest)
key,iv = keys.getKeyIV(kernelname)
if key == None:
print "No keys found for kernel"
return
print "Decrypting %s" % kernelname
kernel = decryptImg3(kernel, key.decode("hex"), iv.decode("hex"))
assert kernel.startswith("complzss"), "Decrypted kernelcache does not start with \"complzss\" => bad key/iv ?"
print "Unpacking ..."
kernel = decompress_lzss(kernel)
assert kernel.startswith("\xCE\xFA\xED\xFE"), "Decompressed kernelcache does not start with 0xFEEDFACE"
for p in patchs_ios5:
print "Doing %s patch" % p
s, r = patchs_ios5[p]
c = kernel.count(s)
if c != 1:
print "=> FAIL, count=%d, do not boot that kernel it wont work" % c
else:
kernel = kernel.replace(s,r)
outkernel = "%s.patched" % kernelname
open(outkernel, "wb").write(kernel)
print "Patched kernel written to %s" % outkernel
ramdiskname = manifest["BuildIdentities"][0]["Manifest"]["RestoreRamDisk"]["Info"]["Path"]
key,iv = keys.getKeyIV("Ramdisk")
build_cmd = "./build_ramdisk.sh %s %s %s %s" % (ipswname, ramdiskname, key, iv)
rs_cmd = "redsn0w -i %s -r myramdisk.dmg -k %s" % (ipswname, outkernel)
rdisk_script="""#!/bin/sh
for VER in 4.2 4.3 5.0
do
if [ -f "/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS$VER.sdk/System/Library/Frameworks/IOKit.framework/IOKit" ];
then
SDKVER=$VER
echo "Found iOS SDK $SDKVER"
break
fi
done
if [ "$SDKVER" == "" ]; then
echo "iOS SDK not found"
exit
fi
SDKVER=$SDKVER make -C ramdisk_tools
%s
echo "You can boot the ramdisk using the following command (fix paths)"
echo "%s"
""" % (build_cmd, rs_cmd)
devclass = manifest["BuildIdentities"][0]["Info"]["DeviceClass"]
scriptname="make_ramdisk_%s.sh" % devclass
f=open(scriptname, "wb")
f.write(rdisk_script)
f.close()
print "Created script %s, you can use it to (re)build the ramdisk"% scriptname
if __name__ == "__main__":
if len(sys.argv) < 2:
print "Usage: %s IPSW" % __file__
sys.exit(-1)
main(sys.argv[1])
| Python |
#!/usr/bin/env python
import os
import sys
from struct import pack, unpack
from Crypto.Cipher import AES
from crypto.aeswrap import AESUnwrap
from util.bplist import BPlistReader
from keystore.keybag import Keybag
from pprint import pprint
MBDB_SIGNATURE = 'mbdb\x05\x00'
MBDX_SIGNATURE = 'mbdx\x02\x00'
MASK_SYMBOLIC_LINK = 0xa000
MASK_REGULAR_FILE = 0x8000
MASK_DIRECTORY = 0x4000
class MBFileRecord(object):
def __init__(self, mbdb):
self.domain = self._decode_string(mbdb)
if self.domain is None:
warn("Domain name missing from record")
self.path = self._decode_string(mbdb)
if self.path is None:
warn("Relative path missing from record")
self.target= self._decode_string(mbdb) # for symbolic links
self.digest = self._decode_string(mbdb)
self.encryption_key = self._decode_data(mbdb)
data = mbdb.read(40) # metadata, fixed size
self.mode, = unpack('>H', data[0:2])
if not(self.is_regular_file() or self.is_symbolic_link() or self.is_directory()):
warn("File type mising from record mode")
if self.is_symbolic_link() and self.target is None:
warn("Target required for symblolic links")
self.inode_number = unpack('>Q', data[2:10])
self.user_id, = unpack('>I', data[10:14])
self.group_id = unpack('>I', data[14:18])
self.last_modification_time, = unpack('>i', data[18:22])
self.last_status_change_time, = unpack('>i', data[22:26])
self.birth_time, = unpack('>i', data[26:30])
self.size, = unpack('>q', data[30:38])
if self.size != 0 and not self.is_regular_file():
warn("Non-zero size for a record which is not a regular file")
self.protection_class = ord(data[38])
num_attributes = ord(data[39])
if num_attributes == 0:
self.extended_attributes = None
else:
self.extended_attributes = {}
for i in xrange(num_attributes):
k = self._decode_string(mbdb)
v = self._decode_data(mbdb)
self.extended_attributes[k] = v
def _decode_string(self, s):
s_len, = unpack('>H', s.read(2))
if s_len == 0xffff:
return None
return s.read(s_len)
def _decode_data(self, s):
return self._decode_string(s)
def type(self):
return self.mode & 0xf000
def is_symbolic_link(self):
return self.type() == MASK_SYMBOLIC_LINK
def is_regular_file(self):
return self.type() == MASK_REGULAR_FILE
def is_directory(self):
return self.type() == MASK_DIRECTORY
class MBDB(object):
def __init__(self, path):
self.files = {}
# open the index
mbdx = file(path + '/Manifest.mbdx', 'rb')
# skip signature
signature = mbdx.read(len(MBDX_SIGNATURE))
if signature != MBDX_SIGNATURE:
raise Exception("Bad mbdx signature")
# open the database
mbdb = file(path + '/Manifest.mbdb', 'rb')
# skip signature
signature = mbdb.read(len(MBDB_SIGNATURE))
if signature != MBDB_SIGNATURE:
raise Exception("Bad mbdb signature")
# number of records in mbdx
records, = unpack('>L', mbdx.read(4))
for i in xrange(records):
# get the fixed size mbdx record
buf = mbdx.read(26)
# convert key to text. it is the filename in the backup directory
sb = buf[:20].encode('hex')
if len(sb) % 2 == 1:
sb = '0'+sb
offset, = unpack('>L', buf[20:24])
# read the record in the mbdb
offset, = unpack('>L', buf[20:24])
mbdb.seek(len(MBDB_SIGNATURE) + offset, os.SEEK_SET)
rec = MBFileRecord(mbdb)
self.files[sb] = rec
mbdx.close()
mbdb.close()
def get_file_by_name(self, filename):
for (k, v) in self.files.iteritems():
if v.path == filename:
return (k, v)
return None
'''
for f in self.files:
print f.path
'''
def getBackupKeyBag(backupfolder, passphrase):
manifest = BPlistReader.plistWithFile(backupfolder + "/Manifest.plist")
kb = Keybag(manifest["BackupKeyBag"].data)
if kb.unlockBackupKeybagWithPasscode(passphrase):
print "BackupKeyBag unlock OK"
return kb
else:
return None
def warn(msg):
print "WARNING: %s" % msg
def main():
if len(sys.argv) not in [3, 4]:
print "Usage: %s <backup path> <output path> [password]" % sys.argv[0]
sys.exit(1)
backup_path = sys.argv[1]
output_path = sys.argv[2]
if len(sys.argv) == 4:
password = sys.argv[3]
else:
password = ''
mbdb = MBDB(backup_path)
kb = getBackupKeyBag(backup_path, password)
if kb is None:
raise Exception("Cannot decrypt keybag. Wrong pass?")
for record in mbdb.files.values():
# create directories if they do not exist
# makedirs throw an exception, my code is ugly =)
if record.is_directory():
try:
os.makedirs(output_path + '/' + record.path)
except:
pass
for (filename, record) in mbdb.files.items():
# skip directories
if record.is_directory():
continue
# adjust output file name
if record.is_symbolic_link():
out_file = record.target
else:
out_file = record.path
# read backup file
try:
f = file(backup_path + '/' + filename, 'rb')
file_data = f.read()
f.close()
except(IOError):
warn("File %s (%s) has not been found" % (filename, record.path))
continue
if record.encryption_key is not None: # file is encrypted!
if kb.classKeys.has_key(record.protection_class):
kek = kb.classKeys[record.protection_class]['KEY']
k = AESUnwrap(kek, record.encryption_key[4:])
if k is not None:
c = AES.new(k, AES.MODE_CBC)
file_data = c.decrypt(file_data)
padding = file_data[record.size:]
if len(padding) > AES.block_size or padding != chr(len(padding)) * len(padding):
warn("Incorrect padding for file %s" % record.path)
file_data = file_data[:record.size]
else:
warn("Cannot unwrap key")
continue
else:
warn("Cannot load encryption key for file %s" % f)
# write output file
print("Writing %s" % out_file)
f = file(output_path + '/' + out_file, 'wb')
f.write(file_data)
f.close()
pass
if __name__ == '__main__':
main()
| Python |
import hashlib,struct,glob,sys,os
from crypto.PBKDF2 import PBKDF2
from util.bplist import BPlistReader
from Crypto.Cipher import AES
from util import read_file, write_file
import plistlib
"""
decrypt iOS 3 backup blob (metadata and file contents)
"""
def decrypt_blob(blob, auth_key):
len = struct.unpack(">H", blob[0:2])[0]
if len != 66:
print "blob len != 66"
magic = struct.unpack(">H", blob[2:4])[0]
if magic != 0x0100:
print "magic != 0x0100"
iv = blob[4:20]
blob_key = AES.new(auth_key, AES.MODE_CBC, iv).decrypt(blob[20:68])[:32]
return AES.new(blob_key, AES.MODE_CBC, iv).decrypt(blob[68:])
def decrypt_backup(backupfolder, outputfolder, passphrase):
manifest = plistlib.readPlist(backupfolder + "/Manifest.plist")
if not manifest["IsEncrypted"]:
print "backup is not encrypted manifest[IsEncrypted]"
return
manifest_data = manifest["Data"].data
authdata = manifest["AuthData"].data
pkbdf_salt = authdata[:8]
iv = authdata[8:24]
key = PBKDF2(passphrase,pkbdf_salt,iterations=2000).read(32)
data = AES.new(key, AES.MODE_CBC, iv).decrypt(authdata[24:])
auth_key = data[:32]
if hashlib.sha1(auth_key).digest() != data[32:52]:
print "wrong auth key (hash mismatch) => wrong passphrase"
return
print "Passphrase seems OK"
for mdinfo_name in glob.glob(backupfolder + "/*.mdinfo"):
mddata_name = mdinfo_name[:-7] + ".mddata"
mdinfo = BPlistReader.plistWithFile(mdinfo_name)
if mdinfo["IsEncrypted"]:
metadata = decrypt_blob(mdinfo["Metadata"], auth_key)
metadata = BPlistReader.plistWithString(metadata)
print metadata["Path"]
filedata = read_file(mddata_name)
filedata = decrypt_blob(filedata, auth_key)
filename = metadata["Path"].replace("/","_")
write_file(outputfolder + "/" + filename, filedata) | Python |
from Crypto.Cipher import AES
ZEROIV = "\x00"*16
def removePadding(blocksize, s):
'Remove rfc 1423 padding from string.'
n = ord(s[-1]) # last byte contains number of padding bytes
if n > blocksize or n > len(s):
raise Exception('invalid padding')
return s[:-n]
def AESdecryptCBC(data, key, iv=ZEROIV, padding=False):
if len(data) % 16:
print "AESdecryptCBC: data length not /16, truncating"
data = data[0:(len(data)/16) * 16]
data = AES.new(key, AES.MODE_CBC, iv).decrypt(data)
if padding:
return removePadding(16, data)
return data
| Python |
import struct
from Crypto.Cipher import AES
"""
http://www.ietf.org/rfc/rfc3394.txt
quick'n'dirty AES wrap implementation
used by iOS 4 KeyStore kernel extension for wrapping/unwrapping encryption keys
"""
def unpack64bit(s):
return struct.unpack(">Q",s)[0]
def pack64bit(s):
return struct.pack(">Q",s)
def AESUnwrap(kek, wrapped):
C = []
for i in xrange(len(wrapped)/8):
C.append(unpack64bit(wrapped[i*8:i*8+8]))
n = len(C) - 1
R = [0] * (n+1)
A = C[0]
for i in xrange(1,n+1):
R[i] = C[i]
for j in reversed(xrange(0,6)):
for i in reversed(xrange(1,n+1)):
todec = pack64bit(A ^ (n*j+i))
todec += pack64bit(R[i])
B = AES.new(kek).decrypt(todec)
A = unpack64bit(B[:8])
R[i] = unpack64bit(B[8:])
#assert A == 0xa6a6a6a6a6a6a6a6, "AESUnwrap: integrity check FAIL, wrong kek ?"
if A != 0xa6a6a6a6a6a6a6a6:
#print "AESUnwrap: integrity check FAIL, wrong kek ?"
return None
res = "".join(map(pack64bit, R[1:]))
return res | Python |
#!/usr/bin/python
# -*- coding: ascii -*-
###########################################################################
# PBKDF2.py - PKCS#5 v2.0 Password-Based Key Derivation
#
# Copyright (C) 2007, 2008 Dwayne C. Litzenberger <dlitz@dlitz.net>
# All rights reserved.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies and that
# both that copyright notice and this permission notice appear in
# supporting documentation.
#
# THE AUTHOR PROVIDES THIS SOFTWARE ``AS IS'' AND ANY EXPRESSED OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Country of origin: Canada
#
###########################################################################
# Sample PBKDF2 usage:
# from Crypto.Cipher import AES
# from PBKDF2 import PBKDF2
# import os
#
# salt = os.urandom(8) # 64-bit salt
# key = PBKDF2("This passphrase is a secret.", salt).read(32) # 256-bit key
# iv = os.urandom(16) # 128-bit IV
# cipher = AES.new(key, AES.MODE_CBC, iv)
# ...
#
# Sample crypt() usage:
# from PBKDF2 import crypt
# pwhash = crypt("secret")
# alleged_pw = raw_input("Enter password: ")
# if pwhash == crypt(alleged_pw, pwhash):
# print "Password good"
# else:
# print "Invalid password"
#
###########################################################################
# History:
#
# 2007-07-27 Dwayne C. Litzenberger <dlitz@dlitz.net>
# - Initial Release (v1.0)
#
# 2007-07-31 Dwayne C. Litzenberger <dlitz@dlitz.net>
# - Bugfix release (v1.1)
# - SECURITY: The PyCrypto XOR cipher (used, if available, in the _strxor
# function in the previous release) silently truncates all keys to 64
# bytes. The way it was used in the previous release, this would only be
# problem if the pseudorandom function that returned values larger than
# 64 bytes (so SHA1, SHA256 and SHA512 are fine), but I don't like
# anything that silently reduces the security margin from what is
# expected.
#
# 2008-06-17 Dwayne C. Litzenberger <dlitz@dlitz.net>
# - Compatibility release (v1.2)
# - Add support for older versions of Python (2.2 and 2.3).
#
###########################################################################
__version__ = "1.2"
from struct import pack
from binascii import b2a_hex
from random import randint
import string
try:
# Use PyCrypto (if available)
from Crypto.Hash import HMAC, SHA as SHA1
except ImportError:
# PyCrypto not available. Use the Python standard library.
import hmac as HMAC
import sha as SHA1
def strxor(a, b):
return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b)])
def b64encode(data, chars="+/"):
tt = string.maketrans("+/", chars)
return data.encode('base64').replace("\n", "").translate(tt)
class PBKDF2(object):
"""PBKDF2.py : PKCS#5 v2.0 Password-Based Key Derivation
This implementation takes a passphrase and a salt (and optionally an
iteration count, a digest module, and a MAC module) and provides a
file-like object from which an arbitrarily-sized key can be read.
If the passphrase and/or salt are unicode objects, they are encoded as
UTF-8 before they are processed.
The idea behind PBKDF2 is to derive a cryptographic key from a
passphrase and a salt.
PBKDF2 may also be used as a strong salted password hash. The
'crypt' function is provided for that purpose.
Remember: Keys generated using PBKDF2 are only as strong as the
passphrases they are derived from.
"""
def __init__(self, passphrase, salt, iterations=1000,
digestmodule=SHA1, macmodule=HMAC):
self.__macmodule = macmodule
self.__digestmodule = digestmodule
self._setup(passphrase, salt, iterations, self._pseudorandom)
def _pseudorandom(self, key, msg):
"""Pseudorandom function. e.g. HMAC-SHA1"""
return self.__macmodule.new(key=key, msg=msg,
digestmod=self.__digestmodule).digest()
def read(self, bytes):
"""Read the specified number of key bytes."""
if self.closed:
raise ValueError("file-like object is closed")
size = len(self.__buf)
blocks = [self.__buf]
i = self.__blockNum
while size < bytes:
i += 1
if i > 0xffffffffL or i < 1:
# We could return "" here, but
raise OverflowError("derived key too long")
block = self.__f(i)
blocks.append(block)
size += len(block)
buf = "".join(blocks)
retval = buf[:bytes]
self.__buf = buf[bytes:]
self.__blockNum = i
return retval
def __f(self, i):
# i must fit within 32 bits
assert 1 <= i <= 0xffffffffL
U = self.__prf(self.__passphrase, self.__salt + pack("!L", i))
result = U
for j in xrange(2, 1+self.__iterations):
U = self.__prf(self.__passphrase, U)
result = strxor(result, U)
return result
def hexread(self, octets):
"""Read the specified number of octets. Return them as hexadecimal.
Note that len(obj.hexread(n)) == 2*n.
"""
return b2a_hex(self.read(octets))
def _setup(self, passphrase, salt, iterations, prf):
# Sanity checks:
# passphrase and salt must be str or unicode (in the latter
# case, we convert to UTF-8)
if isinstance(passphrase, unicode):
passphrase = passphrase.encode("UTF-8")
if not isinstance(passphrase, str):
raise TypeError("passphrase must be str or unicode")
if isinstance(salt, unicode):
salt = salt.encode("UTF-8")
if not isinstance(salt, str):
raise TypeError("salt must be str or unicode")
# iterations must be an integer >= 1
if not isinstance(iterations, (int, long)):
raise TypeError("iterations must be an integer")
if iterations < 1:
raise ValueError("iterations must be at least 1")
# prf must be callable
if not callable(prf):
raise TypeError("prf must be callable")
self.__passphrase = passphrase
self.__salt = salt
self.__iterations = iterations
self.__prf = prf
self.__blockNum = 0
self.__buf = ""
self.closed = False
def close(self):
"""Close the stream."""
if not self.closed:
del self.__passphrase
del self.__salt
del self.__iterations
del self.__prf
del self.__blockNum
del self.__buf
self.closed = True
def crypt(word, salt=None, iterations=None):
"""PBKDF2-based unix crypt(3) replacement.
The number of iterations specified in the salt overrides the 'iterations'
parameter.
The effective hash length is 192 bits.
"""
# Generate a (pseudo-)random salt if the user hasn't provided one.
if salt is None:
salt = _makesalt()
# salt must be a string or the us-ascii subset of unicode
if isinstance(salt, unicode):
salt = salt.encode("us-ascii")
if not isinstance(salt, str):
raise TypeError("salt must be a string")
# word must be a string or unicode (in the latter case, we convert to UTF-8)
if isinstance(word, unicode):
word = word.encode("UTF-8")
if not isinstance(word, str):
raise TypeError("word must be a string or unicode")
# Try to extract the real salt and iteration count from the salt
if salt.startswith("$p5k2$"):
(iterations, salt, dummy) = salt.split("$")[2:5]
if iterations == "":
iterations = 400
else:
converted = int(iterations, 16)
if iterations != "%x" % converted: # lowercase hex, minimum digits
raise ValueError("Invalid salt")
iterations = converted
if not (iterations >= 1):
raise ValueError("Invalid salt")
# Make sure the salt matches the allowed character set
allowed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./"
for ch in salt:
if ch not in allowed:
raise ValueError("Illegal character %r in salt" % (ch,))
if iterations is None or iterations == 400:
iterations = 400
salt = "$p5k2$$" + salt
else:
salt = "$p5k2$%x$%s" % (iterations, salt)
rawhash = PBKDF2(word, salt, iterations).read(24)
return salt + "$" + b64encode(rawhash, "./")
# Add crypt as a static method of the PBKDF2 class
# This makes it easier to do "from PBKDF2 import PBKDF2" and still use
# crypt.
PBKDF2.crypt = staticmethod(crypt)
def _makesalt():
"""Return a 48-bit pseudorandom salt for crypt().
This function is not suitable for generating cryptographic secrets.
"""
binarysalt = "".join([pack("@H", randint(0, 0xffff)) for i in range(3)])
return b64encode(binarysalt, "./")
def test_pbkdf2():
"""Module self-test"""
from binascii import a2b_hex
#
# Test vectors from RFC 3962
#
# Test 1
result = PBKDF2("password", "ATHENA.MIT.EDUraeburn", 1).read(16)
expected = a2b_hex("cdedb5281bb2f801565a1122b2563515")
if result != expected:
raise RuntimeError("self-test failed")
# Test 2
result = PBKDF2("password", "ATHENA.MIT.EDUraeburn", 1200).hexread(32)
expected = ("5c08eb61fdf71e4e4ec3cf6ba1f5512b"
"a7e52ddbc5e5142f708a31e2e62b1e13")
if result != expected:
raise RuntimeError("self-test failed")
# Test 3
result = PBKDF2("X"*64, "pass phrase equals block size", 1200).hexread(32)
expected = ("139c30c0966bc32ba55fdbf212530ac9"
"c5ec59f1a452f5cc9ad940fea0598ed1")
if result != expected:
raise RuntimeError("self-test failed")
# Test 4
result = PBKDF2("X"*65, "pass phrase exceeds block size", 1200).hexread(32)
expected = ("9ccad6d468770cd51b10e6a68721be61"
"1a8b4d282601db3b36be9246915ec82a")
if result != expected:
raise RuntimeError("self-test failed")
#
# Other test vectors
#
# Chunked read
f = PBKDF2("kickstart", "workbench", 256)
result = f.read(17)
result += f.read(17)
result += f.read(1)
result += f.read(2)
result += f.read(3)
expected = PBKDF2("kickstart", "workbench", 256).read(40)
if result != expected:
raise RuntimeError("self-test failed")
#
# crypt() test vectors
#
# crypt 1
result = crypt("cloadm", "exec")
expected = '$p5k2$$exec$r1EWMCMk7Rlv3L/RNcFXviDefYa0hlql'
if result != expected:
raise RuntimeError("self-test failed")
# crypt 2
result = crypt("gnu", '$p5k2$c$u9HvcT4d$.....')
expected = '$p5k2$c$u9HvcT4d$Sd1gwSVCLZYAuqZ25piRnbBEoAesaa/g'
if result != expected:
raise RuntimeError("self-test failed")
# crypt 3
result = crypt("dcl", "tUsch7fU", iterations=13)
expected = "$p5k2$d$tUsch7fU$nqDkaxMDOFBeJsTSfABsyn.PYUXilHwL"
if result != expected:
raise RuntimeError("self-test failed")
# crypt 4 (unicode)
result = crypt(u'\u0399\u03c9\u03b1\u03bd\u03bd\u03b7\u03c2',
'$p5k2$$KosHgqNo$9mjN8gqjt02hDoP0c2J0ABtLIwtot8cQ')
expected = '$p5k2$$KosHgqNo$9mjN8gqjt02hDoP0c2J0ABtLIwtot8cQ'
if result != expected:
raise RuntimeError("self-test failed")
if __name__ == '__main__':
test_pbkdf2()
# vim:set ts=4 sw=4 sts=4 expandtab:
| Python |
from Crypto.Util import number
CURVE_P = (2**255 - 19)
CURVE_A = 121665
def curve25519_monty(x1, z1, x2, z2, qmqp):
a = (x1 + z1) * (x2 - z2) % CURVE_P
b = (x1 - z1) * (x2 + z2) % CURVE_P
x4 = (a + b) * (a + b) % CURVE_P
e = (a - b) * (a - b) % CURVE_P
z4 = e * qmqp % CURVE_P
a = (x1 + z1) * (x1 + z1) % CURVE_P
b = (x1 - z1) * (x1 - z1) % CURVE_P
x3 = a * b % CURVE_P
g = (a - b) % CURVE_P
h = (a + CURVE_A * g) % CURVE_P
z3 = (g * h) % CURVE_P
return x3, z3, x4, z4
def curve25519_mult(n, q):
nqpqx, nqpqz = q, 1
nqx, nqz = 1, 0
for i in range(255, -1, -1):
if (n >> i) & 1:
nqpqx,nqpqz,nqx,nqz = curve25519_monty(nqpqx, nqpqz, nqx, nqz, q)
else:
nqx,nqz,nqpqx,nqpqz = curve25519_monty(nqx, nqz, nqpqx, nqpqz, q)
return nqx, nqz
def curve25519(secret, basepoint):
a = ord(secret[0])
a &= 248
b = ord(secret[31])
b &= 127
b |= 64
s = chr(a) + secret[1:-1] + chr(b)
s = number.bytes_to_long(s[::-1])
basepoint = number.bytes_to_long(basepoint[::-1])
x, z = curve25519_mult(s, basepoint)
zmone = number.inverse(z, CURVE_P)
z = x * zmone % CURVE_P
return number.long_to_bytes(z)[::-1]
if __name__ == "__main__":
from crypto.aeswrap import AESUnwrap
from Crypto.Hash import SHA256
z="04000000080000000200000048000000000000000000000000000000000000000000000002917dc2542198edeb1078c4d1ebab74d9ca87890657ba02b9825dadf20a002f44360c6f87743fac0236df1f9eedbea801e31677aef3a09adfb4e10a37ae27facf419ab3ea3f39f4".decode("hex")
mysecret = "99b66345829d8c05041eea1ba1ed5b2984c3e5ec7a756ef053473c7f22b49f14".decode("hex")
mypublic = "b1c652786697a5feef36a56f36fde524a21193f4e563627977ab515f600fdb3a".decode("hex")
hispublic = z[36:36+32]
#c4d9fe462a2ebbf0745195ce7dc5e8b49947bbd5b42da74175d5f8125b44582b
shared = curve25519(mysecret, hispublic)
print shared.encode("hex")
h = SHA256.new()
h.update('\x00\x00\x00\x01')
h.update(shared)
h.update(hispublic)
h.update(mypublic)
md = h.digest()
#e442c81b91ea876d3cf42d3aea75f4b0c3f90f9fd045e1f5784b91260f3bdc9c
print AESUnwrap(md, z[32+36:]).encode("hex")
| Python |
#!/usr/bin/env python
from Crypto.Cipher import AES
from Crypto.Util import strxor
from struct import pack, unpack
from util.bplist import BPlistReader
def gcm_rightshift(vec):
for x in range(15, 0, -1):
c = vec[x] >> 1
c |= (vec[x-1] << 7) & 0x80
vec[x] = c
vec[0] >>= 1
return vec
def gcm_gf_mult(a, b):
mask = [ 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 ]
poly = [ 0x00, 0xe1 ]
Z = [0] * 16
V = [c for c in a]
for x in range(128):
if b[x >> 3] & mask[x & 7]:
Z = [V[y] ^ Z[y] for y in range(16)]
bit = V[15] & 1
V = gcm_rightshift(V)
V[0] ^= poly[bit]
return Z
def ghash(h, auth_data, data):
u = (16 - len(data)) % 16
v = (16 - len(auth_data)) % 16
x = auth_data + chr(0) * v + data + chr(0) * u
x += pack('>QQ', len(auth_data) * 8, len(data) * 8)
y = [0] * 16
vec_h = [ord(c) for c in h]
for i in range(0, len(x), 16):
block = [ord(c) for c in x[i:i+16]]
y = [y[j] ^ block[j] for j in range(16)]
y = gcm_gf_mult(y, vec_h)
return ''.join(chr(c) for c in y)
def inc32(block):
counter, = unpack('>L', block[12:])
counter += 1
return block[:12] + pack('>L', counter)
def gctr(k, icb, plaintext):
y = ''
if len(plaintext) == 0:
return y
aes = AES.new(k)
cb = icb
for i in range(0, len(plaintext), aes.block_size):
cb = inc32(cb)
encrypted = aes.encrypt(cb)
plaintext_block = plaintext[i:i+aes.block_size]
y += strxor.strxor(plaintext_block, encrypted[:len(plaintext_block)])
return y
def gcm_decrypt(k, iv, encrypted, auth_data, tag):
aes = AES.new(k)
h = aes.encrypt(chr(0) * aes.block_size)
if len(iv) == 12:
y0 = iv + "\x00\x00\x00\x01"
else:
y0 = ghash(h, '', iv)
decrypted = gctr(k, y0, encrypted)
s = ghash(h, auth_data, encrypted)
t = aes.encrypt(y0)
T = strxor.strxor(s, t)
if T != tag:
raise ValueError('Decrypted data is invalid')
else:
return decrypted
def gcm_encrypt(k, iv, plaintext, auth_data):
aes = AES.new(k)
h = aes.encrypt(chr(0) * aes.block_size)
if len(iv) == 12:
y0 = iv + "\x00\x00\x00\x01"
else:
y0 = ghash(h, '', iv)
encrypted = gctr(k, y0, plaintext)
s = ghash(h, auth_data, encrypted)
t = aes.encrypt(y0)
T = strxor.strxor(s, t)
return (encrypted, T)
def main():
#http://www.ieee802.org/1/files/public/docs2011/bn-randall-test-vectors-0511-v1.pdf
k = 'AD7A2BD03EAC835A6F620FDCB506B345'.decode("hex")
p = ''
a = 'D609B1F056637A0D46DF998D88E5222AB2C2846512153524C0895E8108000F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F30313233340001'.decode("hex")
iv = '12153524C0895E81B2C28465'.decode("hex")
c, t = gcm_encrypt(k, iv, '', a)
assert c == ""
assert t == "f09478a9b09007d06f46e9b6a1da25dd".decode("hex")
k = 'AD7A2BD03EAC835A6F620FDCB506B345'.decode("hex")
p = '08000F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F303132333435363738393A0002'.decode("hex")
a = 'D609B1F056637A0D46DF998D88E52E00B2C2846512153524C0895E81'.decode("hex")
iv = '12153524C0895E81B2C28465'.decode("hex")
c, t = gcm_encrypt(k, iv, p, a)
assert c == '701AFA1CC039C0D765128A665DAB69243899BF7318CCDC81C9931DA17FBE8EDD7D17CB8B4C26FC81E3284F2B7FBA713D'.decode("hex")
assert t == '4F8D55E7D3F06FD5A13C0C29B9D5B880'.decode("hex")
key = "91bfb6cbcff07b93a4c68bbfe99ac63b713f0627025c0fb1ffc5b0812dc284f8".decode("hex")
data = "020000000B00000028000000DE44D22E96B1966BAEF4CBEA8675871D40BA669401BD4EBB52AF9C025134187E70549012058456BF0EC0FA1F8FF9F822AC4312AB2141FA712E6D1482358EAC1421A1BFFA81EF38BD0BF2E52675D665EFE3C534E188F575774FAA92E74345575E370B9982661FAE8BD9243B7AD7D2105B275424C0CA1145B9D43AFF04F2747E40D62EC60563960D62A894BE66F267B14D75C0572BE60CC9B339D440FCB418D4F729BBF15C14E0D3A43E4A8B44523D8B3B0F3E7DF85AA67A707EE19CB893277D2392234D7DBC17DA4A0BD7F166189FC54C16C20D287E20FD2FB11BD2CE09ADBDABB95124CD4BFE219E34D3C80E69570A5A506555D7094916C5D75E0065F1796F556EDF0DAA1AA758E0C85AE3951BD363F26B1D43F6CBAEE12D97AD3B60CFA89C1C76BB29F2B54BE31B6CE166F4860C5E5DA92588EF53AA946DF159E60E6F05009D12FB1E37".decode("hex")
ciphertext = data[12+40:-16]
tag = data[-16:]
print repr(gcm_decrypt(key, '', ciphertext, '', tag))
if __name__ == '__main__':
main()
| Python |
"""
/**************************************************************
LZSS.C -- A Data Compression Program
***************************************************************
4/6/1989 Haruhiko Okumura
Use, distribute, and modify this program freely.
Please send me your improved versions.
PC-VAN SCIENCE
NIFTY-Serve PAF01022
CompuServe 74050,1022
**************************************************************/
/*
* lzss.c - Package for decompressing lzss compressed objects
*
* Copyright (c) 2003 Apple Computer, Inc.
*
* DRI: Josh de Cesare
*/
"""
from array import array
import struct
N = 4096
F = 18
THRESHOLD = 2
NIL = N
def decompress_lzss(str):
if str[:8] !="complzss":
print "decompress_lzss: complzss magic missing"
return
decompsize = struct.unpack(">L", str[12:16])[0]
text_buf = array("B", " "*(N + F - 1))
src = array("B", str[0x180:])
srclen = len(src)
dst = array("B", " "*decompsize)
r = N - F
srcidx, dstidx, flags, c = 0, 0, 0, 0
while True:
flags >>= 1
if ((flags & 0x100) == 0):
if (srcidx >= srclen):
break
c = src[srcidx]; srcidx += 1
flags = c | 0xFF00;
if (flags & 1):
if (srcidx >= srclen):
break
c = src[srcidx]; srcidx += 1
dst[dstidx] = c; dstidx += 1
text_buf[r] = c; r += 1
r &= (N - 1);
else:
if (srcidx >= srclen):
break
i = src[srcidx]; srcidx += 1
if (srcidx >= srclen):
break
j = src[srcidx]; srcidx += 1
i |= ((j & 0xF0) << 4)
j = (j & 0x0F) + THRESHOLD
for k in xrange(j+1):
c = text_buf[(i + k) & (N - 1)]
dst[dstidx] = c; dstidx += 1
text_buf[r] = c; r += 1
r &= (N - 1)
return dst.tostring()
| Python |
import base64
def chunks(l, n):
return (l[i:i+n] for i in xrange(0, len(l), n))
def RSA_KEY_DER_to_PEM(data):
a = ["-----BEGIN RSA PRIVATE KEY-----"]
a.extend(chunks(base64.b64encode(data),64))
a.append("-----END RSA PRIVATE KEY-----")
return "\n".join(a) | Python |
import struct
def tlvToDict(blob):
d = {}
for tag,data in loopTLVBlocks(blob):
d[tag] = data
return d
def tlvToList(blob):
return list(loopTLVBlocks(blob))
def loopTLVBlocks(blob):
i = 0
while i + 8 <= len(blob):
tag = blob[i:i+4]
length = struct.unpack(">L",blob[i+4:i+8])[0]
data = blob[i+8:i+8+length]
yield (tag,data)
i += 8 + length | Python |
"""
http://github.com/farcaller/bplist-python/blob/master/bplist.py
"""
import struct
import plistlib
from datetime import datetime, timedelta
class BPListWriter(object):
def __init__(self, objects):
self.bplist = ""
self.objects = objects
def binary(self):
'''binary -> string
Generates bplist
'''
self.data = 'bplist00'
# TODO: flatten objects and count max length size
# TODO: write objects and save offsets
# TODO: write offsets
# TODO: write metadata
return self.data
def write(self, filename):
'''
Writes bplist to file
'''
if self.bplist != "":
pass
# TODO: save self.bplist to file
else:
raise Exception('BPlist not yet generated')
class BPlistReader(object):
def __init__(self, s):
self.data = s
self.objects = []
self.resolved = {}
def __unpackIntStruct(self, sz, s):
'''__unpackIntStruct(size, string) -> int
Unpacks the integer of given size (1, 2 or 4 bytes) from string
'''
if sz == 1:
ot = '!B'
elif sz == 2:
ot = '!H'
elif sz == 4:
ot = '!I'
else:
raise Exception('int unpack size '+str(sz)+' unsupported')
return struct.unpack(ot, s)[0]
def __unpackInt(self, offset):
'''__unpackInt(offset) -> int
Unpacks int field from plist at given offset
'''
return self.__unpackIntMeta(offset)[1]
def __unpackIntMeta(self, offset):
'''__unpackIntMeta(offset) -> (size, int)
Unpacks int field from plist at given offset and returns its size and value
'''
obj_header = struct.unpack('!B', self.data[offset])[0]
obj_type, obj_info = (obj_header & 0xF0), (obj_header & 0x0F)
int_sz = 2**obj_info
return int_sz, self.__unpackIntStruct(int_sz, self.data[offset+1:offset+1+int_sz])
def __resolveIntSize(self, obj_info, offset):
'''__resolveIntSize(obj_info, offset) -> (count, offset)
Calculates count of objref* array entries and returns count and offset to first element
'''
if obj_info == 0x0F:
ofs, obj_count = self.__unpackIntMeta(offset+1)
objref = offset+2+ofs
else:
obj_count = obj_info
objref = offset+1
return obj_count, objref
def __unpackFloatStruct(self, sz, s):
'''__unpackFloatStruct(size, string) -> float
Unpacks the float of given size (4 or 8 bytes) from string
'''
if sz == 4:
ot = '!f'
elif sz == 8:
ot = '!d'
else:
raise Exception('float unpack size '+str(sz)+' unsupported')
return struct.unpack(ot, s)[0]
def __unpackFloat(self, offset):
'''__unpackFloat(offset) -> float
Unpacks float field from plist at given offset
'''
obj_header = struct.unpack('!B', self.data[offset])[0]
obj_type, obj_info = (obj_header & 0xF0), (obj_header & 0x0F)
int_sz = 2**obj_info
return int_sz, self.__unpackFloatStruct(int_sz, self.data[offset+1:offset+1+int_sz])
def __unpackDate(self, offset):
td = int(struct.unpack(">d", self.data[offset+1:offset+9])[0])
return datetime(year=2001,month=1,day=1) + timedelta(seconds=td)
def __unpackItem(self, offset):
'''__unpackItem(offset)
Unpacks and returns an item from plist
'''
obj_header = struct.unpack('!B', self.data[offset])[0]
obj_type, obj_info = (obj_header & 0xF0), (obj_header & 0x0F)
if obj_type == 0x00:
if obj_info == 0x00: # null 0000 0000
return None
elif obj_info == 0x08: # bool 0000 1000 // false
return False
elif obj_info == 0x09: # bool 0000 1001 // true
return True
elif obj_info == 0x0F: # fill 0000 1111 // fill byte
raise Exception("0x0F Not Implemented") # this is really pad byte, FIXME
else:
raise Exception('unpack item type '+str(obj_header)+' at '+str(offset)+ 'failed')
elif obj_type == 0x10: # int 0001 nnnn ... // # of bytes is 2^nnnn, big-endian bytes
return self.__unpackInt(offset)
elif obj_type == 0x20: # real 0010 nnnn ... // # of bytes is 2^nnnn, big-endian bytes
return self.__unpackFloat(offset)
elif obj_type == 0x30: # date 0011 0011 ... // 8 byte float follows, big-endian bytes
return self.__unpackDate(offset)
elif obj_type == 0x40: # data 0100 nnnn [int] ... // nnnn is number of bytes unless 1111 then int count follows, followed by bytes
obj_count, objref = self.__resolveIntSize(obj_info, offset)
return plistlib.Data(self.data[objref:objref+obj_count]) # XXX: we return data as str
elif obj_type == 0x50: # string 0101 nnnn [int] ... // ASCII string, nnnn is # of chars, else 1111 then int count, then bytes
obj_count, objref = self.__resolveIntSize(obj_info, offset)
return self.data[objref:objref+obj_count]
elif obj_type == 0x60: # string 0110 nnnn [int] ... // Unicode string, nnnn is # of chars, else 1111 then int count, then big-endian 2-byte uint16_t
obj_count, objref = self.__resolveIntSize(obj_info, offset)
return self.data[objref:objref+obj_count*2].decode('utf-16be')
elif obj_type == 0x80: # uid 1000 nnnn ... // nnnn+1 is # of bytes
# FIXME: Accept as a string for now
obj_count, objref = self.__resolveIntSize(obj_info, offset)
return plistlib.Data(self.data[objref:objref+obj_count])
elif obj_type == 0xA0: # array 1010 nnnn [int] objref* // nnnn is count, unless '1111', then int count follows
obj_count, objref = self.__resolveIntSize(obj_info, offset)
arr = []
for i in range(obj_count):
arr.append(self.__unpackIntStruct(self.object_ref_size, self.data[objref+i*self.object_ref_size:objref+i*self.object_ref_size+self.object_ref_size]))
return arr
elif obj_type == 0xC0: # set 1100 nnnn [int] objref* // nnnn is count, unless '1111', then int count follows
# XXX: not serializable via apple implementation
raise Exception("0xC0 Not Implemented") # FIXME: implement
elif obj_type == 0xD0: # dict 1101 nnnn [int] keyref* objref* // nnnn is count, unless '1111', then int count follows
obj_count, objref = self.__resolveIntSize(obj_info, offset)
keys = []
for i in range(obj_count):
keys.append(self.__unpackIntStruct(self.object_ref_size, self.data[objref+i*self.object_ref_size:objref+i*self.object_ref_size+self.object_ref_size]))
values = []
objref += obj_count*self.object_ref_size
for i in range(obj_count):
values.append(self.__unpackIntStruct(self.object_ref_size, self.data[objref+i*self.object_ref_size:objref+i*self.object_ref_size+self.object_ref_size]))
dic = {}
for i in range(obj_count):
dic[keys[i]] = values[i]
return dic
else:
raise Exception('don\'t know how to unpack obj type '+hex(obj_type)+' at '+str(offset))
def __resolveObject(self, idx):
try:
return self.resolved[idx]
except KeyError:
obj = self.objects[idx]
if type(obj) == list:
newArr = []
for i in obj:
newArr.append(self.__resolveObject(i))
self.resolved[idx] = newArr
return newArr
if type(obj) == dict:
newDic = {}
for k,v in obj.iteritems():
rk = self.__resolveObject(k)
rv = self.__resolveObject(v)
newDic[rk] = rv
self.resolved[idx] = newDic
return newDic
else:
self.resolved[idx] = obj
return obj
def parse(self):
# read header
if self.data[:8] != 'bplist00':
raise Exception('Bad magic')
# read trailer
self.offset_size, self.object_ref_size, self.number_of_objects, self.top_object, self.table_offset = struct.unpack('!6xBB4xI4xI4xI', self.data[-32:])
#print "** plist offset_size:",self.offset_size,"objref_size:",self.object_ref_size,"num_objs:",self.number_of_objects,"top:",self.top_object,"table_ofs:",self.table_offset
# read offset table
self.offset_table = self.data[self.table_offset:-32]
self.offsets = []
ot = self.offset_table
for i in range(self.number_of_objects):
offset_entry = ot[:self.offset_size]
ot = ot[self.offset_size:]
self.offsets.append(self.__unpackIntStruct(self.offset_size, offset_entry))
#print "** plist offsets:",self.offsets
# read object table
self.objects = []
k = 0
for i in self.offsets:
obj = self.__unpackItem(i)
#print "** plist unpacked",k,type(obj),obj,"at",i
k += 1
self.objects.append(obj)
# rebuild object tree
#for i in range(len(self.objects)):
# self.__resolveObject(i)
# return root object
return self.__resolveObject(self.top_object)
@classmethod
def plistWithString(cls, s):
parser = cls(s)
return parser.parse()
@classmethod
def plistWithFile(cls, f):
file = open(f,"rb")
parser = cls(file.read())
file.close()
return parser.parse() | Python |
def read_file(filename):
f = open(filename, "rb")
data = f.read()
f.close()
return data
def write_file(filename,data):
f = open(filename, "wb")
f.write(data)
f.close()
| Python |
import os
import plistlib
import struct
import socket
from datetime import datetime
from progressbar import ProgressBar, Percentage, Bar, SimpleProgress, ETA
class DeviceInfo(dict):
@staticmethod
def create(dict):
try:
assert dict.has_key("dataVolumeUUID")
filename = "%s.plist" % dict.get("dataVolumeUUID")
return DeviceInfo(plistlib.readPlist(filename))
except:
return DeviceInfo(dict)
def save(self):
filename = "%s.plist" % self.get("dataVolumeUUID", "unk")
print "Saving %s/%s" % (os.getcwd() , filename)
plistlib.writePlist(self, filename)
def __del__(self):
pass#self.save()
class RamdiskToolClient(object):
def __init__(self, host="localhost", port=1999):
self.host = host
self.port = port
self.device_infos = {}
self.connect()
def connect(self):
self.s = socket.socket()
try:
self.s.connect((self.host, self.port))
except:
raise Exception("Cannot cannot to ramdisk over usbmux, run \"python tcprelay.py -t 22:2222 1999:%d\"" % self.port)
def getDeviceInfos(self):
self.device_infos = self.send_req({"Request":"DeviceInfo"})
print "Device UDID :", self.device_infos.get("udid")
return DeviceInfo.create(self.device_infos)
def downloadFile(self, path):
res = self.send_req({"Request": "DownloadFile",
"Path": path})
if type(res) == plistlib._InternalDict and res.has_key("Data"):
return res["Data"].data
def getSystemKeyBag(self):
return self.send_req({"Request":"GetSystemKeyBag"})
def bruteforceKeyBag(self, KeyBagKeys):
return self.send_req({"Request":"BruteforceSystemKeyBag",
"KeyBagKeys": plistlib.Data(KeyBagKeys)})
def getEscrowRecord(self, hostID):
return self.send_req({"Request":"GetEscrowRecord",
"HostID": hostID})
def getPasscodeKey(self, keybagkeys, passcode):
return self.send_req({"Request":"KeyBagGetPasscodeKey",
"KeyBagKeys": plistlib.Data(keybagkeys),
"passcode": passcode})
def send_msg(self, dict):
plist = plistlib.writePlistToString(dict)
data = struct.pack("<L",len(plist)) + plist
return self.s.send(data)
def recv_msg(self):
try:
l = self.s.recv(4)
ll = struct.unpack("<L",l)[0]
data = ""
l = 0
while l < ll:
x = self.s.recv(ll-l)
if not x:
return None
data += x
l += len(x)
return plistlib.readPlistFromString(data)
except:
raise
return None
def send_req(self, dict):
start = None
self.send_msg(dict)
while True:
r = self.recv_msg()
if type(r) == plistlib._InternalDict and r.get("MessageType") == "Progress":
if not start:
pbar = ProgressBar(r.get("Total",100),[SimpleProgress(), " ", Percentage(), " ", Bar()])
pbar.start()
start = datetime.utcnow()
pbar.update( r.get("Progress", 0))
else:
if start:
print dict.get("Request"), ":", datetime.utcnow() - start
return r
| Python |
import os
import sys
import struct
import zlib
from btree import AttributesTree, CatalogTree, ExtentsOverflowTree
from structs import *
from util import write_file
class HFSFile(object):
def __init__(self, volume, hfsplusfork, fileID, deleted=False):
self.volume = volume
self.blockSize = volume.blockSize
self.fileID = fileID
self.totalBlocks = hfsplusfork.totalBlocks
self.logicalSize = hfsplusfork.logicalSize
self.extents = []
self.deleted = deleted
b = 0
for extent in hfsplusfork.HFSPlusExtentDescriptor:
self.extents.append(extent)
b += extent.blockCount
while b != hfsplusfork.totalBlocks:
#print "extents overflow ", b
k,v = volume.getExtentsOverflowForFile(fileID, b)
if not v:
print "extents overflow missing, startblock=%d" % b
break
for extent in v:
self.extents.append(extent)
b += extent.blockCount
def readAll(self, outputfile, truncate=True):
f = open(outputfile, "wb")
for i in xrange(self.totalBlocks):
f.write(self.readBlock(i))
if truncate:
f.truncate(self.logicalSize)
f.close()
def readAllBuffer(self, truncate=True):
r = ""
for i in xrange(self.totalBlocks):
r += self.readBlock(i)
if truncate:
r = r[:self.logicalSize]
return r
def processBlock(self, block, lba):
return block
def readBlock(self, n):
bs = self.volume.blockSize
if n*bs > self.logicalSize:
return "BLOCK OUT OF BOUNDS" + "\xFF" * (bs - len("BLOCK OUT OF BOUNDS"))
bc = 0
for extent in self.extents:
bc += extent.blockCount
if n < bc:
lba = extent.startBlock+(n-(bc-extent.blockCount))
if not self.deleted and self.fileID != kHFSAllocationFileID and not self.volume.isBlockInUse(lba):
print "FAIL, block %x not marked as used" % n
return self.processBlock(self.volume.read(lba*bs, bs), lba)
return ""
class HFSCompressedResourceFork(HFSFile):
def __init__(self, volume, hfsplusfork, fileID):
super(HFSCompressedResourceFork,self).__init__(volume, hfsplusfork, fileID)
block0 = self.readBlock(0)
self.header = HFSPlusCmpfRsrcHead.parse(block0)
print self.header
self.blocks = HFSPlusCmpfRsrcBlockHead.parse(block0[self.header.headerSize:])
print "HFSCompressedResourceFork numBlocks:", self.blocks.numBlocks
#HAX, readblock not implemented
def readAllBuffer(self):
buff = super(HFSCompressedResourceFork, self).readAllBuffer()
r = ""
base = self.header.headerSize + 4
for b in self.blocks.HFSPlusCmpfRsrcBlock:
r += zlib.decompress(buff[base+b.offset:base+b.offset+b.size])
return r
class HFSVolume(object):
def __init__(self, filename, write=False, offset=0):
flag = os.O_RDONLY if not write else os.O_RDWR
if sys.platform == 'win32':
flag = flag | os.O_BINARY
self.fd = os.open(filename, flag)
self.offset = offset
self.writeFlag = write
try:
data = self.read(0, 0x1000)
self.header = HFSPlusVolumeHeader.parse(data[0x400:0x800])
assert self.header.signature == 0x4858 or self.header.signature == 0x482B
except:
raise Exception("Not an HFS+ image")
self.blockSize = self.header.blockSize
if os.path.getsize(filename) < self.header.totalBlocks * self.blockSize:
print "WARNING: image appears to be truncated"
self.allocationFile = HFSFile(self, self.header.allocationFile, kHFSAllocationFileID)
self.allocationBitmap = self.allocationFile.readAllBuffer()
self.extentsFile = HFSFile(self, self.header.extentsFile, kHFSExtentsFileID)
self.extentsTree = ExtentsOverflowTree(self.extentsFile)
self.catalogFile = HFSFile(self, self.header.catalogFile, kHFSCatalogFileID)
self.xattrFile = HFSFile(self, self.header.attributesFile, kHFSAttributesFileID)
self.catalogTree = CatalogTree(self.catalogFile)
self.xattrTree = AttributesTree(self.xattrFile)
self.hasJournal = self.header.attributes & (1 << kHFSVolumeJournaledBit)
def read(self, offset, size):
os.lseek(self.fd, self.offset + offset, os.SEEK_SET)
return os.read(self.fd, size)
def write(self, offset, data):
if self.writeFlag: #fail silently for testing
os.lseek(self.fd, self.offset + offset, os.SEEK_SET)
return os.write(self.fd, data)
def writeBlock(self, lba, block):
return self.write(lba*self.blockSize, block)
def volumeID(self):
return struct.pack(">LL", self.header.finderInfo[6], self.header.finderInfo[7])
def isBlockInUse(self, block):
thisByte = ord(self.allocationBitmap[block / 8])
return (thisByte & (1 << (7 - (block % 8)))) != 0
def unallocatedBlocks(self):
for i in xrange(self.header.totalBlocks):
if not self.isBlockInUse(i):
yield i, self.read(i*self.blockSize, self.blockSize)
def getExtentsOverflowForFile(self, fileID, startBlock, forkType=kForkTypeData):
return self.extentsTree.searchExtents(fileID, forkType, startBlock)
def getXattr(self, fileID, name):
return self.xattrTree.searchXattr(fileID, name)
def getFileByPath(self, path):
return self.catalogTree.getRecordFromPath(path)
def listFolderContents(self, path):
k,v = self.catalogTree.getRecordFromPath(path)
if not k or v.recordType != kHFSPlusFolderRecord:
return
for k,v in self.catalogTree.getFolderContents(v.data.folderID):
if v.recordType == kHFSPlusFolderRecord:
print v.data.folderID, getString(k) + "/"
elif v.recordType == kHFSPlusFileRecord:
print v.data.fileID, getString(k)
def listXattrs(self, path):
k,v = self.catalogTree.getRecordFromPath(path)
if k and v.recordType == kHFSPlusFileRecord:
return self.xattrTree.getAllXattrs(v.data.fileID)
elif k and v.recordType == kHFSPlusFolderThreadRecord:
return self.xattrTree.getAllXattrs(v.data.folderID)
def readFile(self, path, returnString=False):
k,v = self.catalogTree.getRecordFromPath(path)
if not v:
print "File %s not found" % path
return
assert v.recordType == kHFSPlusFileRecord
xattr = self.getXattr(v.data.fileID, "com.apple.decmpfs")
if xattr:
decmpfs = HFSPlusDecmpfs.parse(xattr)
if decmpfs.compression_type == 1:
return xattr[16:]
elif decmpfs.compression_type == 3:
if decmpfs.uncompressed_size == len(xattr) - 16:
return xattr[16:]
return zlib.decompress(xattr[16:])
elif decmpfs.compression_type == 4:
f = HFSCompressedResourceFork(self, v.data.resourceFork, v.data.fileID)
return f.readAllBuffer()
f = HFSFile(self, v.data.dataFork, v.data.fileID)
if returnString:
return f.readAllBuffer()
else:
f.readAll(os.path.basename(path))
def readJournal(self):
jb = self.read(self.header.journalInfoBlock * self.blockSize, self.blockSize)
jib = JournalInfoBlock.parse(jb)
return self.read(jib.offset,jib.size)
if __name__ == "__main__":
v = HFSVolume("myramdisk.dmg",offset=0x40)
v.listFolderContents("/")
print v.readFile("/usr/local/share/restore/imeisv_svn.plist")
print v.listXattrs("/usr/local/share/restore/imeisv_svn.plist")
| Python |
import hashlib
from Crypto.Cipher import AES
from emf import cprotect_xattr, cprotect4_xattr, EMFFile
from structs import *
from util import write_file
"""
Implementation of the following paper :
Using the HFS+ Journal For Deleted File Recovery. Aaron Burghardt, Adam Feldman. DFRWS 2008
http://www.dfrws.org/2008/proceedings/p76-burghardt.pdf
http://www.dfrws.org/2008/proceedings/p76-burghardt_pres.pdf
"""
def carveBtreeNode(node, kClass, dClass):
try:
btnode = BTNodeDescriptor.parse(node)
if btnode.kind == kBTLeafNode:
off = BTNodeDescriptor.sizeof()
recs = []
offsets = Array(btnode.numRecords, UBInt16("off")).parse(node[-2*btnode.numRecords:])
for i in xrange(btnode.numRecords):
off = offsets[btnode.numRecords-i-1]
k = kClass.parse(node[off:])
off += 2 + k.keyLength
d = dClass.parse(node[off:])
recs.append((k,d))
return recs
return []
except:
return []
"""
for standard HFS volumes
"""
def carveHFSVolumeJournal(volume):
journal = volume.readJournal()
hdr = journal_header.parse(journal)
sector_size = hdr.jhdr_size
nodeSize = volume.catalogTree.nodeSize
f={}
for i in xrange(0,len(journal), sector_size):
for k,v in carveBtreeNode(journal[i:i+nodeSize],HFSPlusCatalogKey, HFSPlusCatalogData):
if v.recordType == kHFSPlusFileRecord:
name = getString(k)
h = hashlib.sha1(HFSPlusCatalogKey.build(k)).digest()
if f.has_key(h):
continue
if volume.catalogTree.searchByCNID(v.data.fileID) == (None, None):
if volume.isBlockInUse(v.data.dataFork.HFSPlusExtentDescriptor[0].startBlock) == False:
print "deleted file", v.data.fileID, name
fileid = v.data.fileID
f[h]=(name, v)
return f.values()
magics=["SQLite", "bplist", "<?xml", "\xFF\xD8\xFF", "\xCE\xFA\xED\xFE"]
"""
HAX: should do something better like compute entropy or something
"""
def isDecryptedCorrectly(data):
for m in magics:
if data.startswith(m):
return True
return False
"""
carve the journal for deleted cprotect xattrs and file records
"""
def carveEMFVolumeJournal(volume):
journal = volume.readJournal()
hdr = journal_header.parse(journal)
sector_size = hdr.jhdr_size
nodeSize = volume.catalogTree.nodeSize
files = {}
keys = {}
cprotect_struct_type = cprotect_xattr
if volume.cp_root.major_version >= 4:
cprotect_struct_type = cprotect4_xattr
for i in xrange(0,len(journal),sector_size):
for k,v in carveBtreeNode(journal[i:i+nodeSize],HFSPlusCatalogKey, HFSPlusCatalogData):
if v.recordType == kHFSPlusFileRecord:
name = getString(k)
h = hashlib.sha1(HFSPlusCatalogKey.build(k)).digest()
if files.has_key(h):
continue
if volume.catalogTree.searchByCNID(v.data.fileID) == (None, None):
#we only keep files where the first block is not marked as in use
if volume.isBlockInUse(v.data.dataFork.HFSPlusExtentDescriptor[0].startBlock) == False:
print "Found deleted file record", v.data.fileID, name
files[h] = (name,v)
for k,v in carveBtreeNode(journal[i:i+nodeSize],HFSPlusAttrKey, HFSPlusAttrData):
if getString(k) == "com.apple.system.cprotect":
if volume.catalogTree.searchByCNID(k) == (None, None):
filekeys = keys.setdefault(k.fileID, [])
try:
cprotect = cprotect_struct_type.parse(v.data)
except:
continue
#assert cprotect.xattr_major_version == 2
filekey = volume.keystore.unwrapKeyForClass(cprotect.persistent_class, cprotect.persistent_key)
if filekey and not filekey in filekeys:
print "Found key for file", k.fileID
filekeys.append(filekey)
return files.values(), keys
"""
"bruteforce" method, tries to decrypt all unallocated blocks with provided file keys
this is a hack, don't expect interesting results with this
"""
def carveEMFemptySpace(volume, file_keys, outdir):
for lba, block in volume.unallocatedBlocks():
iv = volume.ivForLBA(lba)
for filekey in file_keys:
ciphertext = AES.new(volume.emfkey, AES.MODE_CBC, iv).encrypt(block)
clear = AES.new(filekey, AES.MODE_CBC, iv).decrypt(ciphertext)
if isDecryptedCorrectly(clear):
print "Decrypted stuff at lba %x" % lba
open(outdir+ "/%x.bin" % lba, "wb").write(clear)
def do_emf_carving(volume, carveokdir, carvenokdir):
deletedFiles, filekeys = carveEMFVolumeJournal(volume)
print "Journal carving done, trying to extract deleted files"
n = 0
for name, vv in deletedFiles:
for filekey in filekeys.get(vv.data.fileID, []):
ff = EMFFile(volume,vv.data.dataFork, vv.data.fileID, filekey, deleted=True)
data = ff.readAllBuffer()
if isDecryptedCorrectly(data):
write_file(carveokdir + "%s_%s" % (filekey.encode("hex")[:8],name.replace("/","_")),data)
n += 1
else:
write_file(carvenokdir + "%s_%s" % (filekey.encode("hex")[:8],name.replace("/","_")),data)
if not filekeys.has_key(vv.data.fileID):
print "Missing file key for", name
else:
del filekeys[vv.data.fileID]
print "Done, extracted %d files" % n
if False:
fks = set(reduce(lambda x,y: x+y, filekeys.values()))
print "%d file keys left, try carving empty space (slow) ? CTRL-C to exit" % len(fks)
raw_input()
carveEMFemptySpace(volume, fks) | Python |
import plistlib
import os
import struct
from hfs import HFSVolume, HFSFile
from keystore.keybag import Keybag
from structs import HFSPlusVolumeHeader, kHFSPlusFileRecord, getString
from construct import Struct, ULInt16,ULInt32, String
from Crypto.Cipher import AES
from construct.macros import ULInt64, Padding
from structs import kHFSRootParentID
import hashlib
"""
iOS >= 4 raw images
http://opensource.apple.com/source/xnu/xnu-1699.22.73/bsd/hfs/hfs_cprotect.c
http://opensource.apple.com/source/xnu/xnu-1699.22.73/bsd/sys/cprotect.h
"""
cp_root_xattr = Struct("cp_root_xattr",
ULInt16("major_version"),
ULInt16("minor_version"),
ULInt64("flags"),
ULInt32("reserved1"),
ULInt32("reserved2"),
ULInt32("reserved3"),
ULInt32("reserved4")
)
cprotect_xattr = Struct("cprotect_xattr",
ULInt16("xattr_major_version"),
ULInt16("xattr_minor_version"),
ULInt32("flags"),
ULInt32("persistent_class"),
ULInt32("key_size"),
String("persistent_key", length=0x28)
)
cprotect4_xattr = Struct("cprotect_xattr",
ULInt16("xattr_major_version"),
ULInt16("xattr_minor_version"),
ULInt32("flags"),
ULInt32("persistent_class"),
ULInt32("key_size"),
Padding(20),
String("persistent_key", length=lambda ctx: ctx["key_size"])
)
#HAX: flags set in finderInfo[3] to tell if the image was already decrypted
FLAG_DECRYPTING = 0x454d4664 #EMFd big endian
FLAG_DECRYPTED = 0x454d4644 #EMFD big endian
class EMFFile(HFSFile):
def __init__(self, volume, hfsplusfork, fileID, filekey, deleted=False):
super(EMFFile,self).__init__(volume, hfsplusfork, fileID, deleted)
self.filekey = filekey
self.ivkey = None
self.decrypt_offset = 0
if volume.cp_root.major_version == 4:
self.ivkey = hashlib.sha1(filekey).digest()[:16]
def processBlock(self, block, lba):
iv = self.volume.ivForLBA(lba)
ciphertext = AES.new(self.volume.emfkey, AES.MODE_CBC, iv).encrypt(block)
if not self.ivkey:
clear = AES.new(self.filekey, AES.MODE_CBC, iv).decrypt(ciphertext)
else:
clear = ""
for i in xrange(len(block)/0x1000):
iv = self.volume.ivForLBA(self.decrypt_offset, False)
iv = AES.new(self.ivkey).encrypt(iv)
clear += AES.new(self.filekey, AES.MODE_CBC, iv).decrypt(ciphertext[i*0x1000:(i+1)*0x1000])
self.decrypt_offset += 0x1000
return clear
def decryptFile(self):
self.decrypt_offset = 0
bs = self.volume.blockSize
for extent in self.extents:
for i in xrange(extent.blockCount):
lba = extent.startBlock+i
data = self.volume.read(lba*bs, bs)
if len(data) == bs:
clear = self.processBlock(data, lba)
self.volume.writeBlock(lba, clear)
class EMFVolume(HFSVolume):
def __init__(self, file, **kwargs):
super(EMFVolume,self).__init__(file, **kwargs)
pl = "%s/%s.plist" % (os.path.dirname(file), self.volumeID().encode("hex"))
if pl.startswith("/"):
pl = pl[1:]
if not os.path.exists(pl):
raise Exception("Missing keyfile %s" % pl)
try:
pldict = plistlib.readPlist(pl)
self.emfkey = pldict["EMF"].decode("hex")
self.lbaoffset = pldict["dataVolumeOffset"]
self.keystore = Keybag.createWithPlist(pldict)
except:
raise #Exception("Invalid keyfile")
rootxattr = self.getXattr(kHFSRootParentID, "com.apple.system.cprotect")
if rootxattr == None:
print "Not an EMF image, no root com.apple.system.cprotec xattr"
else:
self.cp_root = cp_root_xattr.parse(rootxattr)
print "cprotect version :", self.cp_root.major_version
assert self.cp_root.major_version == 2 or self.cp_root.major_version == 4
def ivForLBA(self, lba, add=True):
iv = ""
if add:
lba = lba + self.lbaoffset
for _ in xrange(4):
if (lba & 1):
lba = 0x80000061 ^ (lba >> 1);
else:
lba = lba >> 1;
iv += struct.pack("<L", lba)
return iv
def getFileKeyForCprotect(self, cp):
if self.cp_root.major_version == 2:
cprotect = cprotect_xattr.parse(cp)
elif self.cp_root.major_version == 4:
cprotect = cprotect4_xattr.parse(cp)
return self.keystore.unwrapKeyForClass(cprotect.persistent_class, cprotect.persistent_key)
def readFile(self, path, outFolder="./"):
k,v = self.catalogTree.getRecordFromPath(path)
if not v:
print "File %s not found" % path
return
assert v.recordType == kHFSPlusFileRecord
cprotect = self.getXattr(v.data.fileID, "com.apple.system.cprotect")
if cprotect == None:
print "cprotect attr not found, reading normally"
return super(EMFVolume, self).readFile(path)
filekey = self.getFileKeyForCprotect(cprotect)
if not filekey:
print "Cannot unwrap file key for file %s protection_class=%d" % (path, cprotect.protection_class)
return
f = EMFFile(self, v.data.dataFork, v.data.fileID, filekey)
f.readAll(outFolder + os.path.basename(path))
def flagVolume(self, flag):
self.header.finderInfo[3] = flag
h = HFSPlusVolumeHeader.build(self.header)
return self.write(0x400, h)
def decryptAllFiles(self):
if self.header.finderInfo[3] == FLAG_DECRYPTING:
print "Volume is half-decrypted, aborting (finderInfo[3] == FLAG_DECRYPTING)"
return
elif self.header.finderInfo[3] == FLAG_DECRYPTED:
print "Volume already decrypted (finderInfo[3] == FLAG_DECRYPTED)"
return
self.failedToGetKey = []
self.notEncrypted = []
self.decryptedCount = 0
self.flagVolume(FLAG_DECRYPTING)
self.catalogTree.traverseLeafNodes(callback=self.decryptFile)
self.flagVolume(FLAG_DECRYPTED)
print "Decrypted %d files" % self.decryptedCount
print "Failed to unwrap keys for : ", self.failedToGetKey
print "Not encrypted files : %d" % len(self.notEncrypted)
def decryptFile(self, k,v):
if v.recordType == kHFSPlusFileRecord:
filename = getString(k)
cprotect = self.getXattr(v.data.fileID, "com.apple.system.cprotect")
if not cprotect:
self.notEncrypted.append(filename)
return
fk = self.getFileKeyForCprotect(cprotect)
if not fk:
self.failedToGetKey.append(filename)
return
print "Decrypting", filename
f = EMFFile(self, v.data.dataFork, v.data.fileID, fk)
f.decryptFile()
self.decryptedCount += 1
| Python |
from structs import *
"""
Probably buggy
"""
class BTree(object):
def __init__(self, file, keyStruct, dataStruct):
self.file = file
self.keyStruct = keyStruct
self.dataStruct = dataStruct
block0 = self.file.readBlock(0)
btnode = BTNodeDescriptor.parse(block0)
assert btnode.kind == kBTHeaderNode
self.header = BTHeaderRec.parse(block0[BTNodeDescriptor.sizeof():])
#TODO: do more testing when nodeSize != blockSize
self.nodeSize = self.header.nodeSize
self.nodesInBlock = file.blockSize / self.header.nodeSize
self.blocksForNode = self.header.nodeSize / file.blockSize
#print file.blockSize , self.header.nodeSize
self.lastRecordNumber = 0
type, (hdr, maprec) = self.readBtreeNode(0)
self.maprec = maprec
def isNodeInUse(self, nodeNumber):
thisByte = ord(self.maprec[nodeNumber / 8])
return (thisByte & (1 << (7 - (nodeNumber % 8)))) != 0
def readEmptySpace(self):
res = ""
z = 0
for i in xrange(self.header.totalNodes):
if not self.isNodeInUse(i):
z += 1
res += self.readNode(i)
assert z == self.header.freeNodes
return res
#convert construct structure to tuple
def getComparableKey(self, k):
raise "implement in subclass"
def compareKeys(self, k1, k2):
k2 = self.getComparableKey(k2)
if k1 == k2:
return 0
return -1 if k1 < k2 else 1
def printLeaf(self, key, data):
print key, data
def readNode(self, nodeNumber):
node = ""
for i in xrange(self.blocksForNode):
node += self.file.readBlock(nodeNumber * self.blocksForNode + i)
return node
def readBtreeNode(self, nodeNumber):
self.lastnodeNumber = nodeNumber
node = self.readNode(nodeNumber)
self.lastbtnode = btnode = BTNodeDescriptor.parse(node)
if btnode.kind == kBTHeaderNode:
#XXX
offsets = Array(btnode.numRecords, UBInt16("off")).parse(node[-2*btnode.numRecords:])
hdr = BTHeaderRec.parse(node[BTNodeDescriptor.sizeof():])
maprec = node[offsets[-3]:]
return kBTHeaderNode, [hdr, maprec]
elif btnode.kind == kBTIndexNode:
recs = []
offsets = Array(btnode.numRecords, UBInt16("off")).parse(node[-2*btnode.numRecords:])
for i in xrange(btnode.numRecords):
off = offsets[btnode.numRecords-i-1]
k = self.keyStruct.parse(node[off:])
off += 2 + k.keyLength
k.childNode = UBInt32("nodeNumber").parse(node[off:off+4])
recs.append(k)
return kBTIndexNode, recs
elif btnode.kind == kBTLeafNode:
recs = []
offsets = Array(btnode.numRecords, UBInt16("off")).parse(node[-2*btnode.numRecords:])
for i in xrange(btnode.numRecords):
off = offsets[btnode.numRecords-i-1]
k = self.keyStruct.parse(node[off:])
off += 2 + k.keyLength
d = self.dataStruct.parse(node[off:])
recs.append((k,d))
return kBTLeafNode, recs
else:
raise Exception("Invalid node type " + str(btnode))
def search(self, searchKey, node=None):
if node == None:
node = self.header.rootNode
type, stuff = self.readBtreeNode(node)
if type == kBTIndexNode:
for i in xrange(len(stuff)):
if self.compareKeys(searchKey, stuff[i]) < 0:
if i > 0:
i = i - 1
return self.search(searchKey, stuff[i].childNode)
return self.search(searchKey, stuff[len(stuff)-1].childNode)
elif type == kBTLeafNode:
self.lastRecordNumber = 0
for k,v in stuff:
res = self.compareKeys(searchKey, k)
if res == 0:
return k, v
if res < 0:
break
self.lastRecordNumber += 1
return None, None
def traverse(self, node=None, count=0, callback=None):
if node == None:
node = self.header.rootNode
type, stuff = self.readBtreeNode(node)
if type == kBTIndexNode:
for i in xrange(len(stuff)):
count += self.traverse(stuff[i].childNode, callback=callback)
elif type == kBTLeafNode:
for k,v in stuff:
if callback:
callback(k,v)
else:
self.printLeaf(k, v)
count += 1
return count
def traverseLeafNodes(self, callback=None):
nodeNumber = self.header.firstLeafNode
count = 0
while nodeNumber != 0:
_, stuff = self.readBtreeNode(nodeNumber)
count += len(stuff)
for k,v in stuff:
if callback:
callback(k,v)
else:
self.printLeaf(k, v)
nodeNumber = self.lastbtnode.fLink
return count
#XXX
def searchMultiple(self, searchKey, filterKeyFunction=lambda x:False):
self.search(searchKey)
nodeNumber = self.lastnodeNumber
recordNumber = self.lastRecordNumber
kv = []
while nodeNumber != 0:
_, stuff = self.readBtreeNode(nodeNumber)
for k,v in stuff[recordNumber:]:
if filterKeyFunction(k):
kv.append((k,v))
else:
return kv
nodeNumber = self.lastbtnode.fLink
recordNumber = 0
return kv
class CatalogTree(BTree):
def __init__(self, file):
super(CatalogTree,self).__init__(file, HFSPlusCatalogKey, HFSPlusCatalogData)
def printLeaf(self, k, d):
if d.recordType == kHFSPlusFolderRecord or d.recordType == kHFSPlusFileRecord:
print getString(k)
def getComparableKey(self, k2):
return (k2. parentID, getString(k2))
def searchByCNID(self, cnid):
threadk, threadd = self.search((cnid, ""))
return self.search((threadd.data.parentID, getString(threadd.data))) if threadd else (None, None)
def getFolderContents(self, cnid):
return self.searchMultiple((cnid, ""), lambda k:k.parentID == cnid)
def getRecordFromPath(self, path):
if not path.startswith("/"):
return None, None
if path == "/":
return self.searchByCNID(kHFSRootFolderID)
parentId=kHFSRootFolderID
for p in path.split("/")[1:]:
if p == "":
break
k,v = self.search((parentId, p))
if (k,v) == (None, None):
return None, None
if v.recordType == kHFSPlusFolderRecord:
parentId = v.data.folderID
else:
break
return k,v
class ExtentsOverflowTree(BTree):
def __init__(self, file):
super(ExtentsOverflowTree,self).__init__(file, HFSPlusExtentKey, HFSPlusExtentRecord)
def getComparableKey(self, k2):
return (k2.fileID, k2.forkType, k2.startBlock)
def searchExtents(self, fileID, forkType, startBlock):
return self.search((fileID, forkType, startBlock))
class AttributesTree(BTree):
def __init__(self, file):
super(AttributesTree,self).__init__(file, HFSPlusAttrKey, HFSPlusAttrData)
def printLeaf(self, k, d):
print k.fileID, getString(k), d.data.encode("hex")
def getComparableKey(self, k2):
return (k2.fileID, getString(k2))
def searchXattr(self, fileID, name):
k,v = self.search((fileID, name))
return v.data if v else None
def getAllXattrs(self, fileID):
res = {}
for k,v in self.searchMultiple((fileID, ""), lambda k:k.fileID == fileID):
res[getString(k)] = v.data
return res
| Python |
from construct import *
from construct.macros import UBInt64
"""
http://developer.apple.com/library/mac/#technotes/tn/tn1150.html
"""
def getString(obj):
return obj.HFSUniStr255.unicode
kHFSRootParentID = 1
kHFSRootFolderID = 2
kHFSExtentsFileID = 3
kHFSCatalogFileID = 4
kHFSBadBlockFileID = 5
kHFSAllocationFileID = 6
kHFSStartupFileID = 7
kHFSAttributesFileID = 8
kHFSRepairCatalogFileID = 14
kHFSBogusExtentFileID = 15
kHFSFirstUserCatalogNodeID = 16
kBTLeafNode = -1
kBTIndexNode = 0
kBTHeaderNode = 1
kBTMapNode = 2
kHFSPlusFolderRecord = 0x0001
kHFSPlusFileRecord = 0x0002
kHFSPlusFolderThreadRecord = 0x0003
kHFSPlusFileThreadRecord = 0x0004
kHFSPlusAttrInlineData = 0x10
kHFSPlusAttrForkData = 0x20
kHFSPlusAttrExtents = 0x30
kForkTypeData = 0
kForkTypeRsrc = 0xFF
kHFSVolumeHardwareLockBit = 7
kHFSVolumeUnmountedBit = 8
kHFSVolumeSparedBlocksBit = 9
kHFSVolumeNoCacheRequiredBit = 10
kHFSBootVolumeInconsistentBit = 11
kHFSCatalogNodeIDsReusedBit = 12
kHFSVolumeJournaledBit = 13
kHFSVolumeSoftwareLockBit = 15
DECMPFS_MAGIC = 0x636d7066 #cmpf
HFSPlusExtentDescriptor = Struct("HFSPlusExtentDescriptor",
UBInt32("startBlock"),
UBInt32("blockCount")
)
HFSPlusExtentRecord = Array(8,HFSPlusExtentDescriptor)
HFSPlusForkData = Struct("HFSPlusForkData",
UBInt64("logicalSize"),
UBInt32("clumpSize"),
UBInt32("totalBlocks"),
Array(8, HFSPlusExtentDescriptor)
)
HFSPlusVolumeHeader= Struct("HFSPlusVolumeHeader",
UBInt16("signature"),
UBInt16("version"),
UBInt32("attributes"),
UBInt32("lastMountedVersion"),
UBInt32("journalInfoBlock"),
UBInt32("createDate"),
UBInt32("modifyDate"),
UBInt32("backupDate"),
UBInt32("checkedDate"),
UBInt32("fileCount"),
UBInt32("folderCount"),
UBInt32("blockSize"),
UBInt32("totalBlocks"),
UBInt32("freeBlocks"),
UBInt32("nextAllocation"),
UBInt32("rsrcClumpSize"),
UBInt32("dataClumpSize"),
UBInt32("nextCatalogID"),
UBInt32("writeCount"),
UBInt64("encodingsBitmap"),
Array(8, UBInt32("finderInfo")),
Struct("allocationFile", Embed(HFSPlusForkData)),
Struct("extentsFile", Embed(HFSPlusForkData)),
Struct("catalogFile", Embed(HFSPlusForkData)),
Struct("attributesFile", Embed(HFSPlusForkData)),
Struct("startupFile", Embed(HFSPlusForkData)),
)
BTNodeDescriptor = Struct("BTNodeDescriptor",
UBInt32("fLink"),
UBInt32("bLink"),
SBInt8("kind"),
UBInt8("height"),
UBInt16("numRecords"),
UBInt16("reserved")
)
BTHeaderRec = Struct("BTHeaderRec",
UBInt16("treeDepth"),
UBInt32("rootNode"),
UBInt32("leafRecords"),
UBInt32("firstLeafNode"),
UBInt32("lastLeafNode"),
UBInt16("nodeSize"),
UBInt16("maxKeyLength"),
UBInt32("totalNodes"),
UBInt32("freeNodes"),
UBInt16("reserved1"),
UBInt32("clumpSize"),
UBInt8("btreeType"),
UBInt8("keyCompareType"),
UBInt32("attributes"),
Array(16, UBInt32("reserved3"))
)
HFSUniStr255 = Struct("HFSUniStr255",
UBInt16("length"),
String("unicode", lambda ctx: ctx["length"] * 2, encoding="utf-16-be")
)
HFSPlusAttrKey = Struct("HFSPlusAttrKey",
UBInt16("keyLength"),
UBInt16("pad"),
UBInt32("fileID"),
UBInt32("startBlock"),
HFSUniStr255,
#UBInt32("nodeNumber")
)
HFSPlusAttrData = Struct("HFSPlusAttrData",
UBInt32("recordType"),
Array(2, UBInt32("reserved")),
UBInt32("size"),
MetaField("data", lambda ctx: ctx["size"])
)
HFSPlusCatalogKey = Struct("HFSPlusCatalogKey",
UBInt16("keyLength"),
UBInt32("parentID"),
HFSUniStr255
)
HFSPlusBSDInfo = Struct("HFSPlusBSDInfo",
UBInt32("ownerID"),
UBInt32("groupID"),
UBInt8("adminFlags"),
UBInt8("ownerFlags"),
UBInt16("fileMode"),
UBInt32("union_special")
)
Point = Struct("Point",
SBInt16("v"),
SBInt16("h")
)
Rect = Struct("Rect",
SBInt16("top"),
SBInt16("left"),
SBInt16("bottom"),
SBInt16("right")
)
FileInfo = Struct("FileInfo",
UBInt32("fileType"),
UBInt32("fileCreator"),
UBInt16("finderFlags"),
Point,
UBInt16("reservedField")
)
ExtendedFileInfo = Struct("ExtendedFileInfo",
Array(4, SBInt16("reserved1")),
UBInt16("extendedFinderFlags"),
SBInt16("reserved2"),
SBInt32("putAwayFolderID")
)
FolderInfo = Struct("FolderInfo",
Rect,
UBInt16("finderFlags"),
Point,
UBInt16("reservedField")
)
ExtendedFolderInfo = Struct("ExtendedFolderInfo",
Point,
SBInt32("reserved1"),
UBInt16("extendedFinderFlags"),
SBInt16("reserved2"),
SBInt32("putAwayFolderID")
)
HFSPlusCatalogFolder = Struct("HFSPlusCatalogFolder",
UBInt16("flags"),
UBInt32("valence"),
UBInt32("folderID"),
UBInt32("createDate"),
UBInt32("contentModDate"),
UBInt32("attributeModDate"),
UBInt32("accessDate"),
UBInt32("backupDate"),
HFSPlusBSDInfo,
FolderInfo,
ExtendedFolderInfo,
UBInt32("textEncoding"),
UBInt32("reserved")
)
HFSPlusCatalogFile = Struct("HFSPlusCatalogFile",
UBInt16("flags"),
UBInt32("reserved1"),
UBInt32("fileID"),
UBInt32("createDate"),
UBInt32("contentModDate"),
UBInt32("attributeModDate"),
UBInt32("accessDate"),
UBInt32("backupDate"),
HFSPlusBSDInfo,
FileInfo,
ExtendedFileInfo,
UBInt32("textEncoding"),
UBInt32("reserved2"),
Struct("dataFork", Embed(HFSPlusForkData)),
Struct("resourceFork", Embed(HFSPlusForkData))
)
HFSPlusCatalogThread = Struct("HFSPlusCatalogThread",
SBInt16("reserved"),
UBInt32("parentID"),
HFSUniStr255,
)
HFSPlusCatalogData = Struct("HFSPlusCatalogData",
UBInt16("recordType"),
Switch("data", lambda ctx: ctx["recordType"],
{
kHFSPlusFolderRecord : HFSPlusCatalogFolder,
kHFSPlusFileRecord : HFSPlusCatalogFile,
kHFSPlusFolderThreadRecord: HFSPlusCatalogThread,
kHFSPlusFileThreadRecord: HFSPlusCatalogThread
},
#default=HFSPlusCatalogFolder #XXX: should not reach
)
)
HFSPlusExtentKey = Struct("HFSPlusExtentKey",
UBInt16("keyLength"),
UBInt8("forkType"),
UBInt8("pad"),
UBInt32("fileID"),
UBInt32("startBlock")
)
HFSPlusDecmpfs = Struct("HFSPlusDecmpfs ",
ULInt32("compression_magic"),
ULInt32("compression_type"),
ULInt64("uncompressed_size"),
)
HFSPlusCmpfRsrcHead = Struct("HFSPlusCmpfRsrcHead",
UBInt32("headerSize"),
UBInt32("totalSize"),
UBInt32("dataSize"),
UBInt32("flags")
)
HFSPlusCmpfRsrcBlock = Struct("HFSPlusCmpfRsrcBlock",
ULInt32("offset"),
ULInt32("size")
)
HFSPlusCmpfRsrcBlockHead = Struct("HFSPlusCmpfRsrcBlockHead",
UBInt32("dataSize"),
ULInt32("numBlocks"),
Array(lambda ctx:ctx["numBlocks"], HFSPlusCmpfRsrcBlock)
)
HFSPlusCmpfEnd = Struct("HFSPlusCmpfEnd",
Array(6, UBInt32("pad")),
UBInt16("unk1"),
UBInt16("unk2"),
UBInt16("unk3"),
UBInt32("magic"),
UBInt32("flags"),
UBInt64("size"),
UBInt32("unk4")
)
"""
Journal stuff
"""
JournalInfoBlock = Struct("JournalInfoBlock",
UBInt32("flags"),
Array(8, UBInt32("device_signature")),
UBInt64("offset"),
UBInt64("size"),
Array(32, UBInt32("reserved"))
)
journal_header = Struct("journal_header",
ULInt32("magic"),
ULInt32("endian"),
ULInt64("start"),
ULInt64("end"),
ULInt64("size"),
ULInt32("blhdr_size"),
ULInt32("checksum"),
ULInt32("jhdr_size")
)
block_info = Struct("block_info",
ULInt64("bnum"),
ULInt32("bsize"),
ULInt32("next")
)
block_list_header = Struct("block_list_header",
ULInt16("max_blocks"),
ULInt16("num_blocks"),
ULInt32("bytes_used"),
SLInt32("checksum"),
UBInt32("pad"),
Array(lambda ctx:ctx["num_blocks"], block_info)
)
| Python |
import plistlib
import os
from keystore.keybag import Keybag
from keychain.keychain4 import Keychain4
from keychain.managedconfiguration import bruteforce_old_pass
from util.ramdiskclient import RamdiskToolClient
from util import write_file
def checkPasscodeComplexity(rdclient):
pl = rdclient.downloadFile("/mnt2/mobile/Library/ConfigurationProfiles/UserSettings.plist")
if not pl:
print "Failed to download UserSettings.plist, assuming simple passcode"
return 0
pl = plistlib.readPlistFromString(pl)
print "passcodeKeyboardComplexity :", pl["restrictedValue"]["passcodeKeyboardComplexity"]
return pl["restrictedValue"]["passcodeKeyboardComplexity"]["value"]
def bf_system():
client = RamdiskToolClient()
di = client.getDeviceInfos()
devicedir = di["udid"]
if os.getcwd().find(devicedir) == -1:
try:
os.mkdir(devicedir)
except:
pass
os.chdir(devicedir)
key835 = di.get("key835").decode("hex")
systembag = client.getSystemKeyBag()
kbkeys = systembag["KeyBagKeys"].data
kb = Keybag.createWithDataSignBlob(kbkeys, key835)
keybags = di.setdefault("keybags", {})
kbuuid = kb.uuid.encode("hex")
print "Keybag UUID :", kbuuid
if True and keybags.has_key(kbuuid) and keybags[kbuuid].has_key("passcodeKey"):
print "We've already seen this keybag"
passcodeKey = keybags[kbuuid].get("passcodeKey").decode("hex")
print kb.unlockWithPasscodeKey(passcodeKey)
kb.printClassKeys()
else:
keybags[kbuuid] = {"KeyBagKeys": systembag["KeyBagKeys"]}
di["KeyBagKeys"] = systembag["KeyBagKeys"]
di.save()
if checkPasscodeComplexity(client) == 0:
print "Trying all 4-digits passcodes..."
bf = client.bruteforceKeyBag(systembag["KeyBagKeys"].data)
if bf:
di.update(bf)
keybags[kbuuid].update(bf)
print bf
print kb.unlockWithPasscodeKey(bf.get("passcodeKey").decode("hex"))
kb.printClassKeys()
di["classKeys"] = kb.getClearClassKeysDict()
di.save()
else:
print "Complex passcode used !"
return
#keychain_blob = client.downloadFile("/private/var/Keychains/keychain-2.db")
keychain_blob = client.downloadFile("/mnt2/Keychains/keychain-2.db")
write_file("keychain-2.db", keychain_blob)
print "Downloaded keychain database, use keychain_tool.py to decrypt secrets"
bf_system()
| Python |
import os
import plistlib
from keystore.keybag import Keybag
from util.ramdiskclient import RamdiskToolClient
"""
this wont work on iOS 5 unless the passcode was already bruteforced
"""
def escrow():
client = RamdiskToolClient()
di = client.getDeviceInfos()
key835 = di.get("key835").decode("hex")
plist = os.environ["ALLUSERSPROFILE"] + "/Apple/Lockdown/%s.plist" % di["udid"]
lockdown = plistlib.readPlist(plist)
kb = Keybag.createWithDataSignBlob(lockdown["EscrowBag"].data, key835)
keybags = di.setdefault("keybags", {})
kbuuid = kb.uuid.encode("hex")
if not keybags.has_key(kbuuid):
print lockdown["HostID"]
res = client.getEscrowRecord(lockdown["HostID"])
bagkey = res.get("BagKey")
print "Bag key" + bagkey.data.encode("hex")
res = client.getPasscodeKey(lockdown["EscrowBag"].data, bagkey)
print res
passcodeKey = res["passcodeKey"].decode("hex")
keybags[kbuuid] = {"KeyBagKeys": lockdown["EscrowBag"],
"passcode": bagkey,
"passcodeKey": passcodeKey.encode("hex")}
pl.update(keybags[kbuuid])
else:
passcodeKey = keybags[kbuuid].get("passcodeKey").decode("hex")
print kb.unlockWithPasscodeKey(passcodeKey)
kb.printClassKeys()
escrow() | Python |
import os
import sys
from hfs.emf import EMFVolume
from hfs.journal import do_emf_carving
if __name__ == "__main__":
if len(sys.argv) < 2:
print "Usage: emf_undelete.py disk_image.bin"
sys.exit(0)
filename = sys.argv[1]
volume = EMFVolume(filename)
dirname = os.path.dirname(filename)
if dirname == "":
dirname = "."
outdir = dirname + "/" + volume.volumeID().encode("hex") + "_" + os.path.basename(filename)
carveokdir = outdir + "/undelete/"
carvenokdir = outdir + "/junk/"
try:
os.makedirs(carveokdir)
os.makedirs(carvenokdir)
except:
pass
do_emf_carving(volume, carveokdir, carvenokdir)
| Python |
import plistlib
import sys
from optparse import OptionParser
from keystore.keybag import Keybag
from keychain import keychain_load
from keychain.managedconfiguration import bruteforce_old_pass
def main():
parser = OptionParser(usage="%prog keychain.db keyfile.plist")
parser.add_option("-d", "--display", dest="display", action="store_true", default=False,
help="Show keychain items on stdout")
parser.add_option("-s", "--sanitize", dest="sanitize", action="store_true", default=False,
help="Hide secrets on stdout with ***")
parser.add_option("-p", "--passwords", dest="passwords", action="store_true", default=False,
help="Save generic & internet passwords as CSV file")
parser.add_option("-c", "--certs", dest="certs", action="store_true", default=False,
help="Extract certificates and keys")
parser.add_option("-o", "--old", dest="oldpass", action="store_true", default=False,
help="Bruteforce old passcodes")
(options, args) = parser.parse_args()
if len(args) < 2:
parser.print_help()
return
p = plistlib.readPlist(args[1])
kb = Keybag.createWithPlist(p)
k = keychain_load(args[0], kb, p["key835"].decode("hex"))
if options.display:
k.print_all(options.sanitize)
if options.passwords:
k.save_passwords()
if options.certs:
k.save_certs_keys()
if options.oldpass:
mc = k.get_managed_configuration()
if not mc:
print "Managed configuration not found"
return
print "Bruteforcing %d old passcodes" % len(mc.get("history",[]))
for h in mc["history"]:
p = bruteforce_old_pass(h)
if p:
print "Found : %s" % p
else:
print "Not Found"
if __name__ == "__main__":
main()
| Python |
from optparse import OptionParser
from hfs.emf import EMFVolume
def main():
parser = OptionParser(usage="emf_decrypter.py disk_image.bin")
parser.add_option("-w", "--nowrite", dest="write", action="store_false", default=True,
help="disable modifications of input file, for testing")
(options, args) = parser.parse_args()
if len(args) < 1:
parser.print_help()
return
v = EMFVolume(args[0], write=options.write)
if options.write:
print "WARNING ! This tool will modify the hfs image and possibly wreck it if something goes wrong !"
print "Make sure to backup the image before proceeding"
print "You can use the --nowrite option to do a dry run instead"
else:
print "Test mode : the input file will not be modified"
print "Press a key to continue or CTRL-C to abort"
raw_input()
v.decryptAllFiles()
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/env python
import sys, os
from PyQt4 import QtGui, QtCore
from keychain.keychain_backup4 import KeychainBackup4
from Crypto.Cipher import AES
from crypto.aeswrap import AESUnwrap
from backups.backup4 import MBDB, getBackupKeyBag
from pprint import pprint
class KeychainTreeWidget(QtGui.QTreeWidget):
def __init__(self, parent=None):
QtGui.QTreeWidget.__init__(self, parent)
self.setGeometry(10, 10, 780, 380)
self.header().hide()
self.setColumnCount(2)
class KeychainTreeWidgetItem(QtGui.QTreeWidgetItem):
def __init__(self, title):
QtGui.QTreeWidgetItem.__init__(self, [title])
fnt = self.font(0)
fnt.setBold(True)
self.setFont(0, fnt)
self.setColors()
def setText(self, column, title):
QtGui.QTreeWidgetItem.setText(self, column, title)
def setColors(self):
self.setForeground(0, QtGui.QBrush(QtGui.QColor(80, 80, 80)))
self.setBackground(0, QtGui.QBrush(QtGui.QColor(230, 230, 230)))
self.setBackground(1, QtGui.QBrush(QtGui.QColor(230, 230, 230)))
class LockedKeychainTreeWidgetItem(KeychainTreeWidgetItem):
def setColors(self):
self.setForeground(0, QtGui.QBrush(QtGui.QColor(255, 80, 80)))
self.setBackground(0, QtGui.QBrush(QtGui.QColor(255, 230, 230)))
self.setBackground(1, QtGui.QBrush(QtGui.QColor(255, 230, 230)))
class KeychainWindow(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setGeometry(100, 100, 800, 400)
self.setWindowTitle('Keychain Explorer')
self.passwordTree = KeychainTreeWidget(parent=self)
def setGenericPasswords(self, pwds):
self.genericPasswords = pwds
self.passwordItems = KeychainTreeWidgetItem('Generic Passwords')
for pwd in self.genericPasswords:
if len(pwd['acct']) > 0:
item_title = '%s (%s)' % (pwd['svce'], pwd['acct'])
else:
item_title = pwd['svce']
if pwd['data'] is None:
item = LockedKeychainTreeWidgetItem(item_title)
else:
item = KeychainTreeWidgetItem(item_title)
item.addChild(QtGui.QTreeWidgetItem(['Service', pwd['svce']]))
item.addChild(QtGui.QTreeWidgetItem(['Account', pwd['acct']]))
if pwd['data'] is not None:
item.addChild(QtGui.QTreeWidgetItem(['Data', pwd['data']]))
else:
item.addChild(QtGui.QTreeWidgetItem(['Data', 'N/A']))
item.addChild(QtGui.QTreeWidgetItem(['Access Group', pwd['agrp']]))
self.passwordItems.addChild(item)
self.passwordTree.addTopLevelItem(self.passwordItems)
self.passwordTree.expandAll()
self.passwordTree.resizeColumnToContents(0)
def setInternetPasswords(self, pwds):
self.internetPasswords = pwds
self.internetPasswordItems = KeychainTreeWidgetItem('Internet Passwords')
for pwd in pwds:
item_title = '%s (%s)' % (pwd['srvr'], pwd['acct'])
item = KeychainTreeWidgetItem(item_title)
item.addChild(QtGui.QTreeWidgetItem(['Server', pwd['srvr']]))
item.addChild(QtGui.QTreeWidgetItem(['Account', pwd['acct']]))
if pwd['data'] is not None:
item.addChild(QtGui.QTreeWidgetItem(['Data', pwd['data']]))
else:
item.addChild(QtGui.QTreeWidgetItem(['Data', 'N/A']))
item.addChild(QtGui.QTreeWidgetItem(['Port', str(pwd['port'])]))
item.addChild(QtGui.QTreeWidgetItem(['Access Group', pwd['agrp']]))
self.internetPasswordItems.addChild(item)
self.passwordTree.addTopLevelItem(self.internetPasswordItems)
self.passwordTree.expandAll()
self.passwordTree.resizeColumnToContents(0)
def warn(msg):
print "WARNING: %s" % msg
def main():
app = QtGui.QApplication(sys.argv)
init_path = "{0:s}/Apple Computer/MobileSync/Backup".format(os.getenv('APPDATA'))
dirname = QtGui.QFileDialog.getExistingDirectory(None, "Select iTunes backup directory", init_path)
kb = getBackupKeyBag(dirname, 'pouet') #XXX: hardcoded password for demo
if not kb:
warn("Backup keybag unlock fail : wrong passcode?")
return
db = MBDB(dirname)
keychain_filename, keychain_record = db.get_file_by_name('keychain-backup.plist')
f = file(dirname + '/' + keychain_filename, 'rb')
keychain_data = f.read()
f.close()
if keychain_record.encryption_key is not None: # file is encrypted
if kb.classKeys.has_key(keychain_record.protection_class):
kek = kb.classKeys[keychain_record.protection_class]['KEY']
k = AESUnwrap(kek, keychain_record.encryption_key[4:])
if k is not None:
c = AES.new(k, AES.MODE_CBC)
keychain_data = c.decrypt(keychain_data)
padding = keychain_data[keychain_record.size:]
if len(padding) > AES.block_size or padding != chr(len(padding)) * len(padding):
warn("Incorrect padding for file %s" % keychain_record.path)
keychain_data = keychain_data[:keychain_record.size]
else:
warn("Cannot unwrap key")
else:
warn("Cannot load encryption key for file %s" % f)
f = file('keychain.tmp', 'wb')
f.write(keychain_data)
f.close()
# kc = KeychainBackup4('keychain-backup.plist', kb)
kc = KeychainBackup4('keychain.tmp', kb)
pwds = kc.get_passwords()
inet_pwds = kc.get_inet_passwords()
print inet_pwds
qb = KeychainWindow()
qb.setGenericPasswords(pwds)
qb.setInternetPasswords(inet_pwds)
qb.show()
sys.exit(app.exec_())
pass
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# usbmux.py - usbmux client library for Python
#
# Copyright (C) 2009 Hector Martin "marcan" <hector@marcansoft.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 or version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
import socket, struct, select, sys
try:
import plistlib
haveplist = True
except:
haveplist = False
class MuxError(Exception):
pass
class MuxVersionError(MuxError):
pass
class SafeStreamSocket:
def __init__(self, address, family):
self.sock = socket.socket(family, socket.SOCK_STREAM)
self.sock.connect(address)
def send(self, msg):
totalsent = 0
while totalsent < len(msg):
sent = self.sock.send(msg[totalsent:])
if sent == 0:
raise MuxError("socket connection broken")
totalsent = totalsent + sent
def recv(self, size):
msg = ''
while len(msg) < size:
chunk = self.sock.recv(size-len(msg))
if chunk == '':
raise MuxError("socket connection broken")
msg = msg + chunk
return msg
class MuxDevice(object):
def __init__(self, devid, usbprod, serial, location):
self.devid = devid
self.usbprod = usbprod
self.serial = serial
self.location = location
def __str__(self):
return "<MuxDevice: ID %d ProdID 0x%04x Serial '%s' Location 0x%x>"%(self.devid, self.usbprod, self.serial, self.location)
class BinaryProtocol(object):
TYPE_RESULT = 1
TYPE_CONNECT = 2
TYPE_LISTEN = 3
TYPE_DEVICE_ADD = 4
TYPE_DEVICE_REMOVE = 5
VERSION = 0
def __init__(self, socket):
self.socket = socket
self.connected = False
def _pack(self, req, payload):
if req == self.TYPE_CONNECT:
return struct.pack("IH", payload['DeviceID'], payload['PortNumber']) + "\x00\x00"
elif req == self.TYPE_LISTEN:
return ""
else:
raise ValueError("Invalid outgoing request type %d"%req)
def _unpack(self, resp, payload):
if resp == self.TYPE_RESULT:
return {'Number':struct.unpack("I", payload)[0]}
elif resp == self.TYPE_DEVICE_ADD:
devid, usbpid, serial, pad, location = struct.unpack("IH256sHI", payload)
serial = serial.split("\0")[0]
return {'DeviceID': devid, 'Properties': {'LocationID': location, 'SerialNumber': serial, 'ProductID': usbpid}}
elif resp == self.TYPE_DEVICE_REMOVE:
devid = struct.unpack("I", payload)[0]
return {'DeviceID': devid}
else:
raise MuxError("Invalid incoming request type %d"%req)
def sendpacket(self, req, tag, payload={}):
payload = self._pack(req, payload)
if self.connected:
raise MuxError("Mux is connected, cannot issue control packets")
length = 16 + len(payload)
data = struct.pack("IIII", length, self.VERSION, req, tag) + payload
self.socket.send(data)
def getpacket(self):
if self.connected:
raise MuxError("Mux is connected, cannot issue control packets")
dlen = self.socket.recv(4)
dlen = struct.unpack("I", dlen)[0]
body = self.socket.recv(dlen - 4)
version, resp, tag = struct.unpack("III",body[:0xc])
if version != self.VERSION:
raise MuxVersionError("Version mismatch: expected %d, got %d"%(self.VERSION,version))
payload = self._unpack(resp, body[0xc:])
return (resp, tag, payload)
class PlistProtocol(BinaryProtocol):
TYPE_RESULT = "Result"
TYPE_CONNECT = "Connect"
TYPE_LISTEN = "Listen"
TYPE_DEVICE_ADD = "Attached"
TYPE_DEVICE_REMOVE = "Detached" #???
TYPE_PLIST = 8
VERSION = 1
def __init__(self, socket):
if not haveplist:
raise Exception("You need the plistlib module")
BinaryProtocol.__init__(self, socket)
def _pack(self, req, payload):
return payload
def _unpack(self, resp, payload):
return payload
def sendpacket(self, req, tag, payload={}):
payload['ClientVersionString'] = 'usbmux.py by marcan'
if isinstance(req, int):
req = [self.TYPE_CONNECT, self.TYPE_LISTEN][req-2]
payload['MessageType'] = req
payload['ProgName'] = 'tcprelay'
BinaryProtocol.sendpacket(self, self.TYPE_PLIST, tag, plistlib.writePlistToString(payload))
def getpacket(self):
resp, tag, payload = BinaryProtocol.getpacket(self)
if resp != self.TYPE_PLIST:
raise MuxError("Received non-plist type %d"%resp)
payload = plistlib.readPlistFromString(payload)
return payload['MessageType'], tag, payload
class MuxConnection(object):
def __init__(self, socketpath, protoclass):
self.socketpath = socketpath
if sys.platform in ['win32', 'cygwin']:
family = socket.AF_INET
address = ('127.0.0.1', 27015)
else:
family = socket.AF_UNIX
address = self.socketpath
self.socket = SafeStreamSocket(address, family)
self.proto = protoclass(self.socket)
self.pkttag = 1
self.devices = []
def _getreply(self):
while True:
resp, tag, data = self.proto.getpacket()
if resp == self.proto.TYPE_RESULT:
return tag, data
else:
raise MuxError("Invalid packet type received: %d"%resp)
def _processpacket(self):
resp, tag, data = self.proto.getpacket()
if resp == self.proto.TYPE_DEVICE_ADD:
self.devices.append(MuxDevice(data['DeviceID'], data['Properties']['ProductID'], data['Properties']['SerialNumber'], data['Properties']['LocationID']))
elif resp == self.proto.TYPE_DEVICE_REMOVE:
for dev in self.devices:
if dev.devid == data['DeviceID']:
self.devices.remove(dev)
elif resp == self.proto.TYPE_RESULT:
raise MuxError("Unexpected result: %d"%resp)
else:
raise MuxError("Invalid packet type received: %d"%resp)
def _exchange(self, req, payload={}):
mytag = self.pkttag
self.pkttag += 1
self.proto.sendpacket(req, mytag, payload)
recvtag, data = self._getreply()
if recvtag != mytag:
raise MuxError("Reply tag mismatch: expected %d, got %d"%(mytag, recvtag))
return data['Number']
def listen(self):
ret = self._exchange(self.proto.TYPE_LISTEN)
if ret != 0:
raise MuxError("Listen failed: error %d"%ret)
def process(self, timeout=None):
if self.proto.connected:
raise MuxError("Socket is connected, cannot process listener events")
rlo, wlo, xlo = select.select([self.socket.sock], [], [self.socket.sock], timeout)
if xlo:
self.socket.sock.close()
raise MuxError("Exception in listener socket")
if rlo:
self._processpacket()
def connect(self, device, port):
ret = self._exchange(self.proto.TYPE_CONNECT, {'DeviceID':device.devid, 'PortNumber':((port<<8) & 0xFF00) | (port>>8)})
if ret != 0:
raise MuxError("Connect failed: error %d"%ret)
self.proto.connected = True
return self.socket.sock
def close(self):
self.socket.sock.close()
class USBMux(object):
def __init__(self, socketpath=None):
if socketpath is None:
if sys.platform == 'darwin':
socketpath = "/var/run/usbmuxd"
else:
socketpath = "/var/run/usbmuxd"
self.socketpath = socketpath
self.listener = MuxConnection(socketpath, BinaryProtocol)
try:
self.listener.listen()
self.version = 0
self.protoclass = BinaryProtocol
except MuxVersionError:
self.listener = MuxConnection(socketpath, PlistProtocol)
self.listener.listen()
self.protoclass = PlistProtocol
self.version = 1
self.devices = self.listener.devices
def process(self, timeout=None):
self.listener.process(timeout)
def connect(self, device, port):
connector = MuxConnection(self.socketpath, self.protoclass)
return connector.connect(device, port)
if __name__ == "__main__":
mux = USBMux()
print "Waiting for devices..."
if not mux.devices:
mux.process(0.1)
while True:
print "Devices:"
for dev in mux.devices:
print dev
mux.process()
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# tcprelay.py - TCP connection relay for usbmuxd
#
# Copyright (C) 2009 Hector Martin "marcan" <hector@marcansoft.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 or version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
import usbmux
import SocketServer
import select
from optparse import OptionParser
import sys
import threading
class SocketRelay(object):
def __init__(self, a, b, maxbuf=65535):
self.a = a
self.b = b
self.atob = ""
self.btoa = ""
self.maxbuf = maxbuf
def handle(self):
while True:
rlist = []
wlist = []
xlist = [self.a, self.b]
if self.atob:
wlist.append(self.b)
if self.btoa:
wlist.append(self.a)
if len(self.atob) < self.maxbuf:
rlist.append(self.a)
if len(self.btoa) < self.maxbuf:
rlist.append(self.b)
rlo, wlo, xlo = select.select(rlist, wlist, xlist)
if xlo:
return
if self.a in wlo:
n = self.a.send(self.btoa)
self.btoa = self.btoa[n:]
if self.b in wlo:
n = self.b.send(self.atob)
self.atob = self.atob[n:]
if self.a in rlo:
s = self.a.recv(self.maxbuf - len(self.atob))
if not s:
return
self.atob += s
if self.b in rlo:
s = self.b.recv(self.maxbuf - len(self.btoa))
if not s:
return
self.btoa += s
#print "Relay iter: %8d atob, %8d btoa, lists: %r %r %r"%(len(self.atob), len(self.btoa), rlo, wlo, xlo)
class TCPRelay(SocketServer.BaseRequestHandler):
def handle(self):
print "Incoming connection to %d"%self.server.server_address[1]
mux = usbmux.USBMux(options.sockpath)
print "Waiting for devices..."
if not mux.devices:
mux.process(1.0)
if not mux.devices:
print "No device found"
self.request.close()
return
dev = mux.devices[0]
print "Connecting to device %s"%str(dev)
dsock = mux.connect(dev, self.server.rport)
lsock = self.request
print "Connection established, relaying data"
try:
fwd = SocketRelay(dsock, lsock, self.server.bufsize * 1024)
fwd.handle()
finally:
dsock.close()
lsock.close()
print "Connection closed"
class TCPServer(SocketServer.TCPServer):
allow_reuse_address = True
class ThreadedTCPServer(SocketServer.ThreadingMixIn, TCPServer):
pass
HOST = "localhost"
parser = OptionParser(usage="usage: %prog [OPTIONS] RemotePort[:LocalPort] [RemotePort[:LocalPort]]...")
parser.add_option("-t", "--threaded", dest='threaded', action='store_true', default=False, help="use threading to handle multiple connections at once")
parser.add_option("-b", "--bufsize", dest='bufsize', action='store', metavar='KILOBYTES', type='int', default=128, help="specify buffer size for socket forwarding")
parser.add_option("-s", "--socket", dest='sockpath', action='store', metavar='PATH', type='str', default=None, help="specify the path of the usbmuxd socket")
options, args = parser.parse_args()
serverclass = TCPServer
if options.threaded:
serverclass = ThreadedTCPServer
if len(args) == 0:
parser.print_help()
sys.exit(1)
ports = []
for arg in args:
try:
if ':' in arg:
rport, lport = arg.split(":")
rport = int(rport)
lport = int(lport)
ports.append((rport, lport))
else:
ports.append((int(arg), int(arg)))
except:
parser.print_help()
sys.exit(1)
servers=[]
for rport, lport in ports:
print "Forwarding local port %d to remote port %d"%(lport, rport)
server = serverclass((HOST, lport), TCPRelay)
server.rport = rport
server.bufsize = options.bufsize
servers.append(server)
alive = True
while alive:
try:
rl, wl, xl = select.select(servers, [], [])
for server in rl:
server.handle_request()
except:
alive = False
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
This is the "File Uploader" for Python
"""
import os
from fckutil import *
from fckcommands import * # default command's implementation
from fckconnector import FCKeditorConnectorBase # import base connector
import config as Config
class FCKeditorQuickUpload( FCKeditorConnectorBase,
UploadFileCommandMixin,
BaseHttpMixin, BaseHtmlMixin):
def doResponse(self):
"Main function. Process the request, set headers and return a string as response."
# Check if this connector is disabled
if not(Config.Enabled):
return self.sendUploadResults(1, "This file uploader is disabled. Please check the \"editor/filemanager/connectors/py/config.py\"")
command = 'QuickUpload'
# The file type (from the QueryString, by default 'File').
resourceType = self.request.get('Type','File')
currentFolder = getCurrentFolder(self.request.get("CurrentFolder",""))
# Check for invalid paths
if currentFolder is None:
return self.sendUploadResults(102, '', '', "")
# Check if it is an allowed command
if ( not command in Config.ConfigAllowedCommands ):
return self.sendUploadResults( 1, '', '', 'The %s command isn\'t allowed' % command )
if ( not resourceType in Config.ConfigAllowedTypes ):
return self.sendUploadResults( 1, '', '', 'Invalid type specified' )
# Setup paths
self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType]
self.webUserFilesFolder = Config.QuickUploadPath[resourceType]
if not self.userFilesFolder: # no absolute path given (dangerous...)
self.userFilesFolder = mapServerPath(self.environ,
self.webUserFilesFolder)
# Ensure that the directory exists.
if not os.path.exists(self.userFilesFolder):
try:
self.createServerFoldercreateServerFolder( self.userFilesFolder )
except:
return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ")
# File upload doesn't have to return XML, so intercept here
return self.uploadFile(resourceType, currentFolder)
# Running from command line (plain old CGI)
if __name__ == '__main__':
try:
# Create a Connector Instance
conn = FCKeditorQuickUpload()
data = conn.doResponse()
for header in conn.headers:
if not header is None:
print '%s: %s' % header
print
print data
except:
print "Content-Type: text/plain"
print
import cgi
cgi.print_exception()
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
"""
from time import gmtime, strftime
import string
def escape(text, replace=string.replace):
"""
Converts the special characters '<', '>', and '&'.
RFC 1866 specifies that these characters be represented
in HTML as < > and & respectively. In Python
1.5 we use the new string.replace() function for speed.
"""
text = replace(text, '&', '&') # must be done 1st
text = replace(text, '<', '<')
text = replace(text, '>', '>')
text = replace(text, '"', '"')
return text
def convertToXmlAttribute(value):
if (value is None):
value = ""
return escape(value)
class BaseHttpMixin(object):
def setHttpHeaders(self, content_type='text/xml'):
"Purpose: to prepare the headers for the xml to return"
# Prevent the browser from caching the result.
# Date in the past
self.setHeader('Expires','Mon, 26 Jul 1997 05:00:00 GMT')
# always modified
self.setHeader('Last-Modified',strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime()))
# HTTP/1.1
self.setHeader('Cache-Control','no-store, no-cache, must-revalidate')
self.setHeader('Cache-Control','post-check=0, pre-check=0')
# HTTP/1.0
self.setHeader('Pragma','no-cache')
# Set the response format.
self.setHeader( 'Content-Type', content_type + '; charset=utf-8' )
return
class BaseXmlMixin(object):
def createXmlHeader(self, command, resourceType, currentFolder, url):
"Purpose: returns the xml header"
self.setHttpHeaders()
# Create the XML document header
s = """<?xml version="1.0" encoding="utf-8" ?>"""
# Create the main connector node
s += """<Connector command="%s" resourceType="%s">""" % (
command,
resourceType
)
# Add the current folder node
s += """<CurrentFolder path="%s" url="%s" />""" % (
convertToXmlAttribute(currentFolder),
convertToXmlAttribute(url),
)
return s
def createXmlFooter(self):
"Purpose: returns the xml footer"
return """</Connector>"""
def sendError(self, number, text):
"Purpose: in the event of an error, return an xml based error"
self.setHttpHeaders()
return ("""<?xml version="1.0" encoding="utf-8" ?>""" +
"""<Connector>""" +
self.sendErrorNode (number, text) +
"""</Connector>""" )
def sendErrorNode(self, number, text):
return """<Error number="%s" text="%s" />""" % (number, convertToXmlAttribute(text))
class BaseHtmlMixin(object):
def sendUploadResults( self, errorNo = 0, fileUrl = '', fileName = '', customMsg = '' ):
self.setHttpHeaders("text/html")
"This is the function that sends the results of the uploading process"
return """<script type="text/javascript">
(function()
{
var d = document.domain ;
while ( true )
{
// Test if we can access a parent property.
try
{
var test = window.top.opener.document.domain ;
break ;
}
catch( e ) {}
// Remove a domain part: www.mytest.example.com => mytest.example.com => example.com ...
d = d.replace( /.*?(?:\.|$)/, '' ) ;
if ( d.length == 0 )
break ; // It was not able to detect the domain.
try
{
document.domain = d ;
}
catch (e)
{
break ;
}
}
})() ;
window.parent.OnUploadCompleted(%(errorNumber)s,"%(fileUrl)s","%(fileName)s","%(customMsg)s");
</script>""" % {
'errorNumber': errorNo,
'fileUrl': fileUrl.replace ('"', '\\"'),
'fileName': fileName.replace ( '"', '\\"' ) ,
'customMsg': customMsg.replace ( '"', '\\"' ),
}
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Utility functions for the File Manager Connector for Python
"""
import string, re
import os
import config as Config
# Generic manipulation functions
def removeExtension(fileName):
index = fileName.rindex(".")
newFileName = fileName[0:index]
return newFileName
def getExtension(fileName):
index = fileName.rindex(".") + 1
fileExtension = fileName[index:]
return fileExtension
def removeFromStart(string, char):
return string.lstrip(char)
def removeFromEnd(string, char):
return string.rstrip(char)
# Path functions
def combinePaths( basePath, folder ):
return removeFromEnd( basePath, '/' ) + '/' + removeFromStart( folder, '/' )
def getFileName(filename):
" Purpose: helper function to extrapolate the filename "
for splitChar in ["/", "\\"]:
array = filename.split(splitChar)
if (len(array) > 1):
filename = array[-1]
return filename
def sanitizeFolderName( newFolderName ):
"Do a cleanup of the folder name to avoid possible problems"
# Remove . \ / | : ? * " < > and control characters
return re.sub( '(?u)\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[^\u0000-\u001f\u007f-\u009f]', '_', newFolderName )
def sanitizeFileName( newFileName ):
"Do a cleanup of the file name to avoid possible problems"
# Replace dots in the name with underscores (only one dot can be there... security issue).
if ( Config.ForceSingleExtension ): # remove dots
newFileName = re.sub ( '/\\.(?![^.]*$)/', '_', newFileName ) ;
newFileName = newFileName.replace('\\','/') # convert windows to unix path
newFileName = os.path.basename (newFileName) # strip directories
# Remove \ / | : ? *
return re.sub ( '(?u)/\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[^\u0000-\u001f\u007f-\u009f]/', '_', newFileName )
def getCurrentFolder(currentFolder):
if not currentFolder:
currentFolder = '/'
# Check the current folder syntax (must begin and end with a slash).
if (currentFolder[-1] <> "/"):
currentFolder += "/"
if (currentFolder[0] <> "/"):
currentFolder = "/" + currentFolder
# Ensure the folder path has no double-slashes
while '//' in currentFolder:
currentFolder = currentFolder.replace('//','/')
# Check for invalid folder paths (..)
if '..' in currentFolder or '\\' in currentFolder:
return None
return currentFolder
def mapServerPath( environ, url):
" Emulate the asp Server.mapPath function. Given an url path return the physical directory that it corresponds to "
# This isn't correct but for the moment there's no other solution
# If this script is under a virtual directory or symlink it will detect the problem and stop
return combinePaths( getRootPath(environ), url )
def mapServerFolder(resourceTypePath, folderPath):
return combinePaths ( resourceTypePath , folderPath )
def getRootPath(environ):
"Purpose: returns the root path on the server"
# WARNING: this may not be thread safe, and doesn't work w/ VirtualServer/mod_python
# Use Config.UserFilesAbsolutePath instead
if environ.has_key('DOCUMENT_ROOT'):
return environ['DOCUMENT_ROOT']
else:
realPath = os.path.realpath( './' )
selfPath = environ['SCRIPT_FILENAME']
selfPath = selfPath [ : selfPath.rfind( '/' ) ]
selfPath = selfPath.replace( '/', os.path.sep)
position = realPath.find(selfPath)
# This can check only that this script isn't run from a virtual dir
# But it avoids the problems that arise if it isn't checked
raise realPath
if ( position < 0 or position <> len(realPath) - len(selfPath) or realPath[ : position ]==''):
raise Exception('Sorry, can\'t map "UserFilesPath" to a physical path. You must set the "UserFilesAbsolutePath" value in "editor/filemanager/connectors/py/config.py".')
return realPath[ : position ]
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
This is the "File Uploader" for Python
"""
import os
from fckutil import *
from fckcommands import * # default command's implementation
from fckconnector import FCKeditorConnectorBase # import base connector
import config as Config
class FCKeditorQuickUpload( FCKeditorConnectorBase,
UploadFileCommandMixin,
BaseHttpMixin, BaseHtmlMixin):
def doResponse(self):
"Main function. Process the request, set headers and return a string as response."
# Check if this connector is disabled
if not(Config.Enabled):
return self.sendUploadResults(1, "This file uploader is disabled. Please check the \"editor/filemanager/connectors/py/config.py\"")
command = 'QuickUpload'
# The file type (from the QueryString, by default 'File').
resourceType = self.request.get('Type','File')
currentFolder = getCurrentFolder(self.request.get("CurrentFolder",""))
# Check for invalid paths
if currentFolder is None:
return self.sendUploadResults(102, '', '', "")
# Check if it is an allowed command
if ( not command in Config.ConfigAllowedCommands ):
return self.sendUploadResults( 1, '', '', 'The %s command isn\'t allowed' % command )
if ( not resourceType in Config.ConfigAllowedTypes ):
return self.sendUploadResults( 1, '', '', 'Invalid type specified' )
# Setup paths
self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType]
self.webUserFilesFolder = Config.QuickUploadPath[resourceType]
if not self.userFilesFolder: # no absolute path given (dangerous...)
self.userFilesFolder = mapServerPath(self.environ,
self.webUserFilesFolder)
# Ensure that the directory exists.
if not os.path.exists(self.userFilesFolder):
try:
self.createServerFoldercreateServerFolder( self.userFilesFolder )
except:
return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ")
# File upload doesn't have to return XML, so intercept here
return self.uploadFile(resourceType, currentFolder)
# Running from command line (plain old CGI)
if __name__ == '__main__':
try:
# Create a Connector Instance
conn = FCKeditorQuickUpload()
data = conn.doResponse()
for header in conn.headers:
if not header is None:
print '%s: %s' % header
print
print data
except:
print "Content-Type: text/plain"
print
import cgi
cgi.print_exception()
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Base Connector for Python (CGI and WSGI).
See config.py for configuration settings
"""
import cgi, os
from fckutil import *
from fckcommands import * # default command's implementation
from fckoutput import * # base http, xml and html output mixins
import config as Config
class FCKeditorConnectorBase( object ):
"The base connector class. Subclass it to extend functionality (see Zope example)"
def __init__(self, environ=None):
"Constructor: Here you should parse request fields, initialize variables, etc."
self.request = FCKeditorRequest(environ) # Parse request
self.headers = [] # Clean Headers
if environ:
self.environ = environ
else:
self.environ = os.environ
# local functions
def setHeader(self, key, value):
self.headers.append ((key, value))
return
class FCKeditorRequest(object):
"A wrapper around the request object"
def __init__(self, environ):
if environ: # WSGI
self.request = cgi.FieldStorage(fp=environ['wsgi.input'],
environ=environ,
keep_blank_values=1)
self.environ = environ
else: # plain old cgi
self.environ = os.environ
self.request = cgi.FieldStorage()
if 'REQUEST_METHOD' in self.environ and 'QUERY_STRING' in self.environ:
if self.environ['REQUEST_METHOD'].upper()=='POST':
# we are in a POST, but GET query_string exists
# cgi parses by default POST data, so parse GET QUERY_STRING too
self.get_request = cgi.FieldStorage(fp=None,
environ={
'REQUEST_METHOD':'GET',
'QUERY_STRING':self.environ['QUERY_STRING'],
},
)
else:
self.get_request={}
def has_key(self, key):
return self.request.has_key(key) or self.get_request.has_key(key)
def get(self, key, default=None):
if key in self.request.keys():
field = self.request[key]
elif key in self.get_request.keys():
field = self.get_request[key]
else:
return default
if hasattr(field,"filename") and field.filename: #file upload, do not convert return value
return field
else:
return field.value
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector/QuickUpload for Python (WSGI wrapper).
See config.py for configuration settings
"""
from connector import FCKeditorConnector
from upload import FCKeditorQuickUpload
import cgitb
from cStringIO import StringIO
# Running from WSGI capable server (recomended)
def App(environ, start_response):
"WSGI entry point. Run the connector"
if environ['SCRIPT_NAME'].endswith("connector.py"):
conn = FCKeditorConnector(environ)
elif environ['SCRIPT_NAME'].endswith("upload.py"):
conn = FCKeditorQuickUpload(environ)
else:
start_response ("200 Ok", [('Content-Type','text/html')])
yield "Unknown page requested: "
yield environ['SCRIPT_NAME']
return
try:
# run the connector
data = conn.doResponse()
# Start WSGI response:
start_response ("200 Ok", conn.headers)
# Send response text
yield data
except:
start_response("500 Internal Server Error",[("Content-type","text/html")])
file = StringIO()
cgitb.Hook(file = file).handle()
yield file.getvalue()
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Utility functions for the File Manager Connector for Python
"""
import string, re
import os
import config as Config
# Generic manipulation functions
def removeExtension(fileName):
index = fileName.rindex(".")
newFileName = fileName[0:index]
return newFileName
def getExtension(fileName):
index = fileName.rindex(".") + 1
fileExtension = fileName[index:]
return fileExtension
def removeFromStart(string, char):
return string.lstrip(char)
def removeFromEnd(string, char):
return string.rstrip(char)
# Path functions
def combinePaths( basePath, folder ):
return removeFromEnd( basePath, '/' ) + '/' + removeFromStart( folder, '/' )
def getFileName(filename):
" Purpose: helper function to extrapolate the filename "
for splitChar in ["/", "\\"]:
array = filename.split(splitChar)
if (len(array) > 1):
filename = array[-1]
return filename
def sanitizeFolderName( newFolderName ):
"Do a cleanup of the folder name to avoid possible problems"
# Remove . \ / | : ? * " < > and control characters
return re.sub( '(?u)\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[^\u0000-\u001f\u007f-\u009f]', '_', newFolderName )
def sanitizeFileName( newFileName ):
"Do a cleanup of the file name to avoid possible problems"
# Replace dots in the name with underscores (only one dot can be there... security issue).
if ( Config.ForceSingleExtension ): # remove dots
newFileName = re.sub ( '/\\.(?![^.]*$)/', '_', newFileName ) ;
newFileName = newFileName.replace('\\','/') # convert windows to unix path
newFileName = os.path.basename (newFileName) # strip directories
# Remove \ / | : ? *
return re.sub ( '(?u)/\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[^\u0000-\u001f\u007f-\u009f]/', '_', newFileName )
def getCurrentFolder(currentFolder):
if not currentFolder:
currentFolder = '/'
# Check the current folder syntax (must begin and end with a slash).
if (currentFolder[-1] <> "/"):
currentFolder += "/"
if (currentFolder[0] <> "/"):
currentFolder = "/" + currentFolder
# Ensure the folder path has no double-slashes
while '//' in currentFolder:
currentFolder = currentFolder.replace('//','/')
# Check for invalid folder paths (..)
if '..' in currentFolder or '\\' in currentFolder:
return None
return currentFolder
def mapServerPath( environ, url):
" Emulate the asp Server.mapPath function. Given an url path return the physical directory that it corresponds to "
# This isn't correct but for the moment there's no other solution
# If this script is under a virtual directory or symlink it will detect the problem and stop
return combinePaths( getRootPath(environ), url )
def mapServerFolder(resourceTypePath, folderPath):
return combinePaths ( resourceTypePath , folderPath )
def getRootPath(environ):
"Purpose: returns the root path on the server"
# WARNING: this may not be thread safe, and doesn't work w/ VirtualServer/mod_python
# Use Config.UserFilesAbsolutePath instead
if environ.has_key('DOCUMENT_ROOT'):
return environ['DOCUMENT_ROOT']
else:
realPath = os.path.realpath( './' )
selfPath = environ['SCRIPT_FILENAME']
selfPath = selfPath [ : selfPath.rfind( '/' ) ]
selfPath = selfPath.replace( '/', os.path.sep)
position = realPath.find(selfPath)
# This can check only that this script isn't run from a virtual dir
# But it avoids the problems that arise if it isn't checked
raise realPath
if ( position < 0 or position <> len(realPath) - len(selfPath) or realPath[ : position ]==''):
raise Exception('Sorry, can\'t map "UserFilesPath" to a physical path. You must set the "UserFilesAbsolutePath" value in "editor/filemanager/connectors/py/config.py".')
return realPath[ : position ]
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
See config.py for configuration settings
"""
import os
from fckutil import *
from fckcommands import * # default command's implementation
from fckoutput import * # base http, xml and html output mixins
from fckconnector import FCKeditorConnectorBase # import base connector
import config as Config
class FCKeditorConnector( FCKeditorConnectorBase,
GetFoldersCommandMixin,
GetFoldersAndFilesCommandMixin,
CreateFolderCommandMixin,
UploadFileCommandMixin,
BaseHttpMixin, BaseXmlMixin, BaseHtmlMixin ):
"The Standard connector class."
def doResponse(self):
"Main function. Process the request, set headers and return a string as response."
s = ""
# Check if this connector is disabled
if not(Config.Enabled):
return self.sendError(1, "This connector is disabled. Please check the connector configurations in \"editor/filemanager/connectors/py/config.py\" and try again.")
# Make sure we have valid inputs
for key in ("Command","Type","CurrentFolder"):
if not self.request.has_key (key):
return
# Get command, resource type and current folder
command = self.request.get("Command")
resourceType = self.request.get("Type")
currentFolder = getCurrentFolder(self.request.get("CurrentFolder"))
# Check for invalid paths
if currentFolder is None:
return self.sendError(102, "")
# Check if it is an allowed command
if ( not command in Config.ConfigAllowedCommands ):
return self.sendError( 1, 'The %s command isn\'t allowed' % command )
if ( not resourceType in Config.ConfigAllowedTypes ):
return self.sendError( 1, 'Invalid type specified' )
# Setup paths
if command == "QuickUpload":
self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType]
self.webUserFilesFolder = Config.QuickUploadPath[resourceType]
else:
self.userFilesFolder = Config.FileTypesAbsolutePath[resourceType]
self.webUserFilesFolder = Config.FileTypesPath[resourceType]
if not self.userFilesFolder: # no absolute path given (dangerous...)
self.userFilesFolder = mapServerPath(self.environ,
self.webUserFilesFolder)
# Ensure that the directory exists.
if not os.path.exists(self.userFilesFolder):
try:
self.createServerFoldercreateServerFolder( self.userFilesFolder )
except:
return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ")
# File upload doesn't have to return XML, so intercept here
if (command == "FileUpload"):
return self.uploadFile(resourceType, currentFolder)
# Create Url
url = combinePaths( self.webUserFilesFolder, currentFolder )
# Begin XML
s += self.createXmlHeader(command, resourceType, currentFolder, url)
# Execute the command
selector = {"GetFolders": self.getFolders,
"GetFoldersAndFiles": self.getFoldersAndFiles,
"CreateFolder": self.createFolder,
}
s += selector[command](resourceType, currentFolder)
s += self.createXmlFooter()
return s
# Running from command line (plain old CGI)
if __name__ == '__main__':
try:
# Create a Connector Instance
conn = FCKeditorConnector()
data = conn.doResponse()
for header in conn.headers:
print '%s: %s' % header
print
print data
except:
print "Content-Type: text/plain"
print
import cgi
cgi.print_exception()
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python and Zope.
This code was not tested at all.
It just was ported from pre 2.5 release, so for further reference see
\editor\filemanager\browser\default\connectors\py\connector.py in previous
releases.
"""
from fckutil import *
from connector import *
import config as Config
class FCKeditorConnectorZope(FCKeditorConnector):
"""
Zope versiof FCKeditorConnector
"""
# Allow access (Zope)
__allow_access_to_unprotected_subobjects__ = 1
def __init__(self, context=None):
"""
Constructor
"""
FCKeditorConnector.__init__(self, environ=None) # call superclass constructor
# Instance Attributes
self.context = context
self.request = FCKeditorRequest(context)
def getZopeRootContext(self):
if self.zopeRootContext is None:
self.zopeRootContext = self.context.getPhysicalRoot()
return self.zopeRootContext
def getZopeUploadContext(self):
if self.zopeUploadContext is None:
folderNames = self.userFilesFolder.split("/")
c = self.getZopeRootContext()
for folderName in folderNames:
if (folderName <> ""):
c = c[folderName]
self.zopeUploadContext = c
return self.zopeUploadContext
def setHeader(self, key, value):
self.context.REQUEST.RESPONSE.setHeader(key, value)
def getFolders(self, resourceType, currentFolder):
# Open the folders node
s = ""
s += """<Folders>"""
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
for (name, o) in zopeFolder.objectItems(["Folder"]):
s += """<Folder name="%s" />""" % (
convertToXmlAttribute(name)
)
# Close the folders node
s += """</Folders>"""
return s
def getZopeFoldersAndFiles(self, resourceType, currentFolder):
folders = self.getZopeFolders(resourceType, currentFolder)
files = self.getZopeFiles(resourceType, currentFolder)
s = folders + files
return s
def getZopeFiles(self, resourceType, currentFolder):
# Open the files node
s = ""
s += """<Files>"""
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
for (name, o) in zopeFolder.objectItems(["File","Image"]):
s += """<File name="%s" size="%s" />""" % (
convertToXmlAttribute(name),
((o.get_size() / 1024) + 1)
)
# Close the files node
s += """</Files>"""
return s
def findZopeFolder(self, resourceType, folderName):
# returns the context of the resource / folder
zopeFolder = self.getZopeUploadContext()
folderName = self.removeFromStart(folderName, "/")
folderName = self.removeFromEnd(folderName, "/")
if (resourceType <> ""):
try:
zopeFolder = zopeFolder[resourceType]
except:
zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=resourceType, title=resourceType)
zopeFolder = zopeFolder[resourceType]
if (folderName <> ""):
folderNames = folderName.split("/")
for folderName in folderNames:
zopeFolder = zopeFolder[folderName]
return zopeFolder
def createFolder(self, resourceType, currentFolder):
# Find out where we are
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
errorNo = 0
errorMsg = ""
if self.request.has_key("NewFolderName"):
newFolder = self.request.get("NewFolderName", None)
zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=newFolder, title=newFolder)
else:
errorNo = 102
return self.sendErrorNode ( errorNo, errorMsg )
def uploadFile(self, resourceType, currentFolder, count=None):
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
file = self.request.get("NewFile", None)
fileName = self.getFileName(file.filename)
fileNameOnly = self.removeExtension(fileName)
fileExtension = self.getExtension(fileName).lower()
if (count):
nid = "%s.%s.%s" % (fileNameOnly, count, fileExtension)
else:
nid = fileName
title = nid
try:
zopeFolder.manage_addProduct['OFSP'].manage_addFile(
id=nid,
title=title,
file=file.read()
)
except:
if (count):
count += 1
else:
count = 1
return self.zopeFileUpload(resourceType, currentFolder, count)
return self.sendUploadResults( 0 )
class FCKeditorRequest(object):
"A wrapper around the request object"
def __init__(self, context=None):
r = context.REQUEST
self.request = r
def has_key(self, key):
return self.request.has_key(key)
def get(self, key, default=None):
return self.request.get(key, default)
"""
Running from zope, you will need to modify this connector.
If you have uploaded the FCKeditor into Zope (like me), you need to
move this connector out of Zope, and replace the "connector" with an
alias as below. The key to it is to pass the Zope context in, as
we then have a like to the Zope context.
## Script (Python) "connector.py"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=*args, **kws
##title=ALIAS
##
import Products.zope as connector
return connector.FCKeditorConnectorZope(context=context).doResponse()
"""
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
"""
import os
try: # Windows needs stdio set for binary mode for file upload to work.
import msvcrt
msvcrt.setmode (0, os.O_BINARY) # stdin = 0
msvcrt.setmode (1, os.O_BINARY) # stdout = 1
except ImportError:
pass
from fckutil import *
from fckoutput import *
import config as Config
class GetFoldersCommandMixin (object):
def getFolders(self, resourceType, currentFolder):
"""
Purpose: command to recieve a list of folders
"""
# Map the virtual path to our local server
serverPath = mapServerFolder(self.userFilesFolder,currentFolder)
s = """<Folders>""" # Open the folders node
for someObject in os.listdir(serverPath):
someObjectPath = mapServerFolder(serverPath, someObject)
if os.path.isdir(someObjectPath):
s += """<Folder name="%s" />""" % (
convertToXmlAttribute(someObject)
)
s += """</Folders>""" # Close the folders node
return s
class GetFoldersAndFilesCommandMixin (object):
def getFoldersAndFiles(self, resourceType, currentFolder):
"""
Purpose: command to recieve a list of folders and files
"""
# Map the virtual path to our local server
serverPath = mapServerFolder(self.userFilesFolder,currentFolder)
# Open the folders / files node
folders = """<Folders>"""
files = """<Files>"""
for someObject in os.listdir(serverPath):
someObjectPath = mapServerFolder(serverPath, someObject)
if os.path.isdir(someObjectPath):
folders += """<Folder name="%s" />""" % (
convertToXmlAttribute(someObject)
)
elif os.path.isfile(someObjectPath):
size = os.path.getsize(someObjectPath)
files += """<File name="%s" size="%s" />""" % (
convertToXmlAttribute(someObject),
os.path.getsize(someObjectPath)
)
# Close the folders / files node
folders += """</Folders>"""
files += """</Files>"""
return folders + files
class CreateFolderCommandMixin (object):
def createFolder(self, resourceType, currentFolder):
"""
Purpose: command to create a new folder
"""
errorNo = 0; errorMsg ='';
if self.request.has_key("NewFolderName"):
newFolder = self.request.get("NewFolderName", None)
newFolder = sanitizeFolderName (newFolder)
try:
newFolderPath = mapServerFolder(self.userFilesFolder, combinePaths(currentFolder, newFolder))
self.createServerFolder(newFolderPath)
except Exception, e:
errorMsg = str(e).decode('iso-8859-1').encode('utf-8') # warning with encodigns!!!
if hasattr(e,'errno'):
if e.errno==17: #file already exists
errorNo=0
elif e.errno==13: # permission denied
errorNo = 103
elif e.errno==36 or e.errno==2 or e.errno==22: # filename too long / no such file / invalid name
errorNo = 102
else:
errorNo = 110
else:
errorNo = 102
return self.sendErrorNode ( errorNo, errorMsg )
def createServerFolder(self, folderPath):
"Purpose: physically creates a folder on the server"
# No need to check if the parent exists, just create all hierachy
try:
permissions = Config.ChmodOnFolderCreate
if not permissions:
os.makedirs(folderPath)
except AttributeError: #ChmodOnFolderCreate undefined
permissions = 0755
if permissions:
oldumask = os.umask(0)
os.makedirs(folderPath,mode=0755)
os.umask( oldumask )
class UploadFileCommandMixin (object):
def uploadFile(self, resourceType, currentFolder):
"""
Purpose: command to upload files to server (same as FileUpload)
"""
errorNo = 0
if self.request.has_key("NewFile"):
# newFile has all the contents we need
newFile = self.request.get("NewFile", "")
# Get the file name
newFileName = newFile.filename
newFileName = sanitizeFileName( newFileName )
newFileNameOnly = removeExtension(newFileName)
newFileExtension = getExtension(newFileName).lower()
allowedExtensions = Config.AllowedExtensions[resourceType]
deniedExtensions = Config.DeniedExtensions[resourceType]
if (allowedExtensions):
# Check for allowed
isAllowed = False
if (newFileExtension in allowedExtensions):
isAllowed = True
elif (deniedExtensions):
# Check for denied
isAllowed = True
if (newFileExtension in deniedExtensions):
isAllowed = False
else:
# No extension limitations
isAllowed = True
if (isAllowed):
# Upload to operating system
# Map the virtual path to the local server path
currentFolderPath = mapServerFolder(self.userFilesFolder, currentFolder)
i = 0
while (True):
newFilePath = os.path.join (currentFolderPath,newFileName)
if os.path.exists(newFilePath):
i += 1
newFileName = "%s(%04d).%s" % (
newFileNameOnly, i, newFileExtension
)
errorNo= 201 # file renamed
else:
# Read file contents and write to the desired path (similar to php's move_uploaded_file)
fout = file(newFilePath, 'wb')
while (True):
chunk = newFile.file.read(100000)
if not chunk: break
fout.write (chunk)
fout.close()
if os.path.exists ( newFilePath ):
doChmod = False
try:
doChmod = Config.ChmodOnUpload
permissions = Config.ChmodOnUpload
except AttributeError: #ChmodOnUpload undefined
doChmod = True
permissions = 0755
if ( doChmod ):
oldumask = os.umask(0)
os.chmod( newFilePath, permissions )
os.umask( oldumask )
newFileUrl = self.webUserFilesFolder + currentFolder + newFileName
return self.sendUploadResults( errorNo , newFileUrl, newFileName )
else:
return self.sendUploadResults( errorNo = 203, customMsg = "Extension not allowed" )
else:
return self.sendUploadResults( errorNo = 202, customMsg = "No File" )
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
"""
from time import gmtime, strftime
import string
def escape(text, replace=string.replace):
"""
Converts the special characters '<', '>', and '&'.
RFC 1866 specifies that these characters be represented
in HTML as < > and & respectively. In Python
1.5 we use the new string.replace() function for speed.
"""
text = replace(text, '&', '&') # must be done 1st
text = replace(text, '<', '<')
text = replace(text, '>', '>')
text = replace(text, '"', '"')
return text
def convertToXmlAttribute(value):
if (value is None):
value = ""
return escape(value)
class BaseHttpMixin(object):
def setHttpHeaders(self, content_type='text/xml'):
"Purpose: to prepare the headers for the xml to return"
# Prevent the browser from caching the result.
# Date in the past
self.setHeader('Expires','Mon, 26 Jul 1997 05:00:00 GMT')
# always modified
self.setHeader('Last-Modified',strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime()))
# HTTP/1.1
self.setHeader('Cache-Control','no-store, no-cache, must-revalidate')
self.setHeader('Cache-Control','post-check=0, pre-check=0')
# HTTP/1.0
self.setHeader('Pragma','no-cache')
# Set the response format.
self.setHeader( 'Content-Type', content_type + '; charset=utf-8' )
return
class BaseXmlMixin(object):
def createXmlHeader(self, command, resourceType, currentFolder, url):
"Purpose: returns the xml header"
self.setHttpHeaders()
# Create the XML document header
s = """<?xml version="1.0" encoding="utf-8" ?>"""
# Create the main connector node
s += """<Connector command="%s" resourceType="%s">""" % (
command,
resourceType
)
# Add the current folder node
s += """<CurrentFolder path="%s" url="%s" />""" % (
convertToXmlAttribute(currentFolder),
convertToXmlAttribute(url),
)
return s
def createXmlFooter(self):
"Purpose: returns the xml footer"
return """</Connector>"""
def sendError(self, number, text):
"Purpose: in the event of an error, return an xml based error"
self.setHttpHeaders()
return ("""<?xml version="1.0" encoding="utf-8" ?>""" +
"""<Connector>""" +
self.sendErrorNode (number, text) +
"""</Connector>""" )
def sendErrorNode(self, number, text):
return """<Error number="%s" text="%s" />""" % (number, convertToXmlAttribute(text))
class BaseHtmlMixin(object):
def sendUploadResults( self, errorNo = 0, fileUrl = '', fileName = '', customMsg = '' ):
self.setHttpHeaders("text/html")
"This is the function that sends the results of the uploading process"
return """<script type="text/javascript">
(function()
{
var d = document.domain ;
while ( true )
{
// Test if we can access a parent property.
try
{
var test = window.top.opener.document.domain ;
break ;
}
catch( e ) {}
// Remove a domain part: www.mytest.example.com => mytest.example.com => example.com ...
d = d.replace( /.*?(?:\.|$)/, '' ) ;
if ( d.length == 0 )
break ; // It was not able to detect the domain.
try
{
document.domain = d ;
}
catch (e)
{
break ;
}
}
})() ;
window.parent.OnUploadCompleted(%(errorNumber)s,"%(fileUrl)s","%(fileName)s","%(customMsg)s");
</script>""" % {
'errorNumber': errorNo,
'fileUrl': fileUrl.replace ('"', '\\"'),
'fileName': fileName.replace ( '"', '\\"' ) ,
'customMsg': customMsg.replace ( '"', '\\"' ),
}
| Python |
#!/usr/bin/env python
"""
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Configuration file for the File Manager Connector for Python
"""
# INSTALLATION NOTE: You must set up your server environment accordingly to run
# python scripts. This connector requires Python 2.4 or greater.
#
# Supported operation modes:
# * WSGI (recommended): You'll need apache + mod_python + modpython_gateway
# or any web server capable of the WSGI python standard
# * Plain Old CGI: Any server capable of running standard python scripts
# (although mod_python is recommended for performance)
# This was the previous connector version operation mode
#
# If you're using Apache web server, replace the htaccess.txt to to .htaccess,
# and set the proper options and paths.
# For WSGI and mod_python, you may need to download modpython_gateway from:
# http://projects.amor.org/misc/svn/modpython_gateway.py and copy it in this
# directory.
# SECURITY: You must explicitly enable this "connector". (Set it to "True").
# WARNING: don't just set "ConfigIsEnabled = True", you must be sure that only
# authenticated users can access this file or use some kind of session checking.
Enabled = False
# Path to user files relative to the document root.
UserFilesPath = '/userfiles/'
# Fill the following value it you prefer to specify the absolute path for the
# user files directory. Useful if you are using a virtual directory, symbolic
# link or alias. Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'UserFilesPath' must point to the same directory.
# WARNING: GetRootPath may not work in virtual or mod_python configurations, and
# may not be thread safe. Use this configuration parameter instead.
UserFilesAbsolutePath = ''
# Due to security issues with Apache modules, it is recommended to leave the
# following setting enabled.
ForceSingleExtension = True
# What the user can do with this connector
ConfigAllowedCommands = [ 'QuickUpload', 'FileUpload', 'GetFolders', 'GetFoldersAndFiles', 'CreateFolder' ]
# Allowed Resource Types
ConfigAllowedTypes = ['File', 'Image', 'Flash', 'Media']
# After file is uploaded, sometimes it is required to change its permissions
# so that it was possible to access it at the later time.
# If possible, it is recommended to set more restrictive permissions, like 0755.
# Set to 0 to disable this feature.
# Note: not needed on Windows-based servers.
ChmodOnUpload = 0755
# See comments above.
# Used when creating folders that does not exist.
ChmodOnFolderCreate = 0755
# Do not touch this 3 lines, see "Configuration settings for each Resource Type"
AllowedExtensions = {}; DeniedExtensions = {};
FileTypesPath = {}; FileTypesAbsolutePath = {};
QuickUploadPath = {}; QuickUploadAbsolutePath = {};
# Configuration settings for each Resource Type
#
# - AllowedExtensions: the possible extensions that can be allowed.
# If it is empty then any file type can be uploaded.
# - DeniedExtensions: The extensions that won't be allowed.
# If it is empty then no restrictions are done here.
#
# For a file to be uploaded it has to fulfill both the AllowedExtensions
# and DeniedExtensions (that's it: not being denied) conditions.
#
# - FileTypesPath: the virtual folder relative to the document root where
# these resources will be located.
# Attention: It must start and end with a slash: '/'
#
# - FileTypesAbsolutePath: the physical path to the above folder. It must be
# an absolute path.
# If it's an empty string then it will be autocalculated.
# Useful if you are using a virtual directory, symbolic link or alias.
# Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'FileTypesPath' must point to the same directory.
# Attention: It must end with a slash: '/'
#
#
# - QuickUploadPath: the virtual folder relative to the document root where
# these resources will be uploaded using the Upload tab in the resources
# dialogs.
# Attention: It must start and end with a slash: '/'
#
# - QuickUploadAbsolutePath: the physical path to the above folder. It must be
# an absolute path.
# If it's an empty string then it will be autocalculated.
# Useful if you are using a virtual directory, symbolic link or alias.
# Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'QuickUploadPath' must point to the same directory.
# Attention: It must end with a slash: '/'
AllowedExtensions['File'] = ['7z','aiff','asf','avi','bmp','csv','doc','fla','flv','gif','gz','gzip','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','ods','odt','pdf','png','ppt','pxd','qt','ram','rar','rm','rmi','rmvb','rtf','sdc','sitd','swf','sxc','sxw','tar','tgz','tif','tiff','txt','vsd','wav','wma','wmv','xls','xml','zip']
DeniedExtensions['File'] = []
FileTypesPath['File'] = UserFilesPath + 'file/'
FileTypesAbsolutePath['File'] = (not UserFilesAbsolutePath == '') and (UserFilesAbsolutePath + 'file/') or ''
QuickUploadPath['File'] = FileTypesPath['File']
QuickUploadAbsolutePath['File'] = FileTypesAbsolutePath['File']
AllowedExtensions['Image'] = ['bmp','gif','jpeg','jpg','png']
DeniedExtensions['Image'] = []
FileTypesPath['Image'] = UserFilesPath + 'image/'
FileTypesAbsolutePath['Image'] = (not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'image/' or ''
QuickUploadPath['Image'] = FileTypesPath['Image']
QuickUploadAbsolutePath['Image']= FileTypesAbsolutePath['Image']
AllowedExtensions['Flash'] = ['swf','flv']
DeniedExtensions['Flash'] = []
FileTypesPath['Flash'] = UserFilesPath + 'flash/'
FileTypesAbsolutePath['Flash'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'flash/' or ''
QuickUploadPath['Flash'] = FileTypesPath['Flash']
QuickUploadAbsolutePath['Flash']= FileTypesAbsolutePath['Flash']
AllowedExtensions['Media'] = ['aiff','asf','avi','bmp','fla', 'flv','gif','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','png','qt','ram','rm','rmi','rmvb','swf','tif','tiff','wav','wma','wmv']
DeniedExtensions['Media'] = []
FileTypesPath['Media'] = UserFilesPath + 'media/'
FileTypesAbsolutePath['Media'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'media/' or ''
QuickUploadPath['Media'] = FileTypesPath['Media']
QuickUploadAbsolutePath['Media']= FileTypesAbsolutePath['Media']
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python and Zope.
This code was not tested at all.
It just was ported from pre 2.5 release, so for further reference see
\editor\filemanager\browser\default\connectors\py\connector.py in previous
releases.
"""
from fckutil import *
from connector import *
import config as Config
class FCKeditorConnectorZope(FCKeditorConnector):
"""
Zope versiof FCKeditorConnector
"""
# Allow access (Zope)
__allow_access_to_unprotected_subobjects__ = 1
def __init__(self, context=None):
"""
Constructor
"""
FCKeditorConnector.__init__(self, environ=None) # call superclass constructor
# Instance Attributes
self.context = context
self.request = FCKeditorRequest(context)
def getZopeRootContext(self):
if self.zopeRootContext is None:
self.zopeRootContext = self.context.getPhysicalRoot()
return self.zopeRootContext
def getZopeUploadContext(self):
if self.zopeUploadContext is None:
folderNames = self.userFilesFolder.split("/")
c = self.getZopeRootContext()
for folderName in folderNames:
if (folderName <> ""):
c = c[folderName]
self.zopeUploadContext = c
return self.zopeUploadContext
def setHeader(self, key, value):
self.context.REQUEST.RESPONSE.setHeader(key, value)
def getFolders(self, resourceType, currentFolder):
# Open the folders node
s = ""
s += """<Folders>"""
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
for (name, o) in zopeFolder.objectItems(["Folder"]):
s += """<Folder name="%s" />""" % (
convertToXmlAttribute(name)
)
# Close the folders node
s += """</Folders>"""
return s
def getZopeFoldersAndFiles(self, resourceType, currentFolder):
folders = self.getZopeFolders(resourceType, currentFolder)
files = self.getZopeFiles(resourceType, currentFolder)
s = folders + files
return s
def getZopeFiles(self, resourceType, currentFolder):
# Open the files node
s = ""
s += """<Files>"""
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
for (name, o) in zopeFolder.objectItems(["File","Image"]):
s += """<File name="%s" size="%s" />""" % (
convertToXmlAttribute(name),
((o.get_size() / 1024) + 1)
)
# Close the files node
s += """</Files>"""
return s
def findZopeFolder(self, resourceType, folderName):
# returns the context of the resource / folder
zopeFolder = self.getZopeUploadContext()
folderName = self.removeFromStart(folderName, "/")
folderName = self.removeFromEnd(folderName, "/")
if (resourceType <> ""):
try:
zopeFolder = zopeFolder[resourceType]
except:
zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=resourceType, title=resourceType)
zopeFolder = zopeFolder[resourceType]
if (folderName <> ""):
folderNames = folderName.split("/")
for folderName in folderNames:
zopeFolder = zopeFolder[folderName]
return zopeFolder
def createFolder(self, resourceType, currentFolder):
# Find out where we are
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
errorNo = 0
errorMsg = ""
if self.request.has_key("NewFolderName"):
newFolder = self.request.get("NewFolderName", None)
zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=newFolder, title=newFolder)
else:
errorNo = 102
return self.sendErrorNode ( errorNo, errorMsg )
def uploadFile(self, resourceType, currentFolder, count=None):
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
file = self.request.get("NewFile", None)
fileName = self.getFileName(file.filename)
fileNameOnly = self.removeExtension(fileName)
fileExtension = self.getExtension(fileName).lower()
if (count):
nid = "%s.%s.%s" % (fileNameOnly, count, fileExtension)
else:
nid = fileName
title = nid
try:
zopeFolder.manage_addProduct['OFSP'].manage_addFile(
id=nid,
title=title,
file=file.read()
)
except:
if (count):
count += 1
else:
count = 1
return self.zopeFileUpload(resourceType, currentFolder, count)
return self.sendUploadResults( 0 )
class FCKeditorRequest(object):
"A wrapper around the request object"
def __init__(self, context=None):
r = context.REQUEST
self.request = r
def has_key(self, key):
return self.request.has_key(key)
def get(self, key, default=None):
return self.request.get(key, default)
"""
Running from zope, you will need to modify this connector.
If you have uploaded the FCKeditor into Zope (like me), you need to
move this connector out of Zope, and replace the "connector" with an
alias as below. The key to it is to pass the Zope context in, as
we then have a like to the Zope context.
## Script (Python) "connector.py"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=*args, **kws
##title=ALIAS
##
import Products.zope as connector
return connector.FCKeditorConnectorZope(context=context).doResponse()
"""
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Base Connector for Python (CGI and WSGI).
See config.py for configuration settings
"""
import cgi, os
from fckutil import *
from fckcommands import * # default command's implementation
from fckoutput import * # base http, xml and html output mixins
import config as Config
class FCKeditorConnectorBase( object ):
"The base connector class. Subclass it to extend functionality (see Zope example)"
def __init__(self, environ=None):
"Constructor: Here you should parse request fields, initialize variables, etc."
self.request = FCKeditorRequest(environ) # Parse request
self.headers = [] # Clean Headers
if environ:
self.environ = environ
else:
self.environ = os.environ
# local functions
def setHeader(self, key, value):
self.headers.append ((key, value))
return
class FCKeditorRequest(object):
"A wrapper around the request object"
def __init__(self, environ):
if environ: # WSGI
self.request = cgi.FieldStorage(fp=environ['wsgi.input'],
environ=environ,
keep_blank_values=1)
self.environ = environ
else: # plain old cgi
self.environ = os.environ
self.request = cgi.FieldStorage()
if 'REQUEST_METHOD' in self.environ and 'QUERY_STRING' in self.environ:
if self.environ['REQUEST_METHOD'].upper()=='POST':
# we are in a POST, but GET query_string exists
# cgi parses by default POST data, so parse GET QUERY_STRING too
self.get_request = cgi.FieldStorage(fp=None,
environ={
'REQUEST_METHOD':'GET',
'QUERY_STRING':self.environ['QUERY_STRING'],
},
)
else:
self.get_request={}
def has_key(self, key):
return self.request.has_key(key) or self.get_request.has_key(key)
def get(self, key, default=None):
if key in self.request.keys():
field = self.request[key]
elif key in self.get_request.keys():
field = self.get_request[key]
else:
return default
if hasattr(field,"filename") and field.filename: #file upload, do not convert return value
return field
else:
return field.value
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
"""
import os
try: # Windows needs stdio set for binary mode for file upload to work.
import msvcrt
msvcrt.setmode (0, os.O_BINARY) # stdin = 0
msvcrt.setmode (1, os.O_BINARY) # stdout = 1
except ImportError:
pass
from fckutil import *
from fckoutput import *
import config as Config
class GetFoldersCommandMixin (object):
def getFolders(self, resourceType, currentFolder):
"""
Purpose: command to recieve a list of folders
"""
# Map the virtual path to our local server
serverPath = mapServerFolder(self.userFilesFolder,currentFolder)
s = """<Folders>""" # Open the folders node
for someObject in os.listdir(serverPath):
someObjectPath = mapServerFolder(serverPath, someObject)
if os.path.isdir(someObjectPath):
s += """<Folder name="%s" />""" % (
convertToXmlAttribute(someObject)
)
s += """</Folders>""" # Close the folders node
return s
class GetFoldersAndFilesCommandMixin (object):
def getFoldersAndFiles(self, resourceType, currentFolder):
"""
Purpose: command to recieve a list of folders and files
"""
# Map the virtual path to our local server
serverPath = mapServerFolder(self.userFilesFolder,currentFolder)
# Open the folders / files node
folders = """<Folders>"""
files = """<Files>"""
for someObject in os.listdir(serverPath):
someObjectPath = mapServerFolder(serverPath, someObject)
if os.path.isdir(someObjectPath):
folders += """<Folder name="%s" />""" % (
convertToXmlAttribute(someObject)
)
elif os.path.isfile(someObjectPath):
size = os.path.getsize(someObjectPath)
files += """<File name="%s" size="%s" />""" % (
convertToXmlAttribute(someObject),
os.path.getsize(someObjectPath)
)
# Close the folders / files node
folders += """</Folders>"""
files += """</Files>"""
return folders + files
class CreateFolderCommandMixin (object):
def createFolder(self, resourceType, currentFolder):
"""
Purpose: command to create a new folder
"""
errorNo = 0; errorMsg ='';
if self.request.has_key("NewFolderName"):
newFolder = self.request.get("NewFolderName", None)
newFolder = sanitizeFolderName (newFolder)
try:
newFolderPath = mapServerFolder(self.userFilesFolder, combinePaths(currentFolder, newFolder))
self.createServerFolder(newFolderPath)
except Exception, e:
errorMsg = str(e).decode('iso-8859-1').encode('utf-8') # warning with encodigns!!!
if hasattr(e,'errno'):
if e.errno==17: #file already exists
errorNo=0
elif e.errno==13: # permission denied
errorNo = 103
elif e.errno==36 or e.errno==2 or e.errno==22: # filename too long / no such file / invalid name
errorNo = 102
else:
errorNo = 110
else:
errorNo = 102
return self.sendErrorNode ( errorNo, errorMsg )
def createServerFolder(self, folderPath):
"Purpose: physically creates a folder on the server"
# No need to check if the parent exists, just create all hierachy
try:
permissions = Config.ChmodOnFolderCreate
if not permissions:
os.makedirs(folderPath)
except AttributeError: #ChmodOnFolderCreate undefined
permissions = 0755
if permissions:
oldumask = os.umask(0)
os.makedirs(folderPath,mode=0755)
os.umask( oldumask )
class UploadFileCommandMixin (object):
def uploadFile(self, resourceType, currentFolder):
"""
Purpose: command to upload files to server (same as FileUpload)
"""
errorNo = 0
if self.request.has_key("NewFile"):
# newFile has all the contents we need
newFile = self.request.get("NewFile", "")
# Get the file name
newFileName = newFile.filename
newFileName = sanitizeFileName( newFileName )
newFileNameOnly = removeExtension(newFileName)
newFileExtension = getExtension(newFileName).lower()
allowedExtensions = Config.AllowedExtensions[resourceType]
deniedExtensions = Config.DeniedExtensions[resourceType]
if (allowedExtensions):
# Check for allowed
isAllowed = False
if (newFileExtension in allowedExtensions):
isAllowed = True
elif (deniedExtensions):
# Check for denied
isAllowed = True
if (newFileExtension in deniedExtensions):
isAllowed = False
else:
# No extension limitations
isAllowed = True
if (isAllowed):
# Upload to operating system
# Map the virtual path to the local server path
currentFolderPath = mapServerFolder(self.userFilesFolder, currentFolder)
i = 0
while (True):
newFilePath = os.path.join (currentFolderPath,newFileName)
if os.path.exists(newFilePath):
i += 1
newFileName = "%s(%04d).%s" % (
newFileNameOnly, i, newFileExtension
)
errorNo= 201 # file renamed
else:
# Read file contents and write to the desired path (similar to php's move_uploaded_file)
fout = file(newFilePath, 'wb')
while (True):
chunk = newFile.file.read(100000)
if not chunk: break
fout.write (chunk)
fout.close()
if os.path.exists ( newFilePath ):
doChmod = False
try:
doChmod = Config.ChmodOnUpload
permissions = Config.ChmodOnUpload
except AttributeError: #ChmodOnUpload undefined
doChmod = True
permissions = 0755
if ( doChmod ):
oldumask = os.umask(0)
os.chmod( newFilePath, permissions )
os.umask( oldumask )
newFileUrl = self.webUserFilesFolder + currentFolder + newFileName
return self.sendUploadResults( errorNo , newFileUrl, newFileName )
else:
return self.sendUploadResults( errorNo = 203, customMsg = "Extension not allowed" )
else:
return self.sendUploadResults( errorNo = 202, customMsg = "No File" )
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector/QuickUpload for Python (WSGI wrapper).
See config.py for configuration settings
"""
from connector import FCKeditorConnector
from upload import FCKeditorQuickUpload
import cgitb
from cStringIO import StringIO
# Running from WSGI capable server (recomended)
def App(environ, start_response):
"WSGI entry point. Run the connector"
if environ['SCRIPT_NAME'].endswith("connector.py"):
conn = FCKeditorConnector(environ)
elif environ['SCRIPT_NAME'].endswith("upload.py"):
conn = FCKeditorQuickUpload(environ)
else:
start_response ("200 Ok", [('Content-Type','text/html')])
yield "Unknown page requested: "
yield environ['SCRIPT_NAME']
return
try:
# run the connector
data = conn.doResponse()
# Start WSGI response:
start_response ("200 Ok", conn.headers)
# Send response text
yield data
except:
start_response("500 Internal Server Error",[("Content-type","text/html")])
file = StringIO()
cgitb.Hook(file = file).handle()
yield file.getvalue()
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
See config.py for configuration settings
"""
import os
from fckutil import *
from fckcommands import * # default command's implementation
from fckoutput import * # base http, xml and html output mixins
from fckconnector import FCKeditorConnectorBase # import base connector
import config as Config
class FCKeditorConnector( FCKeditorConnectorBase,
GetFoldersCommandMixin,
GetFoldersAndFilesCommandMixin,
CreateFolderCommandMixin,
UploadFileCommandMixin,
BaseHttpMixin, BaseXmlMixin, BaseHtmlMixin ):
"The Standard connector class."
def doResponse(self):
"Main function. Process the request, set headers and return a string as response."
s = ""
# Check if this connector is disabled
if not(Config.Enabled):
return self.sendError(1, "This connector is disabled. Please check the connector configurations in \"editor/filemanager/connectors/py/config.py\" and try again.")
# Make sure we have valid inputs
for key in ("Command","Type","CurrentFolder"):
if not self.request.has_key (key):
return
# Get command, resource type and current folder
command = self.request.get("Command")
resourceType = self.request.get("Type")
currentFolder = getCurrentFolder(self.request.get("CurrentFolder"))
# Check for invalid paths
if currentFolder is None:
return self.sendError(102, "")
# Check if it is an allowed command
if ( not command in Config.ConfigAllowedCommands ):
return self.sendError( 1, 'The %s command isn\'t allowed' % command )
if ( not resourceType in Config.ConfigAllowedTypes ):
return self.sendError( 1, 'Invalid type specified' )
# Setup paths
if command == "QuickUpload":
self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType]
self.webUserFilesFolder = Config.QuickUploadPath[resourceType]
else:
self.userFilesFolder = Config.FileTypesAbsolutePath[resourceType]
self.webUserFilesFolder = Config.FileTypesPath[resourceType]
if not self.userFilesFolder: # no absolute path given (dangerous...)
self.userFilesFolder = mapServerPath(self.environ,
self.webUserFilesFolder)
# Ensure that the directory exists.
if not os.path.exists(self.userFilesFolder):
try:
self.createServerFoldercreateServerFolder( self.userFilesFolder )
except:
return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ")
# File upload doesn't have to return XML, so intercept here
if (command == "FileUpload"):
return self.uploadFile(resourceType, currentFolder)
# Create Url
url = combinePaths( self.webUserFilesFolder, currentFolder )
# Begin XML
s += self.createXmlHeader(command, resourceType, currentFolder, url)
# Execute the command
selector = {"GetFolders": self.getFolders,
"GetFoldersAndFiles": self.getFoldersAndFiles,
"CreateFolder": self.createFolder,
}
s += selector[command](resourceType, currentFolder)
s += self.createXmlFooter()
return s
# Running from command line (plain old CGI)
if __name__ == '__main__':
try:
# Create a Connector Instance
conn = FCKeditorConnector()
data = conn.doResponse()
for header in conn.headers:
print '%s: %s' % header
print
print data
except:
print "Content-Type: text/plain"
print
import cgi
cgi.print_exception()
| Python |
#!/usr/bin/env python
"""
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Configuration file for the File Manager Connector for Python
"""
# INSTALLATION NOTE: You must set up your server environment accordingly to run
# python scripts. This connector requires Python 2.4 or greater.
#
# Supported operation modes:
# * WSGI (recommended): You'll need apache + mod_python + modpython_gateway
# or any web server capable of the WSGI python standard
# * Plain Old CGI: Any server capable of running standard python scripts
# (although mod_python is recommended for performance)
# This was the previous connector version operation mode
#
# If you're using Apache web server, replace the htaccess.txt to to .htaccess,
# and set the proper options and paths.
# For WSGI and mod_python, you may need to download modpython_gateway from:
# http://projects.amor.org/misc/svn/modpython_gateway.py and copy it in this
# directory.
# SECURITY: You must explicitly enable this "connector". (Set it to "True").
# WARNING: don't just set "ConfigIsEnabled = True", you must be sure that only
# authenticated users can access this file or use some kind of session checking.
Enabled = False
# Path to user files relative to the document root.
UserFilesPath = '/userfiles/'
# Fill the following value it you prefer to specify the absolute path for the
# user files directory. Useful if you are using a virtual directory, symbolic
# link or alias. Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'UserFilesPath' must point to the same directory.
# WARNING: GetRootPath may not work in virtual or mod_python configurations, and
# may not be thread safe. Use this configuration parameter instead.
UserFilesAbsolutePath = ''
# Due to security issues with Apache modules, it is recommended to leave the
# following setting enabled.
ForceSingleExtension = True
# What the user can do with this connector
ConfigAllowedCommands = [ 'QuickUpload', 'FileUpload', 'GetFolders', 'GetFoldersAndFiles', 'CreateFolder' ]
# Allowed Resource Types
ConfigAllowedTypes = ['File', 'Image', 'Flash', 'Media']
# After file is uploaded, sometimes it is required to change its permissions
# so that it was possible to access it at the later time.
# If possible, it is recommended to set more restrictive permissions, like 0755.
# Set to 0 to disable this feature.
# Note: not needed on Windows-based servers.
ChmodOnUpload = 0755
# See comments above.
# Used when creating folders that does not exist.
ChmodOnFolderCreate = 0755
# Do not touch this 3 lines, see "Configuration settings for each Resource Type"
AllowedExtensions = {}; DeniedExtensions = {};
FileTypesPath = {}; FileTypesAbsolutePath = {};
QuickUploadPath = {}; QuickUploadAbsolutePath = {};
# Configuration settings for each Resource Type
#
# - AllowedExtensions: the possible extensions that can be allowed.
# If it is empty then any file type can be uploaded.
# - DeniedExtensions: The extensions that won't be allowed.
# If it is empty then no restrictions are done here.
#
# For a file to be uploaded it has to fulfill both the AllowedExtensions
# and DeniedExtensions (that's it: not being denied) conditions.
#
# - FileTypesPath: the virtual folder relative to the document root where
# these resources will be located.
# Attention: It must start and end with a slash: '/'
#
# - FileTypesAbsolutePath: the physical path to the above folder. It must be
# an absolute path.
# If it's an empty string then it will be autocalculated.
# Useful if you are using a virtual directory, symbolic link or alias.
# Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'FileTypesPath' must point to the same directory.
# Attention: It must end with a slash: '/'
#
#
# - QuickUploadPath: the virtual folder relative to the document root where
# these resources will be uploaded using the Upload tab in the resources
# dialogs.
# Attention: It must start and end with a slash: '/'
#
# - QuickUploadAbsolutePath: the physical path to the above folder. It must be
# an absolute path.
# If it's an empty string then it will be autocalculated.
# Useful if you are using a virtual directory, symbolic link or alias.
# Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'QuickUploadPath' must point to the same directory.
# Attention: It must end with a slash: '/'
AllowedExtensions['File'] = ['7z','aiff','asf','avi','bmp','csv','doc','fla','flv','gif','gz','gzip','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','ods','odt','pdf','png','ppt','pxd','qt','ram','rar','rm','rmi','rmvb','rtf','sdc','sitd','swf','sxc','sxw','tar','tgz','tif','tiff','txt','vsd','wav','wma','wmv','xls','xml','zip']
DeniedExtensions['File'] = []
FileTypesPath['File'] = UserFilesPath + 'file/'
FileTypesAbsolutePath['File'] = (not UserFilesAbsolutePath == '') and (UserFilesAbsolutePath + 'file/') or ''
QuickUploadPath['File'] = FileTypesPath['File']
QuickUploadAbsolutePath['File'] = FileTypesAbsolutePath['File']
AllowedExtensions['Image'] = ['bmp','gif','jpeg','jpg','png']
DeniedExtensions['Image'] = []
FileTypesPath['Image'] = UserFilesPath + 'image/'
FileTypesAbsolutePath['Image'] = (not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'image/' or ''
QuickUploadPath['Image'] = FileTypesPath['Image']
QuickUploadAbsolutePath['Image']= FileTypesAbsolutePath['Image']
AllowedExtensions['Flash'] = ['swf','flv']
DeniedExtensions['Flash'] = []
FileTypesPath['Flash'] = UserFilesPath + 'flash/'
FileTypesAbsolutePath['Flash'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'flash/' or ''
QuickUploadPath['Flash'] = FileTypesPath['Flash']
QuickUploadAbsolutePath['Flash']= FileTypesAbsolutePath['Flash']
AllowedExtensions['Media'] = ['aiff','asf','avi','bmp','fla', 'flv','gif','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','png','qt','ram','rm','rmi','rmvb','swf','tif','tiff','wav','wma','wmv']
DeniedExtensions['Media'] = []
FileTypesPath['Media'] = UserFilesPath + 'media/'
FileTypesAbsolutePath['Media'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'media/' or ''
QuickUploadPath['Media'] = FileTypesPath['Media']
QuickUploadAbsolutePath['Media']= FileTypesAbsolutePath['Media']
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
This page lists the data posted by a form.
"""
import cgi
import os
# Tell the browser to render html
print "Content-Type: text/html"
print ""
try:
# Create a cgi object
form = cgi.FieldStorage()
except Exception, e:
print e
# Document header
print """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>FCKeditor - Samples - Posted Data</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="robots" content="noindex, nofollow">
<link href="../sample.css" rel="stylesheet" type="text/css" />
</head>
<body>
"""
# This is the real work
print """
<h1>FCKeditor - Samples - Posted Data</h1>
This page lists all data posted by the form.
<hr>
<table width="100%" border="1" cellspacing="0" bordercolor="#999999">
<tr style="FONT-WEIGHT: bold; COLOR: #dddddd; BACKGROUND-COLOR: #999999">
<td nowrap>Field Name </td>
<td>Value</td>
</tr>
"""
for key in form.keys():
try:
value = form[key].value
print """
<tr>
<td valign="top" nowrap><b>%s</b></td>
<td width="100%%" style="white-space:pre">%s</td>
</tr>
""" % (key, value)
except Exception, e:
print e
print "</table>"
# For testing your environments
print "<hr>"
for key in os.environ.keys():
print "%s: %s<br>" % (key, os.environ.get(key, ""))
print "<hr>"
# Document footer
print """
</body>
</html>
"""
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Sample page.
"""
import cgi
import os
# Ensure that the fckeditor.py is included in your classpath
import fckeditor
# Tell the browser to render html
print "Content-Type: text/html"
print ""
# Document header
print """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>FCKeditor - Sample</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="robots" content="noindex, nofollow">
<link href="../sample.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>FCKeditor - Python - Sample 1</h1>
This sample displays a normal HTML form with an FCKeditor with full features
enabled.
<hr>
<form action="sampleposteddata.py" method="post" target="_blank">
"""
# This is the real work
try:
sBasePath = os.environ.get("SCRIPT_NAME")
sBasePath = sBasePath[0:sBasePath.find("_samples")]
oFCKeditor = fckeditor.FCKeditor('FCKeditor1')
oFCKeditor.BasePath = sBasePath
oFCKeditor.Value = """<p>This is some <strong>sample text</strong>. You are using <a href="http://www.fckeditor.net/">FCKeditor</a>.</p>"""
print oFCKeditor.Create()
except Exception, e:
print e
print """
<br>
<input type="submit" value="Submit">
</form>
"""
# For testing your environments
print "<hr>"
for key in os.environ.keys():
print "%s: %s<br>" % (key, os.environ.get(key, ""))
print "<hr>"
# Document footer
print """
</body>
</html>
"""
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
This page lists the data posted by a form.
"""
import cgi
import os
# Tell the browser to render html
print "Content-Type: text/html"
print ""
try:
# Create a cgi object
form = cgi.FieldStorage()
except Exception, e:
print e
# Document header
print """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>FCKeditor - Samples - Posted Data</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="robots" content="noindex, nofollow">
<link href="../sample.css" rel="stylesheet" type="text/css" />
</head>
<body>
"""
# This is the real work
print """
<h1>FCKeditor - Samples - Posted Data</h1>
This page lists all data posted by the form.
<hr>
<table width="100%" border="1" cellspacing="0" bordercolor="#999999">
<tr style="FONT-WEIGHT: bold; COLOR: #dddddd; BACKGROUND-COLOR: #999999">
<td nowrap>Field Name </td>
<td>Value</td>
</tr>
"""
for key in form.keys():
try:
value = form[key].value
print """
<tr>
<td valign="top" nowrap><b>%s</b></td>
<td width="100%%" style="white-space:pre">%s</td>
</tr>
""" % (key, value)
except Exception, e:
print e
print "</table>"
# For testing your environments
print "<hr>"
for key in os.environ.keys():
print "%s: %s<br>" % (key, os.environ.get(key, ""))
print "<hr>"
# Document footer
print """
</body>
</html>
"""
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Sample page.
"""
import cgi
import os
# Ensure that the fckeditor.py is included in your classpath
import fckeditor
# Tell the browser to render html
print "Content-Type: text/html"
print ""
# Document header
print """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>FCKeditor - Sample</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="robots" content="noindex, nofollow">
<link href="../sample.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>FCKeditor - Python - Sample 1</h1>
This sample displays a normal HTML form with an FCKeditor with full features
enabled.
<hr>
<form action="sampleposteddata.py" method="post" target="_blank">
"""
# This is the real work
try:
sBasePath = os.environ.get("SCRIPT_NAME")
sBasePath = sBasePath[0:sBasePath.find("_samples")]
oFCKeditor = fckeditor.FCKeditor('FCKeditor1')
oFCKeditor.BasePath = sBasePath
oFCKeditor.Value = """<p>This is some <strong>sample text</strong>. You are using <a href="http://www.fckeditor.net/">FCKeditor</a>.</p>"""
print oFCKeditor.Create()
except Exception, e:
print e
print """
<br>
<input type="submit" value="Submit">
</form>
"""
# For testing your environments
print "<hr>"
for key in os.environ.keys():
print "%s: %s<br>" % (key, os.environ.get(key, ""))
print "<hr>"
# Document footer
print """
</body>
</html>
"""
| Python |
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
This is the integration file for Python.
"""
import cgi
import os
import re
import string
def escape(text, replace=string.replace):
"""Converts the special characters '<', '>', and '&'.
RFC 1866 specifies that these characters be represented
in HTML as < > and & respectively. In Python
1.5 we use the new string.replace() function for speed.
"""
text = replace(text, '&', '&') # must be done 1st
text = replace(text, '<', '<')
text = replace(text, '>', '>')
text = replace(text, '"', '"')
text = replace(text, "'", ''')
return text
# The FCKeditor class
class FCKeditor(object):
def __init__(self, instanceName):
self.InstanceName = instanceName
self.BasePath = '/fckeditor/'
self.Width = '100%'
self.Height = '200'
self.ToolbarSet = 'Default'
self.Value = '';
self.Config = {}
def Create(self):
return self.CreateHtml()
def CreateHtml(self):
HtmlValue = escape(self.Value)
Html = ""
if (self.IsCompatible()):
File = "fckeditor.html"
Link = "%seditor/%s?InstanceName=%s" % (
self.BasePath,
File,
self.InstanceName
)
if (self.ToolbarSet is not None):
Link += "&ToolBar=%s" % self.ToolbarSet
# Render the linked hidden field
Html += "<input type=\"hidden\" id=\"%s\" name=\"%s\" value=\"%s\" style=\"display:none\" />" % (
self.InstanceName,
self.InstanceName,
HtmlValue
)
# Render the configurations hidden field
Html += "<input type=\"hidden\" id=\"%s___Config\" value=\"%s\" style=\"display:none\" />" % (
self.InstanceName,
self.GetConfigFieldString()
)
# Render the editor iframe
Html += "<iframe id=\"%s\__Frame\" src=\"%s\" width=\"%s\" height=\"%s\" frameborder=\"0\" scrolling=\"no\"></iframe>" % (
self.InstanceName,
Link,
self.Width,
self.Height
)
else:
if (self.Width.find("%%") < 0):
WidthCSS = "%spx" % self.Width
else:
WidthCSS = self.Width
if (self.Height.find("%%") < 0):
HeightCSS = "%spx" % self.Height
else:
HeightCSS = self.Height
Html += "<textarea name=\"%s\" rows=\"4\" cols=\"40\" style=\"width: %s; height: %s;\" wrap=\"virtual\">%s</textarea>" % (
self.InstanceName,
WidthCSS,
HeightCSS,
HtmlValue
)
return Html
def IsCompatible(self):
if (os.environ.has_key("HTTP_USER_AGENT")):
sAgent = os.environ.get("HTTP_USER_AGENT", "")
else:
sAgent = ""
if (sAgent.find("MSIE") >= 0) and (sAgent.find("mac") < 0) and (sAgent.find("Opera") < 0):
i = sAgent.find("MSIE")
iVersion = float(sAgent[i+5:i+5+3])
if (iVersion >= 5.5):
return True
return False
elif (sAgent.find("Gecko/") >= 0):
i = sAgent.find("Gecko/")
iVersion = int(sAgent[i+6:i+6+8])
if (iVersion >= 20030210):
return True
return False
elif (sAgent.find("Opera/") >= 0):
i = sAgent.find("Opera/")
iVersion = float(sAgent[i+6:i+6+4])
if (iVersion >= 9.5):
return True
return False
elif (sAgent.find("AppleWebKit/") >= 0):
p = re.compile('AppleWebKit\/(\d+)', re.IGNORECASE)
m = p.search(sAgent)
if (m.group(1) >= 522):
return True
return False
else:
return False
def GetConfigFieldString(self):
sParams = ""
bFirst = True
for sKey in self.Config.keys():
sValue = self.Config[sKey]
if (not bFirst):
sParams += "&"
else:
bFirst = False
if (sValue):
k = escape(sKey)
v = escape(sValue)
if (sValue == "true"):
sParams += "%s=true" % k
elif (sValue == "false"):
sParams += "%s=false" % k
else:
sParams += "%s=%s" % (k, v)
return sParams
| Python |
#!/usr/bin/env python
#
# Copyright (c) 2008 Google, Inc.
# Contributed by Arun Sharma <arun.sharma@google.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# System wide monitoring example. Copied from syst.c
#
# Run as: ./sys.py -c cpulist -e eventlist
import sys
import os
import optparse
import time
import struct
import perfmon
if __name__ == '__main__':
parser = optparse.OptionParser()
parser.add_option("-e", "--events", help="Events to use",
action="store", dest="events")
parser.add_option("-c", "--cpulist", help="CPUs to monitor",
action="store", dest="cpulist")
parser.set_defaults(cpulist="0")
parser.set_defaults(events="PERF_COUNT_HW_CPU_CYCLES")
(options, args) = parser.parse_args()
cpus = options.cpulist.split(',')
cpus = [ int(c) for c in cpus ]
if options.events:
events = options.events.split(",")
else:
raise "You need to specify events to monitor"
s = perfmon.SystemWideSession(cpus, events)
s.start()
# Measuring loop
while 1:
time.sleep(1)
# read the counts
for c in cpus:
for i in range(0, len(events)):
count = struct.unpack("L", s.read(c, i))[0]
print """CPU%d: %s\t%lu""" % (c, events[i], count)
| Python |
#!/usr/bin/env python
from distutils.core import setup, Extension
from distutils.command.install_data import install_data
setup(name='perfmon',
version='4.0',
author='Arun Sharma',
author_email='arun.sharma@google.com',
description='libpfm wrapper',
packages=['perfmon'],
package_dir={ 'perfmon' : 'src' },
py_modules=['perfmon.perfmon_int'],
ext_modules=[Extension('perfmon._perfmon_int',
sources = ['src/perfmon_int.i'],
libraries = ['pfm'],
library_dirs = ['../lib'],
include_dirs = ['../include'],
swig_opts=['-I../include'])])
| Python |
#
# Copyright (c) 2008 Google, Inc.
# Contributed by Arun Sharma <arun.sharma@google.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
import os
from perfmon import *
def public_members(self):
s = "{ "
for k, v in self.__dict__.iteritems():
if not k[0] == '_':
s += "%s : %s, " % (k, v)
s += " }"
return s
class System:
# Use the os that gives us everything
os = PFM_OS_PERF_EVENT_EXT
def __init__(self):
self.ncpus = os.sysconf('SC_NPROCESSORS_ONLN')
self.pmus = []
for i in range(0, PFM_PMU_MAX):
try:
pmu = PMU(i)
except:
pass
else:
self.pmus.append(pmu)
def __repr__(self):
return public_members(self)
class Event:
def __init__(self, info):
self.info = info
self.__attrs = []
def __repr__(self):
return '\n' + public_members(self)
def __parse_attrs(self):
info = self.info
for index in range(0, info.nattrs):
self.__attrs.append(pfm_get_event_attr_info(info.idx, index,
System.os)[1])
def attrs(self):
if not self.__attrs:
self.__parse_attrs()
return self.__attrs
class PMU:
def __init__(self, i):
self.info = pfm_get_pmu_info(i)[1]
self.__events = []
def __parse_events(self):
index = self.info.first_event
while index != -1:
self.__events.append(Event(pfm_get_event_info(index, System.os)[1]))
index = pfm_get_event_next(index)
def events(self):
if not self.__events:
self.__parse_events()
return self.__events
def __repr__(self):
return public_members(self)
if __name__ == '__main__':
from perfmon import *
s = System()
for pmu in s.pmus:
info = pmu.info
if info.flags.is_present:
print info.name, info.size, info.nevents
for e in pmu.events():
print e.info.name, e.info.code
for a in e.attrs():
print '\t\t', a.name, a.code
| Python |
#
# Copyright (c) 2008 Google, Inc.
# Contributed by Arun Sharma <arun.sharma@google.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
from perfmon import *
import os
import sys
# Common base class
class Session:
def __init__(self, events):
self.system = System()
self.event_names = events
self.events = []
self.fds = []
for e in events:
err, encoding = pfm_get_perf_event_encoding(e, PFM_PLM0 | PFM_PLM3,
None, None)
self.events.append(encoding)
def __del__(self):
pass
def read(self, fd):
# TODO: determine counter width
return os.read(fd, 8)
class SystemWideSession(Session):
def __init__(self, cpus, events):
self.cpus = cpus
Session.__init__(self, events)
def __del__(self):
Session.__del__(self)
def start(self):
self.cpu_fds = []
for c in self.cpus:
self.cpu_fds.append([])
cur_cpu_fds = self.cpu_fds[-1]
for e in self.events:
cur_cpu_fds.append(perf_event_open(e, -1, c, -1, 0))
def read(self, c, i):
index = self.cpus.index(c)
return Session.read(self, self.cpu_fds[index][i])
class PerThreadSession(Session):
def __init__(self, pid, events):
self.pid = pid
Session.__init__(self, events)
def __del__(self):
Session.__del__(self)
def start(self):
for e in self.events:
self.fds.append(perf_event_open(e, self.pid, -1, -1, 0))
def read(self, i):
return Session.read(self, self.fds[i])
| Python |
from perfmon_int import *
from pmu import *
from session import *
pfm_initialize()
| Python |
#!/usr/bin/env python
#
# Copyright (c) 2008 Google, Inc.
# Contributed by Arun Sharma <arun.sharma@google.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# Self monitoring example. Copied from self.c
import os
import optparse
import random
import errno
import struct
import perfmon
if __name__ == '__main__':
parser = optparse.OptionParser()
parser.add_option("-e", "--events", help="Events to use",
action="store", dest="events")
parser.set_defaults(events="PERF_COUNT_HW_CPU_CYCLES")
(options, args) = parser.parse_args()
if options.events:
events = options.events.split(",")
else:
raise "You need to specify events to monitor"
s = perfmon.PerThreadSession(int(os.getpid()), events)
s.start()
# code to be measured
#
# note that this is not identical to what examples/self.c does
# thus counts will be different in the end
for i in range(1, 1000000):
random.random()
# read the counts
for i in range(0, len(events)):
count = struct.unpack("L", s.read(i))[0]
print """%s\t%lu""" % (events[i], count)
| Python |
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 by Igor E. Novikov
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import fe
fe.fe_run()
| Python |
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 by Igor E. Novikov
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import fe
fe.fe_run()
| Python |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 by Igor E. Novikov
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
from uc2.uc_conf import UCConfig
from uc2.utils import system
from uc2.utils.fs import expanduser_unicode
from fe import events
class AppData():
app_name = 'Formats Explorer'
app_proc = 'formats-explorer'
app_org = 'sK1 Project'
app_domain = 'sk1project.org'
app_icon = None
doc_icon = None
version = "1.0"
app_config_dir = expanduser_unicode(os.path.join('~', '.config', 'f-explorer'))
if not os.path.lexists(app_config_dir):
os.makedirs(app_config_dir)
app_config = os.path.join(app_config_dir, 'preferences.cfg')
class AppConfig(UCConfig):
def __setattr__(self, attr, value):
if not hasattr(self, attr) or getattr(self, attr) != value:
self.__dict__[attr] = value
events.emit(events.CONFIG_MODIFIED, attr, value)
#============== GENERIC SECTION ===================
#============== UI SECTION ===================
palette_cell_vertical = 18
palette_cell_horizontal = 40
palette_orientation = 1
# 0 - tabbed
# 1 - windowed
interface_type = 0
mw_maximized = 0
mw_width = 1000
mw_height = 700
mw_min_width = 1000
mw_min_height = 700
show_splash = 1
set_doc_icon = 1
ruler_style = 1
ruler_min_tick_step = 3
ruler_min_text_step = 50
ruler_max_text_step = 100
# 0 - page center
# 1 - lower-left page corner
# 2 - upper-left page corner
ruler_coordinates = 1
# 'pt', 'in', 'cm', 'mm'
default_unit = 'mm'
sel_frame_offset = 10.0
sel_frame_color = (0.0, 0.0, 0.0)
sel_frame_dash = [5, 5]
sel_marker_size = 9.0
sel_marker_frame_color = (0.62745, 0.62745, 0.64314)
sel_marker_frame_dash = [5, 5]
sel_marker_fill = (1.0, 1.0, 1.0)
sel_marker_stroke = (0.0, 0.3, 1.0)
rotation_step = 5.0 #in graduses
stroke_sensitive_size = 5.0 #in pixels
#============== I/O SECTION ===================
open_dir = '~'
save_dir = '~'
import_dir = '~'
export_dir = '~'
make_backup = 1
resource_dir = ''
def __init__(self, path):
pass
# self.resource_dir = os.path.join(path, 'share')
class LinuxConfig(AppConfig):
os = system.LINUX
class MacosxConfig(AppConfig):
os = system.MACOSX
mw_maximized = 0
set_doc_icon = 0
ruler_style = 0
class WinConfig(AppConfig):
os = system.WINDOWS
ruler_style = 0
def get_app_config(path):
os_family = system.get_os_family()
if os_family == system.MACOSX:
return MacosxConfig(path)
elif os_family == system.WINDOWS:
return WinConfig(path)
else:
return LinuxConfig(path)
| Python |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 by Igor E. Novikov
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from PyQt4 import Qt, QtGui
def get_app_icons(app):
icons_data = {
'NEW': 'document-new.png',
'OPEN': 'document-open.png',
'SAVE_AS': 'document-save-as.png',
'EXIT': 'application-exit.png',
}
icons = {}
import icons_rc
for key in icons_data.keys():
icon = QtGui.QIcon()
icon.addFile(':/16x16/' + icons_data[key], Qt.QSize(16, 16))
icon.addFile(':/22x22/' + icons_data[key], Qt.QSize(22, 22))
icons[key] = icon
icon = QtGui.QIcon()
icon.addFile(':/fe_icon/fe_16.png', Qt.QSize(16, 16))
icon.addFile(':/fe_icon/fe_22.png', Qt.QSize(22, 22))
icon.addFile(':/fe_icon/fe_32.png', Qt.QSize(32, 32))
icon.addFile(':/fe_icon/fe_48.png', Qt.QSize(48, 48))
icons['FE'] = icon
return icons
| Python |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 by Igor E. Novikov
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from PyQt4 import QtGui, Qt
class ViewArea(QtGui.QFrame):
def __init__(self, parent, app, view):
QtGui.QFrame.__init__(self, parent)
self.app = app
self.view = view
self.build()
self.setAutoFillBackground(True)
self.setMinimumSize(800, 600)
def build(self):
pass
def closeEvent(self, event):
if self.app.close(self.view):
event.accept()
else:
event.ignore()
| Python |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 by Igor E. Novikov
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from PyQt4 import Qt, QtGui
from viewarea import ViewArea
class ModelView:
def __init__(self, app, doc_file=''):
self.app = app
self.viewarea = ViewArea(self.app.mw.mdiArea, self.app, self)
self.subwindow = self.app.mw.mdiArea.addSubWindow(self.viewarea)
# self.subwindow.setWindowIcon(self.app.appdata.doc_icon)
self.subwindow.resize(800, 600)
self.subwindow.setMinimumSize(800, 600)
# self.subwindow.showMaximized()
self.subwindow.show()
| Python |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 by Igor E. Novikov
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from PyQt4 import QtGui, Qt
from fe import events
class AppMainBar(QtGui.QToolBar):
def __init__(self, mw):
QtGui.QToolBar.__init__(self, 'MainToolBar', mw)
self.mw = mw
self.app = mw.app
self.build()
def build(self):
self.setFloatable(False)
self.setAllowedAreas(Qt.Qt.ToolBarAreas(Qt.Qt.TopToolBarArea))
self.addAction(self.app.actions['NEW'])
self.insertSeparator(self.app.actions['OPEN'])
self.addAction(self.app.actions['OPEN'])
self.addAction(self.app.actions['SAVE_AS'])
self.insertSeparator(self.app.actions['EXIT'])
self.addAction(self.app.actions['EXIT'])
| Python |
# -*- coding: utf-8 -*-
# Resource object code
#
# Created: ?? ???. 10 13:05:40 2011
# by: The Resource Compiler for PyQt (Qt v4.6.2)
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore
qt_resource_data = "\
\x00\x00\x09\x19\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x30\x00\x00\x00\x30\x08\x06\x00\x00\x00\x57\x02\xf9\x87\
\x00\x00\x00\x01\x73\x52\x47\x42\x00\xae\xce\x1c\xe9\x00\x00\x00\
\x09\x70\x48\x59\x73\x00\x00\x14\xc3\x00\x00\x14\xc3\x01\x15\x70\
\x4d\x42\x00\x00\x00\x07\x74\x49\x4d\x45\x07\xd9\x08\x11\x00\x2d\
\x32\xc9\xcd\x97\x13\x00\x00\x00\x06\x62\x4b\x47\x44\x00\xff\x00\
\xff\x00\xff\xa0\xbd\xa7\x93\x00\x00\x08\x99\x49\x44\x41\x54\x78\
\xda\xed\x58\x5b\x8c\x55\x57\x19\xfe\xd6\x5a\xfb\x9c\x33\x37\xca\
\x75\x98\x72\x4d\x5b\xb4\xad\x2d\x97\x56\xfa\x60\x1a\x92\xda\x44\
\x4b\x61\x98\x12\x23\x9a\x26\x3e\xf4\x01\x46\x26\x3a\x28\x97\x96\
\x02\x35\xf6\xc1\x48\x21\x80\xb5\x61\xaa\xb1\x40\xa3\x46\xa3\x26\
\x18\xb5\x40\xb9\xe8\x03\xc4\x1a\xdb\x54\x09\xb7\xb6\xb4\xb5\x15\
\x68\x33\x30\xf7\xdb\xb9\x9f\x7d\xf1\xdb\x7f\xf6\xde\x39\x73\x8e\
\x33\x23\x38\x13\x1a\x9d\x6f\xf8\x67\xaf\xbd\xd6\x5e\xff\xfa\xef\
\xeb\x1f\x30\x8e\x71\x8c\xe3\x7f\x08\x4d\x8f\xbd\x8c\x4f\x12\xb6\
\xaf\x3f\x84\x91\x60\x81\xf8\xfa\x8a\x03\x78\xe9\xf0\x6a\x40\x99\
\x85\x4d\x2b\x7f\xf6\x8c\xd6\xea\x8b\x4a\x61\xb2\x56\x9a\x73\x80\
\x26\x29\x19\x7b\xf2\xe4\xab\xcc\xc1\x1f\xf3\x29\xa4\x65\x1d\x3a\
\x9c\x0b\xd7\x35\xf7\x84\x7c\xc0\x47\xe9\x7a\xc0\x13\xba\xe8\x1c\
\xa0\x8f\x74\x9c\xbc\xbe\x07\xe0\xc2\x73\x1b\x0f\x63\xeb\x0f\x56\
\xe0\xdf\x41\x35\xd6\xef\xc7\xbe\x23\x6b\xb0\xb6\xe1\xe5\x16\x4f\
\xe1\x9b\x1a\xf0\xc8\x5c\x91\xa2\x83\xc3\x71\x24\xa0\x9c\x1d\x08\
\x50\xbe\x5e\x2e\x60\xb1\x21\xfe\xc3\x75\x9f\x99\x36\x5a\xf1\xbd\
\x65\xcb\x9e\x65\xeb\x76\x6c\x3a\x82\x2d\x7b\xea\xcb\x15\x00\xb1\
\x76\xc5\x81\xbd\x1c\x36\x7b\x22\x80\x12\x06\x9f\x00\x05\xe4\x0c\
\xe1\xa7\xcd\x8b\x4f\xef\x7e\xb4\x79\x28\x0f\xcc\x57\xc0\x79\xd9\
\x25\x0c\xa8\x39\xb5\x30\x4a\x36\x42\x18\x5f\x87\x02\x0a\x1a\x5a\
\x17\x09\x08\xce\x99\xc1\x21\x44\xc8\x37\x91\x02\x08\xd6\x4d\x68\
\x53\x0f\x1e\x11\xea\xa2\xb9\x60\xb4\x59\xe0\x78\xf6\x85\xa7\x77\
\x0f\xf6\x82\xc5\xef\xb6\xfa\xa7\x88\xdd\xe1\x3f\x91\xa4\x0a\x0d\
\x2d\xbf\x7f\xe2\x14\x6e\x12\x9e\xdb\x70\x64\x09\xe5\x3a\x0a\xa0\
\x5a\x62\xc9\x07\xbc\xef\x50\xf8\xc7\x51\x02\x4d\x7a\x28\x50\x9b\
\xbf\x7d\x98\x65\x8e\xeb\x9c\xc2\x4d\x84\xeb\xba\xaf\xd1\xe2\x0d\
\xf4\x96\x02\x22\xc9\x1e\x19\xaa\x0a\xdd\x1a\x8c\xc5\x95\x3f\xfe\
\xc3\x13\x7f\xc1\x4d\xc6\x33\x2f\x34\x80\x38\xb9\x63\xd3\xab\xa0\
\xe9\x43\x4c\x86\xa0\xdc\x03\x26\x7a\x51\x0a\x21\x0e\xfe\xfa\x97\
\x18\x63\x8c\x74\x96\xe4\xcb\x48\xb0\x86\x62\xb8\xea\xf1\xaf\xe1\
\xbd\x77\xde\xda\xdb\xd9\xd5\xd9\x78\xfe\xec\x99\x44\x2a\x35\x80\
\xd1\x83\x87\x44\xa2\x12\x77\xde\x75\x77\x76\xc6\xac\x39\xfb\xe7\
\x2f\x58\xb4\x2e\x3c\xf3\x7a\x61\x0d\x66\x2b\x10\x46\x17\xdf\xbe\
\xb0\xb7\xb6\x6e\x46\xf3\x40\x2a\x89\xcf\x3d\xb8\x44\x2e\x2a\x35\
\xba\x71\x0e\xdb\xb6\x2b\x66\xcd\x9e\xd3\xfc\xe1\x07\xef\xe1\x8e\
\x79\x77\xae\xc3\x0d\xc0\xc2\x10\xe8\xea\xea\x58\xd3\xd7\xdf\x07\
\xcf\xf5\x50\xe0\xcf\x58\xe1\xfd\x77\xdf\xa1\x37\x2a\x1a\x01\x8c\
\xae\x02\xe7\xce\x9c\xa9\x58\x74\xdf\x62\x38\x8e\x8d\xb1\x44\x2c\
\x16\xc7\x9b\x6f\xfc\x35\x01\x94\xc3\xa3\x97\xa2\xb1\xe7\xa0\x14\
\x7b\xb6\x1c\x1b\x5a\x81\x7e\x5a\x3f\x4f\xe1\xed\x42\x7e\xc4\x78\
\x06\xd4\xf5\xae\x45\x30\xb1\x18\x3a\x3b\xda\x21\xf5\x7f\xfd\xd1\
\x2e\x28\x6f\x8a\x52\xbe\xc0\x24\x78\x11\x03\x97\x2f\xbb\x36\x1f\
\xf3\x8c\x36\x72\xf9\x41\xe9\x17\x37\x6c\xff\x42\xf3\x90\x0a\x38\
\xd4\xbe\x90\xcb\x50\x01\xbb\x5c\x2c\xf2\x75\x49\xd3\xa7\xd7\xa1\
\xa2\xa2\x12\xb9\x5c\x16\xed\xed\xd7\xe4\x96\x0e\x71\xcb\xc4\x49\
\x98\x38\x71\x22\xb2\xd9\x2c\x05\x6c\x13\x7e\xb2\x5e\x82\xbc\xb1\
\xc8\xcb\x0d\xf9\x3e\xc8\xdc\xb8\xa8\x14\xc5\x85\x0a\xbb\x8a\x70\
\x4d\x79\xae\x03\x9b\x03\xad\xbc\x1e\xa5\x2b\xbf\x35\xac\x07\x3c\
\xc7\xa5\x60\x79\x3f\xd1\xca\x6c\x5a\x55\x59\x85\x65\x8f\x2e\x47\
\x88\xab\xad\xad\xf8\xe8\xa3\x2b\xd0\x5a\x47\xdf\xcc\x9d\x3c\x05\
\xf7\xdc\x3b\x1f\x21\x5e\xfb\xf3\x29\xb1\x34\xc5\x42\x31\x8c\x45\
\x05\x82\x50\xd9\xf6\xc2\xf2\x77\xb7\xaf\x3f\xb2\x0a\xd0\x07\x29\
\x67\xb9\x4c\xfc\x67\x7c\x06\xca\x2c\xf0\xbc\xac\xfb\xe4\xce\x65\
\x18\xce\x03\x54\x20\xc7\x1c\x70\x4a\xaa\x87\x83\x85\x0b\xef\x97\
\xf1\x89\xe3\x47\xd1\xdd\xd9\x09\xfa\x03\x96\x15\x43\x31\xce\x9e\
\x39\x2d\x54\x53\x33\x01\xf5\x0d\x2b\xf1\x99\x7b\xee\xc5\x89\x63\
\x97\xca\xbe\xd3\xda\xf0\x2c\x0f\x21\xb6\xfd\xb0\xfe\xb7\x54\x62\
\x17\xe5\x7c\x0a\xe4\x5b\x04\x5a\x9e\x3f\x5a\x3d\xbc\x71\xc7\x23\
\xad\xd1\xfe\x11\x14\x28\xa3\x74\x3a\x83\xea\x9a\x6a\xf4\xf6\xf4\
\xe0\x63\x5a\xdd\x76\x6c\x2a\xe9\x4a\xa8\xa4\x06\x06\x84\x38\x16\
\xc5\x49\xac\x66\x9d\xb8\x72\xf9\x32\xaa\xaa\x6a\x90\xe1\xde\x52\
\x7e\x79\x92\xcb\xfd\x21\xbe\xff\xed\x57\x7c\x25\x36\x53\x81\x93\
\xc5\x17\x99\x22\xe8\xe1\xa7\x36\xee\x58\x7a\x12\xc4\x48\x0a\x88\
\xa5\xe5\x90\x72\x92\x1c\x48\xa5\x52\xc8\xe7\xf3\x45\x8a\xa5\x50\
\xbf\xf2\x4b\x42\x1c\x47\xf3\x85\x42\x41\xde\x95\x02\xb2\xb9\x6c\
\x19\xaf\x2c\x89\x67\x15\xb5\x11\x8f\x51\x89\x43\xd8\xfa\xfc\xf2\
\x87\x01\xb4\x92\xbc\x20\x19\x0e\x6e\xda\xb9\x74\x37\x04\x23\x2b\
\x20\x56\xa5\x75\xca\x49\x84\xca\x0b\x0d\x9a\xcf\xe6\x98\xf0\x05\
\x21\x8e\x8b\xd6\xb2\xc8\xfb\xdf\xdb\xf9\x41\xf3\xb9\x6c\x56\x5a\
\x97\x6e\x7a\xc8\xf5\xca\x7b\xa1\xed\x1b\x0e\x71\x5d\xcf\x87\x34\
\xe9\xb8\xb8\x79\xd7\xf2\xaf\xec\x7c\xf2\xc8\x70\xf7\x40\x79\x0d\
\xce\xf0\x10\x97\xcf\x22\x04\xc2\x53\x50\xdb\x91\xea\xe3\x04\xeb\
\x8a\xf4\x8b\x9f\xff\x34\xa8\xed\x31\xd8\x14\x92\xe0\xba\xcd\x6a\
\x96\x97\x6a\x96\x65\x55\x8b\x27\x12\x91\x07\xaf\x5c\xb9\x0c\x15\
\x24\x72\x29\xb6\x3d\xdf\xc0\xb6\xfa\x70\x8f\x65\x59\x73\x14\xac\
\x76\xff\x2f\x32\xb6\xd3\x28\xc1\xf0\x49\x9c\xe7\x81\x6e\x89\x79\
\xb2\x99\xac\x24\x62\x4f\x77\x8f\x54\xa9\x50\x41\x0a\x25\x21\x45\
\x50\xb9\x78\x54\xff\xf8\x2d\x0d\x91\x91\x64\xcd\x64\x32\xe8\xed\
\xed\x13\x03\x18\x63\x8a\xdd\x0d\x94\x83\x61\xb4\x02\xc4\xc7\x18\
\x06\x7a\x38\x0f\xf4\x0f\x24\xfd\x0a\x21\x64\xfb\x65\x95\x02\x4e\
\xad\xad\x45\x45\x65\x25\x3a\xda\xda\x68\x39\x03\x0f\xca\x27\x89\
\xe7\xd5\x8d\x4d\x58\xbd\xa6\x09\xc9\x64\xd2\x57\x4e\x12\xbe\xad\
\xed\x1a\xce\x9f\x3b\x8b\x14\xe7\x66\xcc\x9c\x2d\x6b\x4c\x6e\x51\
\xbc\x98\x6e\x14\xd6\x70\xcd\x56\x72\xa0\x1f\x03\xfd\xfd\x70\x68\
\xb1\x25\x0f\x7d\x1e\x33\x67\xcd\xc6\xcc\x99\xb3\xf0\xc1\x3f\xde\
\xc7\x89\x13\x47\x45\x10\x5a\x5e\xac\x4d\xeb\x4a\xde\xf8\xe8\xec\
\xec\x60\xd5\xa9\x0a\xdb\x43\x36\x86\x6f\xe1\xed\xbb\xee\xc6\xd2\
\x65\xf5\x58\x74\xff\x62\xf4\xf7\xf6\xe2\xd0\x2b\xbf\x93\x50\x83\
\xc0\x1b\x13\x05\xa2\xf0\x71\xa1\x60\x4c\x4c\xfa\x16\xbb\xe0\x48\
\x09\x2d\xd0\x1b\x5a\xeb\xe8\x62\xe2\x45\x19\x85\x10\xf7\x0d\xb2\
\xaa\xcd\x71\x0f\xf7\xf8\x89\x6b\x19\x0d\x4d\x2a\xb6\xbc\x02\xfe\
\x2b\x05\x52\x5a\x5b\xd5\x52\xaa\x8a\x58\xd9\x81\x9b\x43\xfc\xe9\
\x8f\xc7\xe4\x56\x9e\x33\x77\x2e\xbe\xbc\xea\xab\xb8\x6f\xf1\x03\
\x38\xfd\xb7\x37\x23\x05\x58\x0a\xa9\x40\x2e\x1a\xd3\x3b\x51\x6e\
\xdc\x76\xdb\xed\xbc\xc8\xe6\x93\xc7\x71\x9c\x39\xfd\x77\x18\xe6\
\x05\x93\xb3\xf8\x9b\x1b\x57\x60\xff\xab\x8d\x35\x28\xc2\xda\x86\
\x03\xf8\xc9\xa1\xd5\x70\x4a\xac\xa8\xb4\x46\x2c\x1e\xc7\xa5\x4b\
\x97\xd0\xcd\x04\x9e\x34\x69\x32\x05\x2e\x88\x20\x61\xd9\x65\x55\
\x0a\xc7\x42\x84\xf4\x4c\x53\xa7\x4e\xa3\xf2\x79\x9c\xa6\xf0\x89\
\x44\x22\x98\x77\xa3\xc8\xf1\xa0\x46\x2d\x84\x44\x78\x39\xa0\xc4\
\x03\xc5\x47\xf5\xf5\xf6\x80\x1e\x13\x21\xc2\x8e\x53\x19\xc5\xaa\
\x55\x08\x94\x55\x5c\x17\xcb\x0a\x0f\x63\x0c\x73\x69\x40\x5a\x73\
\xd7\x09\x8f\x54\xc5\x6c\x47\x3f\x07\x1c\x57\x14\x08\xe5\x13\xd2\
\x4a\x8b\x27\xf2\x4c\x6a\xd9\x6c\x2c\x29\x93\xbe\xb4\x71\xbf\x7b\
\x75\x64\x1e\xf1\x58\x5c\xc2\x04\xd2\x53\xda\xa2\x50\x8e\xe1\x65\
\xb4\x05\xce\x88\xe2\x1e\x29\xe4\xed\x8d\x41\x12\x4b\x08\xb0\x94\
\x8a\xc0\x9a\x64\xc2\xa7\xd1\xec\x69\xd2\xa8\x99\x30\x01\x56\x2c\
\x26\x14\xe6\x81\x0e\x6a\x7b\x8c\x61\xc2\x0a\x13\x54\x28\xc5\x3d\
\x96\x5c\x5c\x0c\x41\xf1\x86\x0e\x12\xd8\x11\x2f\x7b\xfc\x6e\x2c\
\xca\x28\x99\xcb\x61\x9a\x64\x28\xb8\x92\x27\x08\xe9\x5f\x26\x4f\
\x99\x42\x0f\x18\xf1\x80\xd2\xa0\xc0\x16\x0e\xfe\xe6\x57\x20\x58\
\x42\x2b\xa1\x3c\x15\x58\x96\xde\xa1\x32\x69\x96\xd9\xb8\x15\xf7\
\x43\x4d\xbc\x0b\x27\xf8\x9f\x40\xc7\x95\xe2\x70\xdd\x18\xb9\x17\
\x72\x7c\x8b\x0a\x59\xda\xc8\xa5\x15\x08\x2c\xf7\x83\xe1\x5c\x6d\
\x5d\x9d\x58\x98\xca\x51\x81\x04\xaa\xaa\x6b\x50\x4d\x4a\x70\xac\
\x63\x46\x84\xaf\xa9\xa9\xa6\xb7\x6e\x41\x92\x39\x10\x8b\x5b\xbe\
\x51\x48\x7c\xea\xd0\x38\x46\xce\x1a\x83\x1c\x70\xe5\x00\x09\x1d\
\x39\x8c\x4f\x63\x49\x08\xb5\xb7\x77\xe0\x53\x9f\xb6\xb1\xf8\xb3\
\x0f\x40\x71\xed\xda\xb5\xab\xac\x4e\x1f\x4a\x8e\x84\x59\x39\xb3\
\x76\x36\x6e\x9f\x37\x0f\x5e\x10\x2e\xd7\xae\xb6\xc2\x8a\xc7\xc5\
\xb3\x62\x7a\x83\xc8\x43\xb6\x33\x06\x21\x24\xb5\x59\x83\xa4\xa0\
\x48\x41\x28\x91\x8c\xbc\xbf\xf1\xfa\xeb\x98\x3a\x6d\x1a\x2a\x12\
\x15\xf2\x37\x41\x9c\xc2\xd1\x1b\xa1\xfc\xd2\x5a\x5c\xbe\xfc\x4f\
\xb9\xbc\xba\xba\xba\xe1\xd8\xb6\x6f\x75\x59\x23\x6b\x49\x64\xe5\
\x6a\xf0\x17\x79\xab\x51\x57\x80\xe1\x50\x9d\x72\x0a\x4e\x35\x8c\
\x14\x49\x0a\xe7\x1f\xe8\x3f\x35\x75\xf2\xa0\x2c\xc5\x72\xda\x8b\
\x64\x10\x66\xa2\xa0\x08\xa2\x82\x4e\x36\x8d\x64\x2a\x29\x16\xa7\
\x31\x84\xdc\xa0\xac\x4a\x85\x73\x24\x89\xa9\x98\xc3\x3b\x65\x52\
\x7a\xd4\x73\x80\xad\xc3\xbe\x69\xb5\xd3\xd1\xdb\xd7\xc7\x0a\x92\
\x96\x24\x64\x7b\x2d\x0d\x1d\xcb\x28\x3b\x4a\xdb\x77\xbd\x5c\x78\
\x52\x2e\x45\x81\x98\xb4\x1c\xca\x18\xce\xf9\x8a\x48\x13\x28\xad\
\x34\xf7\x48\xab\x91\xc9\xe5\xc8\x2b\x8b\x54\x3a\x2d\xbc\x6b\x6f\
\xad\xf3\x4b\xee\x4b\xa3\xea\x81\xe6\xe6\x6f\xa0\xa5\xe5\x47\x1b\
\x9a\x9a\xd6\x6a\x5a\xbc\xf1\xec\xb9\xb3\x95\xe9\x74\x16\x40\xd8\
\x3a\x47\x81\x36\xf8\x3d\x2c\x87\x4a\x3c\x11\x0d\x89\x92\x77\xc5\
\x1b\x39\xce\x16\xe3\x8e\x4c\x47\x7b\xc7\xbe\x7d\xfb\x0f\x6c\x08\
\xce\xc4\xa8\xe1\xd9\x67\xbf\x8b\xb1\x43\xf9\x59\xe3\x18\xc7\x38\
\xfe\x4f\xf1\x2f\xbf\x62\xf6\x10\x0d\xb3\xe8\x0e\x00\x00\x00\x00\
\x49\x45\x4e\x44\xae\x42\x60\x82\
\x00\x00\x02\x93\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x10\x00\x00\x00\x10\x08\x06\x00\x00\x00\x1f\xf3\xff\x61\
\x00\x00\x00\x01\x73\x52\x47\x42\x00\xae\xce\x1c\xe9\x00\x00\x00\
\x06\x62\x4b\x47\x44\x00\xff\x00\xff\x00\xff\xa0\xbd\xa7\x93\x00\
\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0d\xd7\x00\x00\x0d\xd7\x01\
\x42\x28\x9b\x78\x00\x00\x00\x07\x74\x49\x4d\x45\x07\xd9\x08\x11\
\x00\x27\x33\x44\x25\x4f\x0f\x00\x00\x02\x13\x49\x44\x41\x54\x78\
\xda\xad\x90\x4f\x48\x54\x51\x14\xc6\xbf\xfb\xe6\xcd\x9b\x31\xd0\
\x16\x99\xb5\xe9\x0f\xae\xc6\x09\x52\x17\xd6\xaa\x68\x91\xf9\xa7\
\x20\x68\x6a\x52\x84\x08\x22\x42\x13\xa4\x68\x62\x9a\xcd\xa3\x3f\
\x54\xce\xc0\x6c\x42\xcd\x5a\xb7\x70\x53\x89\x03\x62\x4c\xd0\xc2\
\xda\xf4\x06\x2b\x6a\xdb\x34\xad\x72\x62\x7c\x81\xb3\x48\xdf\xbd\
\xef\x74\xde\x28\x39\x11\x89\x60\x3f\x2e\xdc\xfb\x5d\xce\xf7\x71\
\xce\xc1\xa6\x49\xdf\x98\xd9\x94\x4f\xa4\x13\x33\xdb\x04\xb4\xac\
\x10\xa2\x05\x20\x3e\x02\x10\x58\x17\x22\x9a\xe3\xfa\x76\xd7\x55\
\x25\x5d\x39\xee\x94\xe6\xa3\xfd\x44\x1c\x23\x3c\xb3\x17\x82\x55\
\x58\x57\xbf\x44\xc5\x0c\x80\x9a\xb9\x3e\x7b\xf5\x5e\x47\xab\x2e\
\xa5\x3a\x28\x94\xa6\xc5\xd3\xdd\x02\x1b\x24\x15\x9b\x26\x78\x1d\
\x33\xba\x23\x95\xe6\x5b\xb5\xbe\x79\x3d\x9b\xfc\xf4\xf1\x43\xec\
\xfd\xbb\x39\x48\x29\x11\x0c\x04\xf0\x73\x69\x09\xba\xae\x23\xd4\
\x14\x46\x73\x4b\x6b\xea\xd0\xe1\x23\xd7\xa5\xa3\x7e\x37\x29\xcc\
\x4b\x4f\x49\xf3\xf9\x60\x8e\x9e\x14\x63\x23\x0f\x38\x19\x68\x6b\
\x3b\x80\x5d\xbb\xf7\x80\x35\x06\x06\x87\xf0\xb5\x90\x47\xce\xb2\
\x10\x34\xea\x28\x6f\x6d\x15\x42\x73\x49\xac\x8c\x23\x34\x1e\x01\
\x5e\xa2\x47\x2e\xf7\x16\xf6\x82\x8d\x86\x1d\x3b\x91\x4a\xde\x87\
\x79\xf3\x0e\x92\xc3\x77\x2b\xba\x54\x2a\xe1\xd5\xec\xb4\x10\xae\
\x61\xb2\x47\x38\xcb\x4a\x48\xc7\x1d\xd6\x1c\x36\xcb\xe5\x95\x00\
\xc7\x91\xf8\x61\x2f\x20\x60\x04\x60\xf8\xfd\x18\x1a\xec\xaf\xdc\
\x01\x1e\xa5\x38\xff\x0d\xa4\x08\xe6\x78\xe7\x2d\x92\xc8\xb8\x0a\
\x93\xb7\x1f\x45\xe2\xb8\xd2\xfb\x44\x5d\xeb\x9b\x20\x30\x3d\xd1\
\x53\x64\xdb\x36\xbd\xcc\xbe\xa0\x8b\x17\xce\x91\x47\x5f\x6f\x94\
\x26\x9f\x3f\xa3\xef\xc5\x22\xf5\x44\x23\x84\x2a\xe2\xe7\x27\xf0\
\x07\x5e\x41\x57\xc7\x51\xca\xe7\x3f\xd3\xf1\xce\x76\xf2\x38\xd1\
\x75\x8c\x75\x9e\xba\x59\xaf\x05\xac\xa1\x55\x8b\x72\xb9\x8c\xfa\
\xfa\xed\x70\x95\x42\xb0\xa6\x06\x0c\xdf\x5b\x3c\xcd\xff\x0d\x58\
\x5c\x2c\x63\xdd\x00\x83\x67\xd7\xfd\x06\x2c\x2b\x87\xd1\x87\x8f\
\x71\x79\xa0\x1f\x23\x63\xe3\xbc\x5c\x0b\x3e\xde\x45\x6d\x6d\xdd\
\x5f\x01\x7a\xb5\xd8\xdb\xd8\x98\x2a\x7c\x29\xc4\x12\x89\x38\x2f\
\xd4\xe1\x40\x03\x99\xcc\x14\xfc\x6c\x0e\x85\x9a\x10\xde\x17\x4e\
\xe1\x5f\x44\x4f\x47\xb0\x11\xce\x46\xcf\xe0\xbf\xf2\x0b\x59\xa0\
\xf1\x23\x26\x1e\x57\x5d\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\
\x60\x82\
\x00\x00\x04\xd7\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\
\x00\x00\x00\x01\x73\x52\x47\x42\x00\xae\xce\x1c\xe9\x00\x00\x00\
\x09\x70\x48\x59\x73\x00\x00\x0d\xd7\x00\x00\x0d\xd7\x01\x42\x28\
\x9b\x78\x00\x00\x00\x07\x74\x49\x4d\x45\x07\xd9\x08\x11\x00\x2b\
\x32\x9f\x97\x30\x95\x00\x00\x00\x06\x62\x4b\x47\x44\x00\xff\x00\
\xff\x00\xff\xa0\xbd\xa7\x93\x00\x00\x04\x57\x49\x44\x41\x54\x78\
\xda\xed\x95\x6b\x6c\x54\x45\x14\xc7\xff\x33\x77\xbb\x8f\x6e\x44\
\x24\x8d\x7c\x20\xc6\x62\xfd\x50\x11\x22\x0d\x68\x62\x88\x0d\x44\
\x6d\xdd\xb4\x68\xa2\x04\xa3\x41\x42\xa5\x95\x0a\xb5\x2d\xdd\x3e\
\xd2\x04\x4d\x8c\x9a\x4a\xbb\xdb\xd6\x8a\xa1\x14\x10\x42\xe3\x57\
\x09\x04\x2c\xbe\x28\x56\xe5\x11\x62\xea\x37\x15\x89\xa9\x45\x3f\
\xa8\x49\xab\xf6\xb1\x8f\xbb\xf7\x8e\xe7\x4c\x6e\x37\x37\x4d\x97\
\x2c\x59\x13\x63\xd2\x5f\x3b\xf7\xcc\x9d\x39\x33\xf7\x3f\xe7\xcc\
\xcc\x62\x91\x45\x16\xf9\xaf\x11\x20\x76\x86\x06\x70\x74\xe8\x25\
\xec\xaa\x3c\xde\x22\x24\x1a\x84\x10\x2b\xa4\x14\x10\x54\x0c\xa1\
\xad\x2e\x52\x48\xc7\x3a\xef\xdc\xae\xeb\x70\xea\x92\x2c\xd8\x3a\
\x6d\x72\xce\x6f\x4c\x4a\xa3\xa7\x2d\x5a\xde\xd7\xd1\x74\x06\xed\
\xdd\x95\x2e\x01\x0e\x35\xa1\x23\xc3\x10\xd8\x48\x03\x95\x20\xe6\
\x04\xc8\x2c\x04\x68\xbb\x50\x5b\xda\x17\x4a\x4a\x8f\x30\x0c\x79\
\xa1\x2d\x1a\xda\x04\x17\x12\x44\x75\xe8\xfd\x7a\xa5\xd4\x46\x05\
\xa5\xc8\x9d\x30\x40\x03\x74\x31\xb2\x2d\xc6\xc2\xed\xb4\x72\xd0\
\x7c\x42\x29\x5b\xf1\x37\x22\xad\x9f\xb6\xc0\x85\x07\x04\x75\xec\
\x05\xb9\x48\xd2\xab\x20\x5f\x3e\x74\x7a\x47\x3f\xfe\x45\x3a\xf6\
\x9e\xad\x55\x0a\x07\x95\xb2\xc8\x18\x0d\x00\xba\xdc\x11\x60\x0a\
\xa9\x08\x02\x03\x67\xaa\xfa\xfb\x0f\xf4\x22\x57\xdc\x73\xb4\xf7\
\x54\xf4\xf3\xdc\x80\x7e\xac\x98\x1f\x81\x34\xbc\x79\x98\xda\xba\
\x46\x8c\x7e\x73\x35\x32\x3e\x3e\x16\xfe\xe9\xfa\x8f\x3a\x8f\x59\
\xc0\x91\x44\xc1\x9d\xcb\x71\xff\xea\x35\xd1\x92\x75\x0f\x35\xc3\
\x05\x0b\xe0\xfe\xf9\x78\x90\x81\x5f\x7f\x19\x0f\x1b\xc2\xc0\x3d\
\x45\xf7\xe2\x56\xe0\x9c\x4f\x4d\x4d\x85\x01\x34\x23\x03\x59\x09\
\xb8\xf6\xc3\x77\x28\x5c\x59\x04\xcb\xb2\xc0\xd8\xb6\x42\x2a\x65\
\x92\xb5\xe1\xf7\xf9\xc1\xc4\x13\x71\x7d\xd4\x3c\x9e\x3c\xb2\x02\
\x8c\xd7\xeb\xc3\xd5\x2b\x97\x16\x8c\x8e\x63\xb3\x13\x60\x9a\x29\
\x24\x12\x09\x58\xb6\x05\x65\x2b\xdc\x75\x77\x21\x1e\xde\x50\x0a\
\x6f\x5e\x1e\xfa\xdf\xeb\x03\x53\xbb\xa7\x1e\x49\xd3\xc4\xa5\xaf\
\x47\x70\xe3\xe7\x31\x7d\xec\x14\x40\x42\x53\x60\x3a\x1a\x86\x6a\
\x14\xd4\x00\x04\x3d\xe9\x9f\x4f\x24\x6f\xc4\x48\xeb\x39\x65\x90\
\x68\x2b\x65\x3e\x2d\x6f\x26\x20\x99\x34\x75\x99\x9e\x99\x41\x69\
\xe9\x26\x8c\x0c\x7f\x8e\x83\xef\xf6\x62\xdb\xf6\x2a\x2e\x5c\xe7\
\x36\xee\xd3\x3e\xda\x3f\x91\xd4\x63\x99\xf6\x77\x42\x87\x6d\x65\
\x5d\x54\x8a\x05\xd8\x02\x04\x55\x05\xbf\xdb\xb6\xf5\x49\x73\xe7\
\x13\x27\x33\x0b\x48\x99\x3a\x02\xc9\x78\x02\xb1\xd9\x59\x08\x29\
\x71\xfd\xda\xf7\x7a\x75\xca\xf9\xe3\x3a\xb7\x71\x1f\xfb\xb0\x6f\
\x22\x99\x20\x01\x26\x98\x37\xea\x4e\x61\x5f\xdf\xe6\x0d\x80\xfa\
\x03\xf4\x70\x25\xe3\x46\xf8\xed\xb2\xf2\x48\xeb\xd0\xcd\x52\x60\
\xea\xc9\x6c\xcb\x4e\xaf\x88\x57\x99\xe7\xf5\xa2\x27\xb2\x1f\xcc\
\xed\x4b\x97\xea\x36\x86\x05\xc5\x68\x4f\x4c\x4c\x4e\xa4\x53\xf0\
\xea\x81\xa7\xf0\x66\xfd\x69\x18\x86\x5c\x4d\x7b\xe8\x37\xbd\x7e\
\x48\x8b\x14\xaf\xe9\x6c\xf9\x08\xcd\x9d\x21\x2d\xc0\xb9\x3a\xb9\
\x2a\xe6\xa5\x20\x89\x99\x99\x69\xac\x5d\xbb\x0e\x4c\xca\x4a\x21\
\xf6\x77\x1c\xaf\xbd\xfe\x16\x98\x7d\xed\x2d\x1c\x4a\x12\x69\xa1\
\xa0\x60\x39\x2e\x7e\x35\x82\xdb\x96\x2c\xa1\x0f\x1a\x70\xa0\x08\
\x3c\xc9\xe6\xf7\xfd\xe1\x73\x8f\x08\x81\x2f\x05\xc4\x83\x76\xca\
\xfc\xab\x6d\xee\xf7\xa0\xaa\xfc\x10\xdc\xd4\x54\x1c\x01\xd3\x54\
\xbf\x5b\xbd\xb8\xfd\x79\x35\x47\x4f\xb4\x53\xd5\xd5\x56\xab\xaa\
\x17\x9e\x4b\xb7\x55\x51\xff\x2b\xbb\x6b\x54\x6f\xb4\x2b\xdd\xb6\
\x73\xc7\x36\xd5\xd4\xb0\x47\x21\x4b\xe4\xb1\x8f\x77\xc1\xcd\xe1\
\xb3\xd5\xce\x1e\xb0\xe0\xf3\x07\x40\x13\xe2\xf8\xb1\xa3\x68\x68\
\x0c\x63\x9a\xf2\x6c\xbb\x8e\x11\x1f\xcd\xe9\xe9\x59\xd4\x37\x36\
\xb1\x0f\xfb\xf2\x31\xd4\xd1\xcb\x16\x89\x0c\x70\xf8\x79\x23\x1a\
\x1e\x0f\x2e\x9c\xff\x4c\x6f\xb4\x00\x09\xf2\xd2\x1e\x70\xd0\x75\
\x7f\xc0\xaf\xfb\xbe\x18\x3e\xcf\xf7\x01\x8f\xd1\x63\x73\x17\x60\
\x26\xf5\x0a\xa5\x34\xf4\x07\x98\xfc\xfc\xa0\x5e\x61\x5a\x80\xcf\
\x87\x60\x20\x08\x82\x7d\x38\xf7\xe9\xb1\xd9\xe2\xc9\x2c\xc0\xd4\
\x2b\x36\x3c\x06\xbc\xf0\xe9\x8d\x56\xb2\x7e\x3d\xbe\x1d\x1d\x45\
\x73\x53\x23\xb4\xa0\x60\x10\x0f\x94\x94\xe8\xcb\xca\x47\x62\x38\
\x5a\x16\x89\x8e\xc5\xe2\xb9\x47\x80\x2f\x14\x21\x24\x17\x12\x92\
\x8f\xc1\x13\x27\xb0\x65\xcb\x56\x74\x45\xba\x11\x08\x04\x74\xe9\
\xec\xea\xc6\x96\x67\x9e\xc5\x07\x83\x83\xf4\x9e\x0f\x68\x7f\x71\
\x4b\x29\x10\xc8\x40\xd9\x63\x8f\x2a\x0e\xb1\xdf\xef\x47\x30\x98\
\xcf\x96\xd3\x41\xd6\x87\x65\xcb\xee\x80\x10\x06\x26\x27\x27\xa1\
\xaf\x6b\x8a\x4e\x3c\x1e\xa3\x95\xcf\xf2\xea\x75\x2a\x3e\x3c\x79\
\x4a\xe4\x94\x82\x95\x45\x45\xd1\x3f\x27\x27\xc2\x97\x2f\x5f\x71\
\xff\x94\x3a\x56\xb9\xf5\x73\xbf\x53\x57\x28\x2e\x2e\xc6\xaa\xfb\
\x56\x45\x91\x0b\xe5\x65\x8f\x23\x57\x36\x57\x56\x60\x91\xff\x05\
\xff\x00\x9a\x9f\x15\x3e\xc8\x5e\xef\x83\x00\x00\x00\x00\x49\x45\
\x4e\x44\xae\x42\x60\x82\
\x00\x00\x03\x7b\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x16\x00\x00\x00\x16\x08\x03\x00\x00\x00\xf3\x6a\x9c\x09\
\x00\x00\x00\x01\x73\x52\x47\x42\x00\xae\xce\x1c\xe9\x00\x00\x00\
\x09\x70\x48\x59\x73\x00\x00\x09\x84\x00\x00\x09\x84\x01\xaa\xe2\
\x63\x79\x00\x00\x00\x07\x74\x49\x4d\x45\x07\xd9\x08\x11\x00\x29\
\x31\x34\xa8\x03\xad\x00\x00\x01\xce\x50\x4c\x54\x45\x00\x00\x00\
\x57\x57\x57\x5c\x5c\x5c\x5f\x44\x98\x67\x4d\x9d\x6b\x52\xa0\x8c\
\x8c\x8c\x62\x41\xa0\x66\x4b\xa0\x65\x4b\x9f\x7e\x66\xaf\x7f\x67\
\xb0\x86\x6e\xb6\x7f\x68\xae\x83\x6b\xb4\x87\x6f\xb6\xcc\xc9\xc7\
\xcd\xca\xc8\x6f\x56\xa3\x88\x86\x85\x8d\x8b\x8a\x74\x5a\xab\x6e\
\x54\xa3\x6d\x54\xa1\x69\x4e\x9f\x7b\x64\xab\x68\x4d\x9e\x86\x70\
\xb5\x7e\x66\xaf\x6c\x53\xa0\x70\x57\xa4\x86\x70\xb5\x46\x43\x40\
\x47\x44\x40\x49\x47\x43\x4a\x48\x44\x4e\x4b\x49\x4e\x4c\x49\x4f\
\x4d\x4a\x58\x55\x52\x59\x57\x53\x5a\x58\x53\x5f\x44\x98\x5f\x5b\
\x59\x5f\x5c\x58\x5f\x5c\x59\x61\x5f\x5b\x61\x5f\x5c\x62\x46\x9d\
\x62\x60\x5d\x63\x5f\x5c\x63\x60\x5c\x63\x61\x5e\x64\x4a\x9b\x65\
\x62\x5f\x66\x4c\x9f\x66\x62\x5f\x66\x63\x5f\x67\x64\x60\x68\x4d\
\x9e\x69\x66\x63\x69\x67\x64\x6a\x66\x63\x6b\x4f\xa2\x6b\x69\x66\
\x6c\x53\xa0\x6c\x54\xa1\x6e\x6c\x69\x6f\x55\xa4\x6f\x6e\x6b\x70\
\x57\xa3\x72\x6f\x6b\x72\x70\x6d\x73\x59\xa7\x73\x71\x6d\x74\x5b\
\xa6\x74\x71\x6d\x75\x5d\xa9\x75\x73\x70\x77\x5d\xaa\x77\x5f\xa8\
\x77\x74\x70\x77\x75\x72\x78\x75\x71\x78\x76\x74\x79\x76\x72\x79\
\x78\x74\x7a\x62\xac\x7b\x62\xad\x7b\x77\x73\x7b\x77\x75\x7c\x65\
\xac\x7c\x7a\x77\x7e\x7a\x75\x7e\x7b\x78\x80\x69\xaf\x81\x6a\xb1\
\x81\x7d\x78\x81\x7d\x79\x81\x80\x7d\x82\x6a\xb2\x84\x7f\x7b\x84\
\x80\x7b\x84\x81\x7c\x85\x81\x7e\x86\x70\xb5\x86\x82\x7f\x87\x70\
\xb5\x8a\x88\x84\x8c\x89\x85\x8c\x8a\x87\x8e\x8b\x88\x91\x8e\x8a\
\x94\x91\x8f\x96\x93\x91\x99\x97\x95\x9b\x98\x95\x9b\x9a\x96\x9c\
\x98\x95\x9c\x99\x96\x9e\x9e\x9b\x9f\x9d\x9b\x9f\x9e\x9b\xa0\x9d\
\x9a\xa0\x9e\x9a\xa4\xa2\xa1\xa5\xa4\xa2\xa8\xa6\xa3\xaa\xa8\xa4\
\xaf\xae\xab\xb0\xaf\xad\xb4\xb2\xb0\xb4\xb2\xb1\xb5\xb3\xb1\xb6\
\xb4\xb2\xb9\xb7\xb4\xb9\xb7\xb5\xc2\xc1\xc0\xc3\xc2\xc0\xc3\xc2\
\xc1\xc5\xc4\xc2\xc8\xc7\xc7\xc9\xc9\xc8\xca\xc9\xc8\xce\xce\xcc\
\xd0\xce\xcd\xd4\xd3\xd2\xf1\xf1\xf0\xf5\xf4\xf4\xf5\xf5\xf4\xf8\
\xf8\xf8\xfa\xfb\xfa\xfb\xfb\xfb\xff\xff\xff\x78\xe1\x99\x16\x00\
\x00\x00\x20\x74\x52\x4e\x53\x00\x00\x00\x00\x00\x00\x00\x01\x0a\
\x12\x2f\x3f\x78\x7d\x7f\x84\x88\x88\x8b\x8f\x8f\xa2\xbe\xd0\xd9\
\xe3\xe9\xeb\xfd\xfe\xfe\xfe\x7e\xc0\xe0\x71\x00\x00\x00\x01\x62\
\x4b\x47\x44\x99\x01\xd6\x36\xa8\x00\x00\x00\xfa\x49\x44\x41\x54\
\x18\x19\xb5\xc1\x65\x3b\x43\x61\x00\x80\xe1\x07\xdb\x74\x77\x4d\
\x9b\x98\x1c\xd3\x9b\x66\x98\x66\x66\x66\x47\x77\x77\x77\x77\x7b\
\xff\x2d\x9f\xec\xf8\xea\xba\xdc\x37\xff\xca\x3f\x6e\x46\x6e\x2a\
\xda\x87\x6f\xbe\x92\x43\x1a\x95\x91\x1c\x92\x1f\x10\x69\xf3\xe2\
\x17\x6f\x5b\x0c\xd0\x6e\x41\x85\x93\x0a\x2c\x7d\x40\x73\x1b\x04\
\x1e\x8e\x0d\xdb\x27\xec\x43\xe3\xeb\x01\x80\xd9\x0c\xd4\x9b\xe0\
\x60\x77\xf5\x45\x2c\x8a\xd7\x8d\x9d\x0b\x42\x4d\x6a\xb5\x29\x88\
\xaa\x5a\xb0\x2e\x9d\x3c\xcf\xcd\xce\x3f\x9e\x2f\x5b\x21\x3c\xb6\
\x3a\x0c\xca\x8c\xd0\xb1\x70\x79\x3b\x29\xa6\xaf\xcf\x7a\x7b\x50\
\xba\x47\x45\xa0\xa4\xb0\x08\x1a\xba\x9e\x8e\x06\x4b\x9b\xb6\x1f\
\x74\x2d\xa0\xf0\xf4\x50\x40\x46\x2e\x94\x88\x4f\x9d\x56\x64\xe5\
\x7f\x88\x62\x7e\xb8\x61\xd0\xdc\xad\xa5\x8b\xb4\x95\x7b\x8d\x01\
\x19\x7d\xf9\xde\x69\x8e\xc8\x3e\xde\xd7\xeb\x91\xc9\x6c\xdc\xba\
\x29\x10\x79\x57\x9b\x35\x5a\x64\x2a\xfa\x47\xde\x45\x9d\x78\x1b\
\xe8\x6c\x45\x26\xb8\x3b\x39\x31\x3e\x25\x21\x29\xb5\x32\x04\x27\
\x57\x9c\x5c\xf8\x83\x2f\xfa\x75\x42\x73\x82\x2f\xe2\xb9\x00\x00\
\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\
\x00\x00\x02\x7f\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x10\x00\x00\x00\x10\x08\x03\x00\x00\x00\x28\x2d\x0f\x53\
\x00\x00\x00\x01\x73\x52\x47\x42\x00\xae\xce\x1c\xe9\x00\x00\x00\
\x09\x70\x48\x59\x73\x00\x00\x6e\xba\x00\x00\x6e\xba\x01\xd6\xde\
\xb1\x17\x00\x00\x00\x07\x74\x49\x4d\x45\x07\xd9\x0a\x16\x0d\x11\
\x07\x03\x42\xd2\x45\x00\x00\x01\x2c\x50\x4c\x54\x45\x00\x00\x00\
\x00\x00\x00\x08\x08\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x38\x81\xd9\x23\x6d\
\xc2\x3a\x82\xd9\x2e\x75\xc8\x3a\x83\xd9\x36\x7c\xce\x3a\x83\xd9\
\x3e\x83\xd4\x3c\x84\xdb\x46\x89\xd8\xff\xff\xff\x00\x4c\xa3\x02\
\x4e\xa8\x02\x4f\xa8\x0f\x58\xaa\x10\x60\xba\x18\x54\x9d\x19\x56\
\x9d\x22\x6b\xbf\x39\x82\xd9\x39\x83\xde\x3a\x83\xd9\x3a\x84\xde\
\x3c\x76\xbf\x3c\x84\xdb\x41\x87\xdb\x4e\x82\xc3\x50\x94\xe6\x50\
\x95\xe6\x50\x95\xe8\x54\x94\xe1\x69\x93\xcb\x6e\x87\xa6\x6f\x96\
\xcb\x76\x8d\xa7\x79\xa9\xe6\x7e\x92\xa9\x7e\x95\xb1\x7e\xad\xe8\
\x88\xb3\xeb\x90\x9d\xad\x90\xae\xd4\x91\xb0\xd6\x91\xba\xee\x94\
\xb9\xea\x95\xb9\xea\x9e\xbd\xe3\x9e\xc2\xed\xa0\xc3\xed\xae\xcb\
\xef\xae\xcd\xef\xaf\xca\xee\xaf\xcd\xef\xb0\xd0\xf7\xb7\xd0\xef\
\xb8\xd2\xf1\xb9\xd4\xf1\xbc\xd5\xf4\xbd\xd6\xf4\xc3\xd8\xf2\xc5\
\xd9\xf3\xc6\xd9\xf1\xd0\xe0\xf6\xd9\xe7\xf7\xe2\xe3\xe3\xe8\xe9\
\xe9\xeb\xeb\xeb\xeb\xec\xec\xed\xed\xed\xed\xee\xee\xee\xef\xef\
\xef\xef\xef\xef\xf0\xf0\xf0\xf0\xf0\xf1\xf1\xf1\xf1\xf2\xf2\xf2\
\xf3\xf3\xf3\xf3\xf3\xf4\xf4\xf4\xf4\xf5\xf5\xf5\xf5\xf5\xf6\xf6\
\xf6\xf8\xf8\xf8\xf9\xf9\xf9\xfa\xfa\xfa\xfb\xfb\xfb\xfc\xfc\xfc\
\xff\xff\xfa\xff\xff\xfe\xff\xff\xff\x5e\x7c\x77\xf2\x00\x00\x00\
\x15\x74\x52\x4e\x53\x00\x11\x1f\x2a\x2b\x33\x34\x35\x36\x37\xfa\
\xfb\xfb\xfc\xfc\xfd\xfd\xfd\xfe\xfe\xfe\x9a\xea\xde\x23\x00\x00\
\x00\x01\x62\x4b\x47\x44\x63\x5c\xbe\x2d\xaa\x00\x00\x00\xab\x49\
\x44\x41\x54\x18\x19\x45\xc1\x3d\x4a\x03\x01\x14\x04\xe0\x99\x79\
\xf3\xb2\x90\x10\x14\x6c\xb5\x12\x82\xad\x8d\xad\x47\xf0\x02\x39\
\x9f\xbd\xad\x47\xb1\xb5\x51\x48\x6b\x8c\xfb\xf7\x92\xcd\x12\xfc\
\x3e\x02\x4a\x62\x56\xdd\x08\x03\xdc\xe2\xe2\xf5\x17\xbe\xef\xfa\
\xb7\x27\x52\x0a\xe0\xba\x03\xb8\x7c\xfe\x7e\xfc\xb2\x2c\x0a\xef\
\x4d\x86\x74\x68\xa1\x48\xdb\xa1\x97\x9b\x4d\x6b\xb5\x23\xc2\x16\
\x09\xa1\x3f\xc8\x22\x60\x4b\x24\xce\xac\x45\x62\x4d\xe2\x2c\x1d\
\xbc\x1d\x6a\x10\x4e\x0a\x1c\x83\xc1\xd5\xa6\xbd\xeb\x88\x49\xe5\
\xe7\xe2\xc3\xea\xf7\x3f\x7f\xc4\xa4\x9a\xbd\x64\xc5\x09\x31\xa9\
\x88\x90\x95\xd9\x24\x66\xca\x94\xb5\x8c\x1d\x31\xab\xab\x46\x7c\
\x18\x48\x5c\x54\x05\x69\xe2\x5f\xf5\x47\xee\xed\x2c\xaf\x4d\x54\
\x16\x15\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\
\x00\x00\x03\x4a\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x10\x00\x00\x00\x10\x08\x06\x00\x00\x00\x1f\xf3\xff\x61\
\x00\x00\x00\x06\x62\x4b\x47\x44\x00\xff\x00\xff\x00\xff\xa0\xbd\
\xa7\x93\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x03\x76\x00\x00\
\x03\x76\x01\x7d\xd5\x82\xcc\x00\x00\x00\x07\x74\x49\x4d\x45\x07\
\xd7\x0c\x1b\x16\x0a\x05\x13\x29\x78\x6f\x00\x00\x02\xd7\x49\x44\
\x41\x54\x78\xda\x8d\x92\xcf\x6b\x54\x57\x14\xc7\x3f\xf7\xbe\x37\
\x6f\x5e\x66\x32\x93\xa9\x24\x1d\x27\x89\x10\x75\x5c\x34\xb5\x3f\
\xd4\xaa\x7f\x81\x0b\x15\x17\xa1\xe8\x2a\xd0\x45\x6d\x17\x81\x2e\
\xda\x95\xbb\x4a\x76\x5d\x15\x04\x41\x8b\x36\x5d\x74\x91\x62\xe9\
\x1f\x10\x88\x6e\x5c\x88\xa0\xa8\xd8\x92\x90\x74\x88\x21\x93\xa8\
\x33\x31\x33\xe3\xcb\xcc\xbc\x5f\xf7\x79\x78\x74\x21\xd2\x85\x07\
\x0e\xe7\xbe\xfb\xee\xf7\x73\xbf\xe7\x70\x55\x6b\x7e\xfe\x68\xef\
\xee\xdd\x9b\xad\x85\x85\x7d\x00\xc9\x5b\x09\x60\x80\x77\xf7\x9d\
\xbd\x7b\xed\xca\xf4\xb4\xf7\x6a\x65\xe5\x8c\xaa\x5f\xba\x74\x2f\
\x3c\x70\xe0\x64\x57\x29\xde\x37\x12\xa5\xd0\xad\x16\x2f\xaf\x5f\
\xbb\xa3\x16\xb4\xde\xd8\x33\x3b\x3b\x66\x95\x4a\x24\x5a\xe3\x45\
\x11\x05\xa9\xff\x17\xaf\x8d\x21\x6f\xdb\x68\xa9\x96\xd4\xa7\x33\
\x33\x75\x1d\xc8\x47\xd0\xe9\x10\x78\x1e\xfe\xc1\x83\x94\x4f\x9d\
\xa2\x1d\x86\xf8\xed\x36\x6f\xa7\xec\xa5\xff\xc2\x6a\x95\x60\x77\
\x97\xb0\xdb\xc5\x17\xad\x0e\x21\x15\x27\x49\xc2\xe4\x89\x13\x94\
\x2b\x15\xc6\xcf\x9e\xa5\xa7\x35\x81\x08\x25\xd3\xf5\xe8\xe9\xd3\
\x8c\x94\xcb\x7c\x74\xfc\x38\x72\x36\x05\x44\x90\x02\x52\x07\xde\
\xb3\x67\xac\xcc\xcd\x61\xa4\x85\xa2\xb4\x33\x3e\x35\x45\x9c\x1b\
\x20\xca\xb9\x54\xce\x9d\x63\xb0\x58\x24\x0e\xc3\xf4\x8c\xb7\xb6\
\x46\x24\x80\x10\xb0\xa3\x8c\x9d\x3a\x40\x84\xcf\xef\xdf\x27\xdc\
\xf5\xd8\xff\xf5\x45\xdc\x7c\x9e\xd1\xf3\x17\xe4\x36\x83\x93\xcb\
\x61\x44\x5c\x9b\xbb\x49\xf3\xe9\xdf\x80\x22\x5b\x1a\x4a\x01\xd6\
\x54\x36\xf3\x43\xe0\x64\x8b\xb1\x00\x94\x89\x31\xcd\x3a\xf1\x46\
\x8d\xfc\x67\xc7\x30\x5a\x83\xb6\xd0\x62\x79\xe7\x8f\x5f\xe9\x3c\
\x79\x48\xaf\xd9\xa4\xbd\xbe\xc1\xfa\xe2\x22\x7e\xbf\xff\xda\x8e\
\x2c\x8b\xf6\xe3\xc7\x98\x24\xa6\x58\x74\x28\xed\x71\xe9\xf5\xb7\
\x51\x67\xbe\x64\xb0\xf4\x01\x91\x80\x77\x5e\x6d\xb3\xb9\xf0\x17\
\xc9\xf2\x3f\x78\x5d\xf0\xfa\x9a\xd8\x76\x09\x01\x1d\xdb\x16\x89\
\x02\xe9\x84\xac\x0e\x50\xfb\xc6\x99\xb8\x7c\x85\xd2\xf0\x08\x16\
\x06\x2b\x31\x64\x07\x0b\x7c\xf8\xe3\x55\x32\x93\x87\x91\x91\xe0\
\x66\x15\xb6\xad\x49\x01\xc6\x56\x0a\xad\x70\x6c\x70\x0f\x7f\xca\
\xc7\x57\xe7\x19\x19\x1b\xc7\xd1\x90\xbb\x3e\xc3\xd0\xdc\x77\xb2\
\x56\x0c\x09\x70\xe2\xa7\xdf\xc8\x7e\x72\x04\xc7\x01\x2b\xa3\xfe\
\x73\x90\xd1\x28\x0d\x45\x79\x03\x5f\xdc\xf8\x93\x91\x51\x11\x5b\
\xc2\xbc\xf2\x0d\xee\xf2\x6d\x0a\xff\xde\x61\xf8\xf7\xef\x29\xe6\
\x73\x0c\x8f\x8e\xf1\xf9\xb5\x5b\x14\xaa\x87\xb0\x05\x10\xa5\x0e\
\x84\x0e\xe0\x37\x1a\x38\xad\x06\x16\x32\xb0\xd9\xaf\xf0\x1f\x2e\
\x92\x00\x26\x81\xf8\xd1\x6d\xcc\xcf\xdf\x32\xe0\x64\xc8\xb4\x9a\
\x84\xdb\x0d\x94\x05\x06\x50\x37\x8e\x56\x9f\xf7\x6a\xf5\x72\x4e\
\xc7\x72\xc3\x10\x95\xc9\x2a\x6a\xed\x01\x85\x1c\x69\xbf\x96\x06\
\x3f\x00\xaf\x07\xf1\xc4\x31\x5e\x2e\xd5\xd8\x69\xb4\xe9\x3b\x05\
\x96\x6a\xdb\x75\xdb\x2d\xef\x5f\x37\x41\x54\x56\xdd\x0e\x3d\x13\
\xf3\x62\x75\x99\x01\x77\x10\x1f\x70\x22\x40\x41\x6c\x20\xd0\xd0\
\x5b\x59\xa6\x1b\x42\x24\x43\xf5\xfa\x03\xe2\xc2\x5a\xb5\xb7\x96\
\x56\xa7\x3b\x9b\x5b\xbf\x84\xbe\x5f\x4d\x78\xbf\x50\x5a\x23\xb9\
\x2a\xaf\xf6\xe2\x1b\x6a\x91\x52\x21\x98\x91\x3a\x79\x00\x00\x00\
\x00\x49\x45\x4e\x44\xae\x42\x60\x82\
\x00\x00\x02\x43\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x10\x00\x00\x00\x10\x08\x06\x00\x00\x00\x1f\xf3\xff\x61\
\x00\x00\x00\x04\x73\x42\x49\x54\x08\x08\x08\x08\x7c\x08\x64\x88\
\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x01\xbb\x00\x00\x01\xbb\
\x01\x3a\xec\xe3\xe2\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\
\x74\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\
\x70\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x01\xc0\x49\x44\
\x41\x54\x78\xda\x8d\x8f\xbd\x6b\x53\x51\x18\x87\x9f\x73\x72\xc1\
\xb6\x41\x90\x82\x52\x2a\xc5\x39\xdd\x8c\x93\x75\xab\x83\x9b\xbb\
\x53\xbb\xe4\x3f\x68\x07\x11\x8a\x25\xd4\x82\x43\x87\xa2\x20\x0e\
\x15\x07\xe9\x6a\x16\xc5\x3d\xb5\x88\xa1\x1f\x42\xd3\x4d\x25\xe8\
\xcd\x87\x83\x12\x92\x9b\x8f\x9b\x9c\xd7\xe6\xe0\xe1\x70\x89\x5f\
\x3f\xf8\x71\xce\x19\x9e\xe7\x7d\x8f\x02\x2e\x00\xf3\xfc\x2b\xab\
\xdc\xce\x5c\xcb\x2c\x65\x2f\x67\xa7\x0f\xab\x87\xf5\x72\xbb\xfc\
\x40\x96\xe5\x49\x30\x82\x1b\x8d\xc6\x9e\x11\x41\x6b\x6d\xab\x94\
\x4a\xf4\xd9\xc7\x1d\x76\x7f\xec\xb2\x78\x69\x91\xcd\xf9\x4d\xee\
\x95\xef\xce\xa5\xbf\xa5\x1f\xab\x1d\x25\x1a\xc0\x08\x7f\xcd\xf6\
\xe9\x36\xd5\x4e\x95\xfd\x4f\x05\x00\x3e\x57\x0b\x98\x41\x4d\x63\
\x58\x0d\x00\x52\x29\xeb\xb1\xd3\xdc\x06\xda\x6f\x40\xed\x7b\x8d\
\xe8\x4e\x84\xcb\x8b\x9b\x65\x00\xd4\x23\x35\x1b\x00\x16\x42\x04\
\xf5\xeb\x0b\x16\x76\xe7\x59\x67\xae\xcc\x10\x3c\x57\x5c\x05\xde\
\x2f\x09\xb9\x82\xe2\x40\x80\x8b\x84\xda\x4d\x76\xb0\x6b\xca\xdf\
\x59\xc9\xac\x20\xe7\x35\x61\x0a\x9b\x0f\xc0\xb1\xc1\x30\xc5\x43\
\xbf\x01\x78\x81\xff\x8a\x6d\x6e\x2e\x07\x1a\xb6\xbe\x6e\x91\x7e\
\x99\x26\x0a\xf8\xc2\x04\x79\xb9\x25\x4f\x15\xb0\xd0\x6c\x36\xf7\
\xbc\xc0\xd7\x6d\xe7\x4e\x97\x20\x08\x6e\x88\xc8\x5b\x7b\x07\x50\
\x7e\x03\x57\x0f\x26\xce\x64\xbc\x00\xdc\xba\x6e\xb2\x83\xfe\x4f\
\x40\x12\x76\x60\x42\x60\x8c\xb1\x6d\xb7\x23\x01\x62\x2f\x18\x03\
\xc6\xe1\x4a\xa5\x42\x18\x86\x4c\x4c\x4e\xf2\xea\xf5\x9b\x77\xc0\
\x11\xf8\x2c\x44\x51\x24\xdd\x6e\x57\xfa\xfd\xbe\xc4\x71\x2c\x83\
\xc1\x40\x86\xc3\xa1\x18\x63\xec\xbb\x58\x2c\xda\xf7\xfd\x8d\x8d\
\x13\x60\x4a\x44\x70\xc5\x0a\x3a\x9d\x3f\x0a\x5a\xad\x96\x94\x4a\
\x25\x59\xcb\xe7\x47\xf0\xb4\x87\xbd\xe0\xfa\x99\xc0\xf4\x7a\xbd\
\x11\x9c\x10\x8c\x52\xaf\x37\xcc\xda\xfa\xfa\xbe\x9f\x9c\xac\x02\
\xce\x01\x59\x40\xf1\xfb\xc4\xc0\x91\x88\xc4\x30\x9e\x9f\xaf\xc9\
\x06\x51\x54\x9d\xd3\x94\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\
\x60\x82\
\x00\x00\x03\x47\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x10\x00\x00\x00\x10\x08\x06\x00\x00\x00\x1f\xf3\xff\x61\
\x00\x00\x00\x04\x73\x42\x49\x54\x08\x08\x08\x08\x7c\x08\x64\x88\
\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x01\xbb\x00\x00\x01\xbb\
\x01\x3a\xec\xe3\xe2\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\
\x74\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\
\x70\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x02\xc4\x49\x44\
\x41\x54\x78\xda\x9d\x93\x5b\x48\x53\x71\x1c\xc7\x3f\xe7\x6c\xe9\
\xa6\x36\x8f\xb5\x91\xa7\x48\x6c\x0b\x32\x8c\x08\xa4\xfb\x58\x2d\
\xbb\x88\xd5\x53\x62\x17\x8b\xae\xf3\xb5\xb2\x46\x17\x24\x28\xba\
\x47\x05\x41\x85\xbd\x44\x74\x2f\x0d\x2a\x95\x82\xc0\x82\x6e\x08\
\x25\xdd\x2f\x76\xa3\x8b\xb5\x6a\x73\xd3\xed\x2c\xdd\x39\xae\x79\
\x40\x5d\xf4\x12\x7d\xe1\xfb\x76\xbe\x1f\xbe\xbf\xef\x9f\x23\xc4\
\xe3\x71\xfe\x45\xd5\x6b\xe4\x41\x79\xcf\xf3\x1b\xd4\x48\xf4\x4d\
\x3f\x59\x2e\xcf\xaf\xae\xfe\x06\xa0\x03\xe6\xce\x99\xd3\xfa\xeb\
\x57\x87\xb4\x7a\xad\x97\x64\x09\x22\x80\x88\x40\x8c\x91\x6c\xe1\
\x63\xad\x84\xe5\xf2\x0b\x9e\x29\x0a\x17\x26\x4e\x0c\x5e\xa9\xab\
\xcb\x32\x02\x28\x11\x45\xca\x96\xb3\x71\x4d\x75\x13\x4f\x06\x74\
\x5b\x88\x13\x7d\xb4\x98\x1f\x3e\x91\x65\xf5\xaf\xf1\x48\x22\xb6\
\x9f\x61\xc4\xd6\xa0\x04\xa0\x03\xba\xba\xba\x30\xa5\x9a\x30\xa5\
\x18\x38\x79\xe3\x31\xc9\xca\xf4\x1d\x64\x8c\xf5\x15\x0b\x2b\x15\
\x04\xd5\x4f\x91\x37\x85\x9a\x9b\x23\x09\xbe\x35\xd2\x0b\xd0\x12\
\x00\x55\x55\x11\x45\x58\x5c\x38\x0a\x01\xf4\x26\xaf\x1a\xab\xc8\
\xb5\x3c\xa5\xb8\xa2\x03\xff\xcf\xef\x9c\xdd\x9a\x46\x28\x65\x1a\
\xb7\xdf\xb4\x24\x32\x1a\x00\x62\x4f\x03\x4d\xd3\x68\x8f\x76\x12\
\xed\x54\x51\x12\x7e\xff\xbc\x96\xbc\xd4\xe3\x94\x6d\xed\xe4\xdd\
\xc7\x00\x47\xd6\x9b\x21\x2d\x8f\xc6\x2f\x13\x30\x99\xcd\x00\xf4\
\x9d\xa0\x69\x7a\x83\x70\x02\x70\xfe\xda\x3d\x52\x63\xef\xf1\x4c\
\x7e\x4d\xf9\x2e\x81\x47\x2f\x43\x6c\x28\x53\xc9\xb0\x48\xec\xbe\
\x32\x8c\xd9\x33\x25\xa4\xcc\x4c\xda\xdb\xda\xfe\x6e\xd0\x16\x8e\
\xe2\x1a\x6d\xc5\x33\xc5\xcf\xe1\x73\x9f\xb8\xdb\x14\x62\xc9\xf4\
\x08\xee\x82\x74\x2e\x36\xcd\x20\x7f\xc4\x70\x0a\xc6\xbb\xba\xbf\
\xd7\x9d\x34\xa2\x86\xa6\xaa\x6c\x5b\xb7\x82\x03\xde\xa1\x9c\xbe\
\xfe\x95\xaa\xd3\x2f\x28\xc8\xfd\x4c\x59\xa1\x91\xe5\x7b\x44\x82\
\x91\x06\x1c\x0e\x07\x6f\x9f\x3c\xa0\x27\xd3\x37\xa2\x96\x20\x6a\
\x9d\x6c\x5c\xaa\x71\xeb\xc6\x25\xf6\x9e\xca\x22\x77\xa0\x8f\x1d\
\xe5\x06\x56\xed\x4b\xe3\xab\x3f\x8e\x7d\x58\x36\x46\x83\x41\x3f\
\xb5\x27\xf3\xc7\x06\x2b\xa7\x7f\xa0\xf5\x9b\x9f\xed\x67\x24\x06\
\x59\xda\x38\xe6\x85\xfd\x97\xed\x08\x19\x56\x36\x6e\x9a\x87\xcb\
\xe5\xa2\x74\x5e\x89\x7e\xaa\xc3\x6e\xd7\x33\xbd\x1b\x38\x0b\x72\
\x49\x4f\x37\x50\x71\xd4\x42\x7f\xb3\xca\xe1\xd5\xed\xec\x3a\xd5\
\x45\xc3\x03\x8d\x9c\x9c\x1c\x64\x59\xa6\xb9\xb9\x19\x79\xf0\x60\
\x44\xa3\x41\x7f\xf6\x98\xaa\xf6\x01\x0a\xdd\x93\x90\xc7\x6c\x27\
\xd3\x62\x62\x9f\xe7\x3b\x57\xef\x08\x9c\xa8\x8f\x61\xb3\xd9\x70\
\x3a\x9d\x84\x42\x21\xdd\xf1\xee\xf1\x12\xd5\xad\x56\x2b\xb1\x58\
\x0c\x1d\xb0\xad\x62\xbe\x71\xc8\x10\x1b\x4a\xa0\x91\x35\x0b\x24\
\xee\xbf\xb4\x72\xa8\x26\x8d\x01\x52\x16\xc5\xc5\xc5\x84\xc3\xe1\
\x5e\x40\x24\x12\xd1\x83\x51\x45\xd1\x47\x07\x30\xf6\x33\x65\x6c\
\xae\xdc\x59\xc5\xac\xb1\x16\xf5\x6c\xbd\xcf\xe8\x2e\x2a\x65\xf9\
\x4a\x03\x00\x81\x40\x80\x64\x7d\x69\x69\x01\xe2\x3c\x6c\x6a\x42\
\x34\x88\x41\x00\x2a\x56\x15\x2d\xf2\x94\x8c\x73\x74\xff\x95\xff\
\xe3\xdf\xfd\x96\x70\x9f\x9f\x28\xbe\x9f\x00\x00\x00\x00\x49\x45\
\x4e\x44\xae\x42\x60\x82\
\x00\x00\x03\x1c\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x16\x00\x00\x00\x16\x08\x06\x00\x00\x00\xc4\xb4\x6c\x3b\
\x00\x00\x00\x04\x73\x42\x49\x54\x08\x08\x08\x08\x7c\x08\x64\x88\
\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x03\x76\x00\x00\x03\x76\
\x01\x7d\xd5\x82\xcc\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\
\x74\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\
\x70\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x02\x99\x49\x44\
\x41\x54\x78\xda\xb5\x93\xcb\x6a\x14\x41\x14\x86\xff\x53\xa7\xfa\
\x36\x97\xc4\x44\xd0\xa0\x28\x41\x14\x82\xe8\x56\x5c\x24\x48\x7c\
\x00\x17\x22\xf8\x02\xae\x74\x25\xbe\x8c\x8b\xbc\x83\xe4\x19\x14\
\x09\x04\x14\x44\xd1\x88\x8a\x89\x44\xd0\x24\x9a\xdb\x4c\x67\xfa\
\x52\xe5\xa9\x74\x3a\xa6\xd3\x33\x41\x8c\xfe\xf0\xcf\x54\x4d\x4d\
\x7d\xf5\x9f\xd3\x5d\x64\xad\xc5\xff\x90\xc6\x21\x11\xd1\x79\x00\
\xe7\xca\x29\xfe\x4c\x56\xfc\x45\x42\x2e\x0d\x04\x8b\x2e\x2e\x2e\
\x2d\xcd\x86\x22\x39\x04\x4a\x4c\x7b\x46\x39\x2e\x12\x54\x4e\x9d\
\x9a\x9a\xba\x0d\xa0\x0e\x7e\x30\xf3\xfe\xed\x8f\x4e\x3a\x31\x7d\
\x7f\x06\xa4\x34\x7c\xcf\x93\x6f\xe5\x40\x55\x17\x55\xd5\xc0\xcc\
\xac\x70\x40\xfb\x93\x8d\x38\xbb\x70\xeb\xda\x18\x6e\x5c\x39\x09\
\xad\xd9\x41\x5d\xda\xba\x95\x72\xae\x8e\xc5\x67\x6f\x3e\x7c\x72\
\xef\xf1\xc2\x5a\x0d\xcc\xbb\x7f\x28\x32\x54\x5a\xe0\x7e\xaf\xba\
\x58\x3f\x54\xcd\xe4\xe5\x51\x8a\x93\x7c\xb4\xd6\x0a\xcf\x63\x4a\
\x73\x0b\x67\x3a\x08\x2d\xc6\x25\xec\xf0\x83\x46\x29\xb7\xcf\xf7\
\x7d\xd4\xc0\xcc\x3e\x3a\x71\x86\xb8\x67\xa0\xaa\xd0\x32\x5d\x09\
\xeb\x0b\xdf\x91\x7d\x3a\x60\xd4\x5b\xc1\x9a\x3a\xb2\x18\x27\x06\
\x00\x1d\x05\xad\xb4\xa0\x54\x9c\x1a\xb0\xd6\xfd\x12\x6b\x6c\xf5\
\x32\x74\x93\xbc\xb2\xb1\x06\x1d\x90\xdc\x05\xd2\xca\x43\x29\xba\
\xfa\x68\xce\x58\x6b\x09\xff\x50\x02\xb3\xda\x95\x7c\x67\x72\x7c\
\x73\xb8\xe9\x0f\x59\x00\x26\x4f\xd1\x0c\xfd\x5a\x22\x50\x5f\x00\
\x2c\x0a\x75\xe2\x04\x4a\x69\xac\x6e\xa6\xeb\xb3\x73\x9f\x4f\xe8\
\xd0\xf7\xb2\xd7\xcb\xa9\x3d\x35\x12\xc1\x18\x83\x3c\x03\x46\x5a\
\xea\x37\x98\x8e\xbe\xc8\xb6\xf8\xc0\x7a\x07\xd0\x1e\x63\x75\x23\
\x46\xe0\xeb\x4c\x37\xa2\xa0\xcb\x0a\xdc\x0c\x35\xf2\x5c\xc0\x6c\
\xd0\x90\xb1\x52\x34\x28\x6e\x11\x20\xcf\xf7\xf3\xca\x36\x57\xa5\
\x80\x35\xd6\x36\xc0\x8d\x30\xe8\xea\x76\x14\xfc\x24\xe0\x74\x23\
\x00\xb2\x0c\x30\x0c\x01\x17\x6f\xc5\xa0\x5e\xa4\xa9\x81\x17\xf9\
\x70\x4a\x92\x04\xdb\x3d\x83\x28\x64\x08\x17\x44\x46\xb7\xa2\x60\
\x45\xb7\x9b\xc1\x32\x01\x67\x22\xcf\x20\xa5\x1c\x96\xad\x9c\xbe\
\x77\xab\xfa\x57\x8f\x54\x11\x7c\x9f\xe4\x80\x0c\xb1\xc9\x10\xf9\
\xca\xe5\xde\x05\xcb\x12\x0f\x35\xc3\xaf\x92\x98\x3f\xc5\x3b\xe9\
\xf5\x80\x53\x30\x0c\xac\x91\x56\x04\x03\xc0\x24\x60\x21\x27\x6e\
\x4d\x42\x74\x92\x18\xa1\x07\x91\x81\x93\x66\x03\x05\xc3\xcd\x86\
\xf7\x51\x47\xb4\xb3\x90\x28\xa5\x5c\x65\x59\x5e\x6c\x8c\x02\x77\
\x31\xfa\xb7\xc2\x5a\x0b\x12\x6f\x75\x05\xea\xa3\x22\x66\x97\xd8\
\xaa\xa6\x67\xde\x68\xea\xad\xbc\xd0\x3c\x86\x3c\xcf\xc4\xc5\xc9\
\xdf\x56\xd6\xfe\xf2\xfd\x55\xd0\x9a\x10\x50\x77\x5e\x2f\xce\x3f\
\x7b\x3a\x3e\x7d\xd7\x44\xd1\x30\xbb\xf2\x8f\x23\x57\x4d\x3b\x4a\
\xcc\xf7\x57\x2f\x9f\x93\x9b\x08\x70\xa2\xd1\x6a\x5d\xda\x7b\x38\
\x74\x8c\x1b\x67\xba\xdb\xdb\xef\x84\xf9\xa1\x04\x7b\x00\xda\x38\
\xbe\xac\x78\x4b\x98\xd9\x2f\x71\xe5\xf9\x54\xda\xd5\x79\xa9\x00\
\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\
\x00\x00\x04\x6e\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x16\x00\x00\x00\x16\x08\x06\x00\x00\x00\xc4\xb4\x6c\x3b\
\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x04\xc2\x00\x00\x04\xc2\
\x01\xbc\xcf\x90\x18\x00\x00\x00\x07\x74\x49\x4d\x45\x07\xd7\x0c\
\x1b\x16\x0c\x0e\xd2\xa1\x06\x61\x00\x00\x00\x06\x62\x4b\x47\x44\
\x00\xff\x00\xff\x00\xff\xa0\xbd\xa7\x93\x00\x00\x03\xfb\x49\x44\
\x41\x54\x78\xda\xb5\x92\x5f\x68\x1c\x55\x14\xc6\xbf\xfb\x67\x66\
\x77\x36\xd9\x90\x0a\x4d\x49\xa4\xa4\x4d\x49\x97\xa0\x60\x12\x23\
\x44\x1a\x48\x45\xd2\x86\xe0\x43\x8c\x85\x9a\x06\xa1\xad\x10\x34\
\xa2\x28\x4a\xfc\x83\x88\xa0\x14\x2b\x62\x8d\x4f\x79\x90\x52\xfa\
\xd4\xa7\xfa\x58\x69\x28\x48\x15\x89\xa2\xd6\xda\x24\x26\x36\x6b\
\xc2\x6e\x53\x45\xc8\x6e\xb2\xbb\xd9\x9d\xd9\xb9\x33\xe3\x99\xdb\
\x6c\x5a\xd6\x22\xe2\x9f\x03\x1f\x73\xb8\x73\xbf\xdf\xf9\xf6\xec\
\xe0\xbf\xa8\x20\x08\x42\xed\x20\xd5\x57\xce\x18\x09\x99\x73\xe7\
\x76\x7b\xb3\xb3\xa7\xd7\xa7\xa6\x7a\x54\x36\xcb\x83\x8a\x81\xf4\
\x77\xfb\x7b\xf6\xed\x0b\xb6\xf5\xf7\xff\xbc\xba\xbc\xdc\xbf\x7b\
\x7c\x3c\x25\x41\xe5\x2d\x2f\x4d\x1a\x07\x0f\xee\x17\x5d\x5d\xe0\
\x9e\xf7\xd7\xe9\x70\xf7\xf2\xa4\x44\xc1\xf7\xdb\x56\x3f\x3d\xff\
\x11\x80\x21\x0d\x4e\x9e\x3d\xdb\x1b\x6f\xd8\x01\x55\x2e\xe3\xdf\
\x94\x13\x8f\x63\x65\x69\xb9\x1f\x54\x1a\x9c\x9d\x5f\x90\x46\x26\
\x73\xeb\x67\x31\x86\x74\x5d\x1d\x40\xcf\x9d\xb9\x1c\x98\xef\xdf\
\x3d\x39\xe7\xfa\x5e\x58\x3b\xd7\xd7\xc1\x68\xcf\x4c\x08\x14\x6d\
\xdb\xdc\x02\x7b\x24\x77\x63\x03\x21\xc2\x4e\x24\xb0\xff\xc0\x01\
\x30\x02\x7f\x7d\xe1\x02\xea\x92\x49\xa0\x1a\x4e\xd0\x5c\x4b\x0b\
\x1e\x19\x18\xd0\x7f\xdc\x0f\x17\x2f\x22\xba\xb0\x00\x6e\x9a\xf0\
\x2a\x57\x48\x50\x9b\x60\x45\x4a\xec\xdd\x4b\x3e\xae\xc1\x5d\x34\
\xc0\x6e\x6d\x85\x2a\x95\xf4\x3b\x92\xee\x4b\x74\xd6\xd9\xd7\xa7\
\xa1\x74\x57\x7b\x2a\xef\x14\x63\x55\xe0\x42\x01\x65\xd2\xc2\x99\
\x33\xb0\xd3\x69\x0a\xe9\x6b\x63\x5b\x6f\x2f\xd0\xd9\x09\x65\x17\
\xb5\xfc\x8e\x0e\x24\x7a\x7a\xe0\x79\x1e\x94\x52\x28\xa5\x52\xda\
\x43\x5e\x0d\xd6\x89\xb7\x56\x41\x53\xdd\x62\x51\x83\xc2\xba\x3a\
\x31\x81\xfb\xc6\xc6\x20\x9b\x9a\xf4\xd9\xae\xee\x6e\xdc\x94\x5c\
\xf7\x8d\x0f\x3e\x14\x42\x75\xaf\x56\x56\x30\x37\x39\x89\xc0\x75\
\xa1\x39\x8e\x03\xef\xce\xc4\xbe\x94\x7a\x15\xe5\x8a\xd6\xd6\x30\
\x77\xea\x7d\xa8\x1b\xa9\x10\xa2\xd3\x37\xb4\x77\x62\xfb\x03\x1d\
\x61\x4a\x2d\x7f\x25\x8d\x85\x8f\x3f\x80\xca\xad\xc1\xa5\xa4\x3c\
\x12\x81\x9b\xcf\xa1\x6c\xdb\x77\x24\x16\x1c\x6b\x8b\x8b\x10\x96\
\x05\x23\x66\x21\x6a\x19\x80\x0f\x24\x4f\xbd\x83\x3d\xcf\xbf\x0a\
\xbf\xa1\xa9\x32\x40\x27\x8d\xe5\x32\xb8\x71\x7a\x02\xd2\xb3\xe1\
\xe4\xd6\x91\xff\x3d\x8b\xe4\xcc\x4f\x10\xa6\x01\xb7\xec\xdc\x06\
\xfb\x04\xce\x5c\xbb\x06\x8f\x92\x58\x51\x81\x78\x7d\x84\x64\xc1\
\xaf\x8d\x62\xfa\x8b\xcf\xd1\xfe\xf8\x93\x1a\x5a\x81\x5f\xb9\xf4\
\x19\xc4\xa5\xf3\x70\x8a\x2e\x4a\xc4\x29\x86\x21\x15\xc0\x62\xd1\
\xea\x55\x08\x80\x01\xc4\x87\x29\x3c\x08\x55\x04\x77\xf2\x58\x7f\
\xec\x29\x74\x0c\x0d\xeb\x94\xa4\x2d\xf8\xae\x81\x27\xe0\x1c\x7b\
\x05\x56\x8d\x81\xa8\x09\x44\x0c\xf2\x49\xf2\x4b\x5e\x0d\xe6\xd4\
\x31\x48\x09\xad\x88\x65\xc2\x1f\x7d\x0d\x0f\x1f\x1f\x83\x10\x42\
\x7f\x7a\x75\x37\xe7\x50\xff\xdb\x7c\x38\x40\xc3\x13\x83\x23\x08\
\x46\xdf\x84\x49\x6b\x33\x08\x6c\x84\x60\x33\x04\xe3\x36\x38\x10\
\x9c\xb8\x04\x0e\x13\x53\x04\xeb\xc5\xb7\x09\xfa\x1c\x24\x4d\xe1\
\x9c\x13\x74\x16\xfc\xc3\x23\x30\x27\x46\xd0\x90\x59\x24\x90\xa1\
\x75\xff\xe1\xa3\xa8\x7d\xf9\x04\x0c\xf2\xd0\x7c\xc8\x3f\x27\x66\
\xba\xe3\xa4\xc6\xd7\xdf\x45\xf7\xb1\x67\x42\xa3\x06\xc7\x52\x3f\
\x42\x9d\x3c\x8c\x18\xb7\x51\x6b\x38\x1a\xbe\x7d\x35\x89\x68\x34\
\x0a\xd3\x34\xd1\x7e\xe4\x69\xdc\xfb\xc6\x49\xed\x15\x12\x04\x46\
\x15\x78\xf3\xa0\xb9\x65\x8f\x4e\xa9\x75\xfd\x7b\x64\xdf\x3a\x04\
\xe6\xda\x60\xe1\x6c\x12\x53\x0e\x9c\x13\x34\x28\x3d\x8b\x48\x24\
\xa2\xef\x35\x35\x37\xdf\x82\x85\x9c\x4a\x62\xda\x19\x0b\x0c\xae\
\xc1\x7e\x00\x4c\x8f\x0e\x23\xff\xcd\x65\xd8\x57\xbf\xc2\xf2\x4b\
\x83\x70\x4b\x36\xca\x0a\x28\x3a\x40\xa1\x04\x38\x65\xc0\xb5\x1d\
\xfc\x3a\x3e\x04\x35\x33\x8d\x8d\x6f\xbf\xc4\x77\xcf\x0e\x6b\x2f\
\x13\xac\xc2\x85\x24\x59\xdb\x12\xad\x7e\xb6\x30\x23\x38\x19\xc1\
\x81\x2b\x63\x87\x50\x13\x05\x62\x16\x41\x84\x09\x67\x73\x28\xf3\
\x01\x0f\x40\x99\x93\x02\x1f\xf3\x2f\x0c\x62\xc3\x06\x02\x46\xa0\
\x1a\x0b\x22\x56\x0b\xdf\x5b\x53\x15\xb0\xa3\x58\xfc\x72\x7d\x7b\
\xdb\xa3\xce\xd2\x2f\x90\x26\x11\x22\x04\x30\x09\x4a\xb2\x0d\xea\
\x49\x92\x23\x2c\x3d\x40\x49\x02\xd3\x99\x32\x09\x6a\x01\x3c\x06\
\x58\x66\x1c\x99\x3c\x83\xab\xfc\x29\x0d\x66\x8c\x79\xef\x35\x36\
\x8e\xd8\x85\xc2\x27\xa4\x3e\x5a\x8d\xc4\x3f\x28\x21\x33\x2a\x00\
\xa6\x02\xa5\x8e\xe3\xff\xac\x3f\x00\x96\xb0\x06\xcd\xf7\xa2\xd6\
\x6c\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\
\x00\x00\x03\x69\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x16\x00\x00\x00\x16\x08\x06\x00\x00\x00\xc4\xb4\x6c\x3b\
\x00\x00\x00\x04\x73\x42\x49\x54\x08\x08\x08\x08\x7c\x08\x64\x88\
\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x03\x76\x00\x00\x03\x76\
\x01\x7d\xd5\x82\xcc\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\
\x74\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\
\x70\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x02\xe6\x49\x44\
\x41\x54\x78\xda\x95\x95\xdb\x6b\xd3\x60\x18\x87\x9f\xa4\x87\xd5\
\x0d\x75\x58\xa7\x76\xed\xa4\x2a\xa2\x20\x08\x0a\x22\x08\xca\x64\
\x88\x07\x10\x2f\xbd\x51\x99\xb7\x83\xca\xdc\xcd\xfc\x13\x04\x41\
\x10\x74\xe0\x3f\x20\x0c\xf4\x56\xbd\x11\x77\xd0\xe1\xc4\x55\x50\
\x91\x3a\x68\xa7\x3d\xcc\xa5\x9e\x36\xd7\xd9\xae\x69\xf3\x99\x2f\
\xf5\xa3\x9d\x81\x6e\x7b\xe0\xc7\x9b\x84\xe6\xe1\x97\x97\x90\x6a\
\x42\x08\xd6\x83\x76\x4f\xf3\x10\x20\xa6\x7b\xf4\xab\x11\x5f\x24\
\x24\x5a\x44\x4b\x6e\x21\x37\x6d\x61\x3d\x64\x37\xb7\xc5\x49\x61\
\x02\x68\x40\xd4\xc9\x5a\x38\x40\x3b\x7d\x0c\xf5\x1c\xec\x09\x5d\
\x0c\x5d\x84\xf2\x3f\x83\x0f\x86\x53\xc3\x3c\xfb\xf0\x2c\x49\x90\
\x63\xe2\x8a\xc8\x6b\x40\x77\x26\x9b\x7b\xae\xeb\x1a\x9a\xa6\x53\
\x9b\x9a\x3d\x75\x00\x79\xec\xa4\x22\x4c\x4e\x3c\x3d\x41\xb0\x23\
\xc8\xd9\x3d\x67\xf9\x9a\x9b\xe5\xde\xf1\x21\x24\xd7\x5f\xf6\xb1\
\x35\xd4\xc9\xe3\xe4\x13\x26\xa6\x27\x32\xc0\x2e\x1d\x90\x12\x57\
\x94\x5c\xe5\x7e\xea\x3e\x33\xd6\x0c\x91\x8e\x08\xc9\xf2\x47\x8c\
\xc5\x04\x8a\xef\x85\x04\x3f\xc5\x47\xa2\xdb\x22\xf8\x43\xfe\x2e\
\x7c\xf4\x7b\x01\xd9\xb2\x51\xe8\x0e\xf0\x28\xf9\x08\xe1\x11\x8c\
\x4e\x8d\x10\x0e\x04\x20\x5f\x84\x73\x38\x7c\x99\xfe\xc0\xb7\x85\
\x24\xb9\xe5\x12\xc2\x2f\x40\xa7\x57\x8a\x5d\x52\xdd\x2d\x27\x55\
\x48\x61\x7e\x37\x99\x1b\x34\xf8\x9f\xb1\x58\x1e\x85\xf7\x96\x06\
\x9b\xe9\xd0\x01\xd7\xa3\x6b\xb5\xac\x38\x6f\x6d\x6f\x05\x8d\x55\
\xd1\xbd\xc0\x26\x02\x72\x28\xe9\xca\xb6\x8d\x6b\x01\x82\x1b\x83\
\x18\x7b\x0d\xda\x86\x34\x22\x1b\xa0\xed\x17\xc4\x07\x04\x92\x53\
\x77\x35\xd8\x0a\xe9\x22\x54\xbb\x90\xa4\x6a\x8d\xeb\x2b\x50\x6d\
\xe5\x71\x3d\xf6\x79\x6f\xb4\x17\xbc\xf0\x27\x0c\xda\x4e\xf0\x77\
\x82\x22\x10\xb1\xb3\x1b\x7e\x77\x82\x15\x00\xbc\x3c\x90\xe2\x95\
\xed\x6a\x32\xd7\x5b\x11\x8b\xc6\x88\xb6\x45\xa1\x0a\x33\xf3\x30\
\x57\x02\x45\xa6\x08\x6f\xbe\xc1\xdc\x22\xe0\xe7\x13\x4b\xdc\x71\
\xde\xe3\xf9\x85\x85\xe7\xaa\xed\x8a\xf9\x2f\x6a\x5d\xf9\x72\x9e\
\x9e\xf7\x3d\x24\xe6\x13\x50\x02\xdf\x0f\x79\x1d\x2a\x5b\xc0\xf2\
\x00\x9b\xc9\x30\xcf\x11\x71\x5e\x18\xba\xba\xa9\x21\x2e\xa9\x9a\
\xdb\x5b\xb6\xf3\xf6\xf0\x5b\x6e\xee\xbd\xc9\xa1\xae\x43\x04\xf6\
\x6f\x64\xcb\xbe\x1d\x58\x3e\x3e\xd3\xca\x00\x21\x76\x49\x29\x80\
\xd3\xf8\xf7\xe2\xa2\x6c\xdc\xf8\x76\xb8\xc4\xf5\xe9\xc6\xe3\xf1\
\x9c\x14\x42\x8c\xd0\x80\xb7\x66\x77\xb7\x56\xac\x26\x77\x53\x17\
\xd7\x65\x75\x69\xd3\xc6\x76\x3b\x2c\xcb\x92\xb3\xa9\xb8\x2e\x85\
\xa6\x8d\x8b\xc5\x22\xe9\x74\x9a\xa5\xa5\x25\xca\xe5\xb2\x23\x37\
\x0c\x23\x07\xcc\x82\x9b\x6e\xfb\x87\xc2\xbe\x49\x2c\x2f\x2f\x0b\
\xfb\x06\x61\x9a\xa6\xa8\x54\x2a\x4e\xaa\xd5\xaa\xb0\x05\x4e\xa6\
\xa6\xa6\xd4\xb1\x73\x7d\x7c\x7c\xac\x18\x0e\x87\x8f\xca\xe6\xff\
\x47\x7d\x1b\x6b\xa9\xe3\xda\xa7\x6c\x57\x28\x14\x50\xab\x78\xfd\
\x7a\xd2\xbc\x76\xad\xef\x4c\x36\x9b\x9d\xc4\x4d\x4d\xac\xa9\x34\
\x91\x4b\xb1\xfd\x44\x8e\x74\x72\xf2\x95\x39\x38\x78\xe3\x42\x3c\
\xfe\x7e\xb4\xe9\x8e\xdd\x22\x37\xf6\x5a\x6c\xb9\xe0\xc5\x8b\xf1\
\x52\x7f\x7f\xec\x74\x3c\xfe\x6e\x8c\x26\xe8\xac\x11\x7b\xa7\xe4\
\xf3\xc6\xec\xa5\x4b\x97\x8f\xaf\x26\x5d\xff\x7f\x1e\xa4\x85\x10\
\x29\xd6\xc0\x5f\xde\x98\x4d\x4f\xc1\x1f\x40\x71\x00\x00\x00\x00\
\x49\x45\x4e\x44\xae\x42\x60\x82\
\x00\x00\x04\xd1\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x16\x00\x00\x00\x16\x08\x06\x00\x00\x00\xc4\xb4\x6c\x3b\
\x00\x00\x00\x04\x73\x42\x49\x54\x08\x08\x08\x08\x7c\x08\x64\x88\
\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x03\x76\x00\x00\x03\x76\
\x01\x7d\xd5\x82\xcc\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\
\x74\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\
\x70\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x04\x4e\x49\x44\
\x41\x54\x78\xda\xb5\x94\x6d\x6c\x14\x45\x18\xc7\x7f\x7b\xaf\xa5\
\xd2\x2a\x0d\xa8\xf4\x8d\x96\x4a\x5b\x04\x6c\x0a\xa9\xad\x62\xad\
\x40\x4c\x4b\x82\x2f\x88\x91\x0f\x5a\x93\x2a\xd8\x8a\x5a\xac\x96\
\x62\xf1\x05\x25\x11\x21\x20\x2f\x91\xd4\x40\x42\x50\xa3\x09\x31\
\x41\x48\x20\x9a\x16\x0c\x55\xb1\x46\x50\xd0\x04\x84\xa4\x2d\x0d\
\xb4\x5c\x4b\x4b\x7a\xd7\x1e\x77\xdb\xbb\xd9\xbb\x75\xe7\x36\xd9\
\xde\x59\xf9\xe0\x07\xff\x97\xe7\x66\x36\x33\xf3\x9b\xff\x3e\xb3\
\xcf\x38\x74\x5d\xe7\xff\x90\x03\x60\x69\x65\x55\x4f\x20\x10\xc8\
\xb1\xd9\x6d\xac\x7d\x73\x3d\x4e\xa3\x25\x7e\x43\x9b\x02\x28\x28\
\x4a\xec\x1f\x20\xd6\x37\x5b\x85\x90\xd0\xd8\xb9\x6d\x0b\xd1\x48\
\x94\xbc\xbc\xbc\xbe\x03\x9f\x7f\x96\x15\x03\x07\xd5\x60\x4e\x43\
\x43\x03\x5d\xdd\xdd\x94\x3c\x58\xce\xed\xc9\x49\x98\x58\x24\xc6\
\x02\x59\x70\x13\x68\x84\xd9\x8e\x04\x54\xba\x2e\x5e\x20\x12\x89\
\xd0\xda\xd6\x9a\x69\x39\x8e\x46\xa3\xec\xd8\xb9\x83\x82\xfc\x02\
\x84\xa6\x19\x06\x15\x0b\x6c\xc1\x4d\x20\x51\xa1\xe2\x59\xd7\x48\
\x68\xe8\x06\x19\xcd\xcd\xa4\x14\xcf\x47\x68\x51\x3a\x3b\x3b\x25\
\xd8\x60\xe9\x58\x60\x99\x67\xcd\x00\xca\x0d\x24\xd4\xe9\xb4\xd1\
\x7a\xa6\x8b\x09\xd2\x75\x72\x7d\x6b\xd1\xb3\xdd\x4c\xea\xe8\xe1\
\x68\x45\x05\x0f\x1f\x3e\x82\x63\x7e\xa9\x5c\x1b\x0b\x5d\x8f\x92\
\xe0\xb8\xb0\xa0\x30\xb6\x81\x62\x33\xc0\x76\x85\x65\x65\xb3\xfe\
\xc9\xe4\x62\x7b\x23\x79\x69\x1e\x9e\x3a\x21\x28\x0b\x0a\x1e\x12\
\x82\x1f\x57\xaf\xa6\xe2\xf4\x1f\xd2\xad\x0c\x99\xe7\x44\xc7\x12\
\x2e\xf3\x15\x31\x06\xd4\xb0\xc6\xf7\x67\x7b\x88\x57\xb0\xe7\x2b\
\x9e\xce\x6f\xe3\xd9\x4d\x1a\xbf\x5f\x18\x26\x3c\xd3\x80\x3f\x9e\
\x8a\xed\xf2\x5c\x44\x24\x2a\xa1\xa6\x6b\x5d\x4f\x70\x2c\x07\x4c\
\xb0\xd1\x57\x43\x1a\x0b\xe7\x64\x59\xd0\xfe\xce\xef\x8c\xfc\x7f\
\xc3\xba\x16\xf8\xe5\xcf\x20\xd3\x52\x03\x6c\xab\x85\xd0\x6d\x8f\
\x30\x58\x5a\x43\x24\x0e\xac\x47\x6f\xe1\x58\x8b\xe8\x8c\x85\x05\
\x67\x3b\x07\x90\x12\xbe\x0b\x54\xa5\x6d\x63\xcf\x61\xc1\xb1\x53\
\x86\xa3\xd0\x10\x2d\x6f\x39\xf0\x2b\xb9\x1c\x39\x5f\xce\x13\x55\
\xb9\xf2\xc0\x24\xd8\xe4\xe8\xf1\x60\xf9\x0a\xc6\x00\x60\x39\x9e\
\x9d\x3d\x95\x31\x7f\x1f\x33\x1c\xfb\x69\x3f\xed\xe5\xd3\xc3\x3a\
\x23\xde\xeb\x1c\xd8\xe0\x26\x75\x4a\x1a\x87\x2e\x3d\xc9\xfd\xc5\
\xf7\x71\x67\x7a\x56\x2c\x15\x51\x13\x9c\xe8\x58\xe6\x45\x02\xa5\
\x84\x88\x20\xbb\x91\xf0\x28\x33\x82\xbb\xe8\xec\xea\xa2\x79\xaf\
\x9d\x11\xdf\x10\x5b\xea\x6c\xe4\x66\xba\xd8\xd7\xb1\x84\xbb\x73\
\xa6\x33\xeb\xde\xa2\xd8\x79\xe8\x80\x26\x8d\x99\xac\x78\xc7\x66\
\x2a\xa4\x36\x35\xae\x41\x21\xca\xc6\xd5\x49\x5c\xf3\xff\xc4\xaa\
\x2d\x93\xf1\xfa\x82\xac\xaa\xf2\x52\x3e\xcf\x45\xdd\xce\x14\x06\
\x46\x7e\x26\x6f\xe6\x00\xbf\x9e\x6c\x25\x41\x26\x2b\xde\xb1\x95\
\x8a\x98\xd6\x2c\x0f\x90\x73\xcf\x42\x56\xd4\x5e\xe2\xa6\xaa\xb2\
\x64\xde\x00\x75\xcb\x5d\xd4\x7f\x32\x99\x6e\x8f\x8d\xc2\xfc\x4c\
\x14\x30\xd7\x24\xca\x32\x38\xc1\xf1\x22\x03\x52\xb1\xb8\x9a\x95\
\xb5\xfb\xb8\xe2\x11\xcc\x9a\xd6\xcb\xe6\x5a\x07\xef\x1d\x48\xa2\
\xe3\x3c\x06\x34\x1b\xa7\xd3\x69\xce\x9f\xa8\x89\x05\x22\x2b\x2f\
\x3b\xad\x9f\xfa\x97\x9f\xa1\x6e\xfd\x7e\xfe\xea\x11\x4c\x4b\xbe\
\x4e\x4b\xa3\x8d\x2f\x4f\xde\xc1\xe9\xcb\x53\x69\xde\xf0\x02\x95\
\x95\x95\x96\xb3\xda\x97\x6a\xf1\xfb\x47\xcd\xb5\x99\x59\x48\x45\
\xe2\x0b\x44\x7e\x2a\x53\x92\x06\xd9\xf3\x6e\x31\x4d\x1f\x7c\xc1\
\x0f\x67\x75\x52\x5c\xa3\xec\x6d\x0c\x73\xfc\x8c\x83\x5d\x5f\xc3\
\xd2\xa5\x25\x94\x94\x94\x30\x3c\x3c\x6c\x5d\x01\x19\xe9\xe9\x0c\
\x0e\x3a\xf0\x79\xbd\x08\x21\x30\x59\xda\x38\xd8\xae\xe8\xbc\xf3\
\xa2\x9b\xed\x2d\xc7\x38\x7a\x2a\x8d\x64\x97\xc6\xee\x57\x7c\xf4\
\x0e\x39\x79\xf5\x63\x95\xb2\x07\x16\x50\x5d\x5d\x2d\x17\xcb\x90\
\xd0\x58\x44\x24\x4c\xd7\x91\x3f\x4d\x08\xec\x76\xbb\x34\x39\x0e\
\x5e\xbc\x70\x0e\xee\xbc\xd7\xf8\xf6\xdc\x3a\x1c\x76\x1f\x1b\x9f\
\xeb\x27\x39\xd9\xcd\xb2\xa6\x00\x49\x93\x26\x53\x5f\x5f\x8f\xaa\
\xaa\x09\x50\x19\x21\x21\xac\x1b\x4d\xde\x8a\xe9\x19\x19\x5c\xed\
\xeb\x1d\x07\x3f\xba\xa8\x14\xa1\xf6\xf1\x51\x53\x39\xed\xc7\x0f\
\x52\xbe\x60\x0a\x2b\xde\x4e\x36\x26\x4e\xc7\xed\x76\xc7\x2a\x72\
\x74\xd4\xcc\x65\x7c\xa8\x63\x2a\xa1\xd0\x98\xf9\x2c\x04\x7e\x63\
\x8e\xe5\x78\xd3\x1b\x2b\x53\xe7\x16\xcd\xd5\x47\x07\xcf\x29\xea\
\xf0\x79\x72\x66\x14\x71\xe2\xda\x22\xea\x5e\xcf\x22\x2c\xc2\xf2\
\x90\xfe\x15\x2a\xdd\x07\x6f\x06\x18\x53\xc7\x10\xe1\x30\xc2\xe5\
\xc2\xe3\xf1\x8c\x83\x35\x1c\x1f\xbe\xbf\xfd\xa0\x52\xf3\x58\x46\
\xff\xa1\xb6\xab\x77\x5d\xf1\xf8\x6d\xcf\xd7\xcc\xc7\xe5\x52\xad\
\xfa\x37\xe0\x56\xc4\xeb\x9a\x01\x0a\x87\x43\x00\x32\x55\x26\xd0\
\xe9\x08\xc4\xda\x11\xef\x8d\xbe\xd2\xd9\x29\x25\x0d\x9b\xdb\x7e\
\x6b\xd8\xcc\x7f\xd2\xd6\xad\x5b\xb9\x95\xfe\x06\x57\x6a\xa9\xaf\
\x9a\x2c\x10\x30\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\
\
"
qt_resource_name = "\
\x00\x05\
\x00\x35\x9b\x52\
\x00\x32\
\x00\x32\x00\x78\x00\x32\x00\x32\
\x00\x05\
\x00\x34\xdb\x46\
\x00\x31\
\x00\x36\x00\x78\x00\x31\x00\x36\
\x00\x07\
\x0c\xb5\xfa\x9e\
\x00\x66\
\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\
\x00\x09\
\x02\x7b\x8e\x27\
\x00\x66\
\x00\x65\x00\x5f\x00\x34\x00\x38\x00\x2e\x00\x70\x00\x6e\x00\x67\
\x00\x09\
\x02\x49\x8e\x27\
\x00\x66\
\x00\x65\x00\x5f\x00\x31\x00\x36\x00\x2e\x00\x70\x00\x6e\x00\x67\
\x00\x09\
\x02\x65\x8e\x27\
\x00\x66\
\x00\x65\x00\x5f\x00\x33\x00\x32\x00\x2e\x00\x70\x00\x6e\x00\x67\
\x00\x09\
\x02\x55\x8e\x27\
\x00\x66\
\x00\x65\x00\x5f\x00\x32\x00\x32\x00\x2e\x00\x70\x00\x6e\x00\x67\
\x00\x11\
\x01\xa6\xc4\x87\
\x00\x64\
\x00\x6f\x00\x63\x00\x75\x00\x6d\x00\x65\x00\x6e\x00\x74\x00\x2d\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x2e\x00\x70\x00\x6e\x00\x67\
\
\x00\x14\
\x07\x40\xa2\xc7\
\x00\x61\
\x00\x70\x00\x70\x00\x6c\x00\x69\x00\x63\x00\x61\x00\x74\x00\x69\x00\x6f\x00\x6e\x00\x2d\x00\x65\x00\x78\x00\x69\x00\x74\x00\x2e\
\x00\x70\x00\x6e\x00\x67\
\x00\x10\
\x0c\xbc\x2e\x67\
\x00\x64\
\x00\x6f\x00\x63\x00\x75\x00\x6d\x00\x65\x00\x6e\x00\x74\x00\x2d\x00\x6e\x00\x65\x00\x77\x00\x2e\x00\x70\x00\x6e\x00\x67\
\x00\x14\
\x0b\xa9\xab\x27\
\x00\x64\
\x00\x6f\x00\x63\x00\x75\x00\x6d\x00\x65\x00\x6e\x00\x74\x00\x2d\x00\x73\x00\x61\x00\x76\x00\x65\x00\x2d\x00\x61\x00\x73\x00\x2e\
\x00\x70\x00\x6e\x00\x67\
"
qt_resource_struct = "\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x01\
\x00\x00\x00\x10\x00\x02\x00\x00\x00\x04\x00\x00\x00\x0c\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x04\x00\x00\x00\x08\
\x00\x00\x00\x20\x00\x02\x00\x00\x00\x04\x00\x00\x00\x04\
\x00\x00\x00\x4c\x00\x00\x00\x00\x00\x01\x00\x00\x09\x1d\
\x00\x00\x00\x7c\x00\x00\x00\x00\x00\x01\x00\x00\x10\x8f\
\x00\x00\x00\x64\x00\x00\x00\x00\x00\x01\x00\x00\x0b\xb4\
\x00\x00\x00\x34\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\
\x00\x00\x00\x94\x00\x00\x00\x00\x00\x01\x00\x00\x1f\x71\
\x00\x00\x00\xbc\x00\x00\x00\x00\x00\x01\x00\x00\x22\x91\
\x00\x00\x01\x10\x00\x00\x00\x00\x00\x01\x00\x00\x2a\x70\
\x00\x00\x00\xea\x00\x00\x00\x00\x00\x01\x00\x00\x27\x03\
\x00\x00\x00\x94\x00\x00\x00\x00\x00\x01\x00\x00\x14\x0e\
\x00\x00\x00\xbc\x00\x00\x00\x00\x00\x01\x00\x00\x16\x91\
\x00\x00\x01\x10\x00\x00\x00\x00\x00\x01\x00\x00\x1c\x26\
\x00\x00\x00\xea\x00\x00\x00\x00\x00\x01\x00\x00\x19\xdf\
"
def qInitResources():
QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data)
def qCleanupResources():
QtCore.qUnregisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data)
qInitResources()
| Python |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 by Igor E. Novikov
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
from PyQt4 import QtGui, Qt
from uc2.utils import system
from fe import events, app_conf
from fe import config
import mainwindow, iconfactory, view
class Application(QtGui.QApplication):
"""Provides main Formats Explorer application instance."""
proxy = None
config = None
appdata = None
mw = None
generic_icons = {}
current_doc = None
docs = []
def __init__(self, packagedir):
"""
Constructs an instance.
packagedir - Formats Explorer package location.
The value is needed for correct resource uploading.
"""
QtGui.QApplication.__init__(self, sys.argv)
self.events = events
self.appdata = app_conf.AppData()
self.config = config
self.config.load(self.appdata.app_config)
self.generic_icons = iconfactory.get_app_icons(self)
import actions
self.actions = actions.create_actions(self)
self.mw = mainwindow.MainWindow(self)
def run(self):
events.emit(events.NO_DOCS)
msg = 'To start open existing document'
events.emit(events.APP_STATUS, msg)
self.mw.show()
self.exec_()
def update_config(self):
if self.mw.windowState() == Qt.Qt.WindowMaximized:
if self.config.os != system.MACOSX:
self.config.mw_maximized = 1
else:
self.config.mw_maximized = 0
self.config.mw_width = self.mw.width()
self.config.mw_height = self.mw.height()
def app_exit(self):
self.update_config()
self.config.save(self.appdata.app_config)
sys.exit(self.exit())
def close(self, view):
pass
return True
def new(self):
doc = view.ModelView(self)
self.docs.append(doc)
self.set_current_doc(doc)
# self.mw.menubar.rebuild_window_menu()
# self.mw.set_title()
events.emit(events.APP_STATUS, self.tr('New document created'))
def open(self):
pass
def save_as(self):
pass
def set_current_doc(self, doc):
self.current_doc = doc
events.emit(events.DOC_CHANGED, doc)
| Python |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 by Igor E. Novikov
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from PyQt4 import QtGui
from fe import events
class AppMenuBar(QtGui.QMenuBar):
def __init__(self, mw):
QtGui.QMenuBar.__init__(self, mw)
self.mw = mw
self.build()
def build(self):
actions = self.mw.app.actions
#--- FILE ---
self.file_menu = self.addMenu('&File')
self.file_menu.addAction(actions['NEW'])
self.file_menu.addSeparator()
self.file_menu.addAction(actions['OPEN'])
self.file_menu.addAction(actions['SAVE_AS'])
self.file_menu.addSeparator()
self.file_menu.addAction(actions['EXIT'])
#--- WINDOW ---
self.window_menu = self.addMenu('&Window')
#--- FILE ---
self.help_menu = self.addMenu('&Help')
| Python |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 by Igor E. Novikov
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from PyQt4 import QtGui, QtCore
from fe import events
class AppAction(QtGui.QAction):
mode = None
def __init__(self, icon, text, obj, method, shortcut='',
channels=[], validator=None):
QtGui.QAction.__init__(self, icon, text, obj)
if shortcut:
self.setShortcut(shortcut)
self.method = method
obj.connect(self, QtCore.SIGNAL('triggered()'), method)
self.channels = channels
self.validator = validator
if channels:
for channel in channels:
events.connect(channel, self.receiver)
def receiver(self, *args):
self.setEnabled(self.validator())
def create_actions(app):
actions = {}
actions['NEW'] = AppAction(app.generic_icons['NEW'],
app.tr('New'),
app, app.new,
'Ctrl+N')
actions['OPEN'] = AppAction(app.generic_icons['OPEN'],
app.tr('Open...'),
app, app.open,
'Ctrl+O')
actions['SAVE_AS'] = AppAction(app.generic_icons['SAVE_AS'],
app.tr('Save As...'),
app, app.save_as)
actions['EXIT'] = AppAction(app.generic_icons['EXIT'],
app.tr('Exit'),
app, app.app_exit,
'Ctrl+Q')
return actions
| Python |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 by Igor E. Novikov
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from PyQt4 import Qt, QtGui, QtCore
from menubar import AppMenuBar
from maintoolbar import AppMainBar
from color import qt_middle_color
class MainWindow(QtGui.QMainWindow):
"""
The class represents main application window.
app - Formats Explorer Application class instance
"""
mdiArea = None
app = None
def __init__(self, app):
super(MainWindow, self).__init__()
self.app = app
self.set_title()
self.setWindowIcon(app.generic_icons['FE'])
self.mdiArea = QtGui.QMdiArea()
self.setCentralWidget(self.mdiArea)
self.mdiArea.setDocumentMode(True)
clr = qt_middle_color(self.palette().text().color(), self.palette().background().color(), 0.4)
self.mdiArea.setBackground(Qt.QBrush(clr))
self.menubar = AppMenuBar(self)
self.setMenuBar(self.menubar)
self.maintoolbar = AppMainBar(self)
self.addToolBar(self.maintoolbar)
self.setMinimumSize(self.app.config.mw_min_width, self.app.config.mw_min_height)
self.resize(self.app.config.mw_width, self.app.config.mw_height)
if self.app.config.mw_maximized:
self.setWindowState(Qt.Qt.WindowMaximized)
screen = QtGui.QDesktopWidget().screenGeometry()
size = self.geometry()
self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 3)
def closeEvent(self, event):
self.app.app_exit()
def set_title(self):
app_name = self.app.appdata.app_name
self.setWindowTitle(app_name)
| Python |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 by Igor E. Novikov
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
from app_conf import get_app_config
global config
config = None
def fe_run():
"""Formats Explorer application launch routine."""
global config
_pkgdir = __path__[0]
config = get_app_config(_pkgdir)
from application import Application
app = Application(_pkgdir)
app.run()
| Python |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 by Igor E. Novikov
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from PyQt4 import Qt
def gtk_to_tk_color(color):
"""
Converts gtk color representation to tk.
For example: #0000ffff0000 will be converted to #00ff00
"""
return color[0] + color[1] + color[2] + color[5] + color[6] + color[9] + color[10]
def tkcolor_to_rgb(tkcolor):
"""
Converts tk color string as tuple of integer values.
For example: #ff00ff => (255,0,255)
"""
return (int(tkcolor[1:3], 0x10), int(tkcolor[3:5], 0x10), int(tkcolor[5:], 0x10))
def rgb_to_tkcolor(r, g, b):
"""
Converts integer values as tk color string.
For example: (255,0,255) => #ff00ff
"""
return '#%02X%02X%02X' % (r, g, b)
def saturated_color(color):
"""
Returns saturated color value.
"""
r, g, b = tkcolor_to_rgb(color)
delta = 255 - max(r, g, b)
return rgb_to_tkcolor(r + delta, g + delta, b + delta)
def middle_color(dark, light, factor=0.5):
"""
Calcs middle color value.
dark, light - tk color strings
factor - resulted color shift
"""
dark = tkcolor_to_rgb(dark)
light = tkcolor_to_rgb(light)
r = dark[0] + (light[0] - dark[0]) * factor
g = dark[1] + (light[1] - dark[1]) * factor
b = dark[2] + (light[2] - dark[2]) * factor
return rgb_to_tkcolor(r, g, b)
def lighter_color(color, factor):
"""
Calcs lighted color value according factor.
color - tk color strings
factor - resulted color shift
"""
return middle_color(color, saturated_color(color), factor)
def qt_saturated_color(qcolor):
"""
Returns saturated QColor value.
"""
r, g, b = tkcolor_to_rgb(str(qcolor.name()))
delta = 255 - max(r, g, b)
return Qt.QColor(rgb_to_tkcolor(r + delta, g + delta, b + delta))
def qt_middle_color(dark, light, factor=0.5):
"""
Calcs middle QColor value.
dark, light - QColor instances
factor - resulted color shift
"""
dark = tkcolor_to_rgb(str(dark.name()))
light = tkcolor_to_rgb(str(light.name()))
r = dark[0] + (light[0] - dark[0]) * factor
g = dark[1] + (light[1] - dark[1]) * factor
b = dark[2] + (light[2] - dark[2]) * factor
return Qt.QColor(rgb_to_tkcolor(r, g, b))
def qt_lighter_color(color, factor):
"""
Calcs lighted QColor value according factor.
color - QColor instance
factor - resulted color shift
"""
return Qt.QColor(qt_middle_color(color, qt_saturated_color(color), factor))
| Python |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 by Igor E. Novikov
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
The package provides Qt-like signal-slot functionality
for internal events processing.
Signal arguments:
CONFIG_MODIFIED arg[0] - [attr, value]
APP_STATUS arg[0] - statusbar message
NO_DOCS no args
DOC_MODIFIED arg[0] - presenter instance
DOC_CHANGED arg[0] - actual presenter instance
DOC_SAVED arg[0] - saved presenter instance
DOC_CLOSED no args
MODE_CHANGED arg[0] - canvas MODE value
SELECTION_CHANGED arg[0] - presenter instance
CLIPBOARD no args
"""
#Signal channels
CONFIG_MODIFIED = ['CONFIG_MODIFIED']
APP_STATUS = ['APP_STATUS']
NO_DOCS = ['NO_DOCS']
DOC_MODIFIED = ['DOC_MODIFIED']
DOC_CHANGED = ['DOC_CHANGED']
DOC_SAVED = ['DOC_SAVED']
DOC_CLOSED = ['DOC_CLOSED']
MODE_CHANGED = ['MODE_CHANGED']
SELECTION_CHANGED = ['SELECTION_CHANGED']
CLIPBOARD = ['CLIPBOARD']
def connect(channel, receiver):
"""
Connects signal receive method
to provided channel.
"""
if callable(receiver):
try:
channel.append(receiver)
except:
msg = "Cannot connect to channel:"
print msg, channel, "receiver:", receiver
def disconnect(channel, receiver):
"""
Disconnects signal receive method
from provided channel.
"""
if callable(receiver):
try:
channel.remove(receiver)
except:
msg = "Cannot disconnect from channel:"
print msg, channel, "receiver:", receiver
def emit(channel, *args):
"""
Sends signal to all receivers in channel.
"""
# print 'signal', channel[0]
try:
for receiver in channel[1:]:
try:
if callable(receiver):
receiver(args)
except:
pass
except:
print "Cannot send signal to channel:", channel
| Python |
#!/usr/bin/python2.6
#
# Simple http server to emulate api.playfoursquare.com
import logging
import shutil
import sys
import urlparse
import SimpleHTTPServer
import BaseHTTPServer
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""Handle playfoursquare.com requests, for testing."""
def do_GET(self):
logging.warn('do_GET: %s, %s', self.command, self.path)
url = urlparse.urlparse(self.path)
logging.warn('do_GET: %s', url)
query = urlparse.parse_qs(url.query)
query_keys = [pair[0] for pair in query]
response = self.handle_url(url)
if response != None:
self.send_200()
shutil.copyfileobj(response, self.wfile)
self.wfile.close()
do_POST = do_GET
def handle_url(self, url):
path = None
if url.path == '/v1/venue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/addvenue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/venues':
path = '../captures/api/v1/venues.xml'
elif url.path == '/v1/user':
path = '../captures/api/v1/user.xml'
elif url.path == '/v1/checkcity':
path = '../captures/api/v1/checkcity.xml'
elif url.path == '/v1/checkins':
path = '../captures/api/v1/checkins.xml'
elif url.path == '/v1/cities':
path = '../captures/api/v1/cities.xml'
elif url.path == '/v1/switchcity':
path = '../captures/api/v1/switchcity.xml'
elif url.path == '/v1/tips':
path = '../captures/api/v1/tips.xml'
elif url.path == '/v1/checkin':
path = '../captures/api/v1/checkin.xml'
elif url.path == '/history/12345.rss':
path = '../captures/api/v1/feed.xml'
if path is None:
self.send_error(404)
else:
logging.warn('Using: %s' % path)
return open(path)
def send_200(self):
self.send_response(200)
self.send_header('Content-type', 'text/xml')
self.end_headers()
def main():
if len(sys.argv) > 1:
port = int(sys.argv[1])
else:
port = 8080
server_address = ('0.0.0.0', port)
httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/python
import datetime
import sys
import textwrap
import common
from xml.dom import pulldom
PARSER = """\
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.parsers;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.types.%(type_name)s;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Auto-generated: %(timestamp)s
*
* @author Joe LaPenna (joe@joelapenna.com)
* @param <T>
*/
public class %(type_name)sParser extends AbstractParser<%(type_name)s> {
private static final Logger LOG = Logger.getLogger(%(type_name)sParser.class.getCanonicalName());
private static final boolean DEBUG = Foursquare.PARSER_DEBUG;
@Override
public %(type_name)s parseInner(XmlPullParser parser) throws XmlPullParserException, IOException,
FoursquareError, FoursquareParseException {
parser.require(XmlPullParser.START_TAG, null, null);
%(type_name)s %(top_node_name)s = new %(type_name)s();
while (parser.nextTag() == XmlPullParser.START_TAG) {
String name = parser.getName();
%(stanzas)s
} else {
// Consume something we don't understand.
if (DEBUG) LOG.log(Level.FINE, "Found tag that we don't recognize: " + name);
skipSubTree(parser);
}
}
return %(top_node_name)s;
}
}"""
BOOLEAN_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(Boolean.valueOf(parser.nextText()));
"""
GROUP_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new GroupParser(new %(sub_parser_camel_case)s()).parse(parser));
"""
COMPLEX_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new %(parser_name)s().parse(parser));
"""
STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(parser.nextText());
"""
def main():
type_name, top_node_name, attributes = common.WalkNodesForAttributes(
sys.argv[1])
GenerateClass(type_name, top_node_name, attributes)
def GenerateClass(type_name, top_node_name, attributes):
"""generate it.
type_name: the type of object the parser returns
top_node_name: the name of the object the parser returns.
per common.WalkNodsForAttributes
"""
stanzas = []
for name in sorted(attributes):
typ, children = attributes[name]
replacements = Replacements(top_node_name, name, typ, children)
if typ == common.BOOLEAN:
stanzas.append(BOOLEAN_STANZA % replacements)
elif typ == common.GROUP:
stanzas.append(GROUP_STANZA % replacements)
elif typ in common.COMPLEX:
stanzas.append(COMPLEX_STANZA % replacements)
else:
stanzas.append(STANZA % replacements)
if stanzas:
# pop off the extranious } else for the first conditional stanza.
stanzas[0] = stanzas[0].replace('} else ', '', 1)
replacements = Replacements(top_node_name, name, typ, [None])
replacements['stanzas'] = '\n'.join(stanzas).strip()
print PARSER % replacements
def Replacements(top_node_name, name, typ, children):
# CameCaseClassName
type_name = ''.join([word.capitalize() for word in top_node_name.split('_')])
# CamelCaseClassName
camel_name = ''.join([word.capitalize() for word in name.split('_')])
# camelCaseLocalName
attribute_name = camel_name.lower().capitalize()
# mFieldName
field_name = 'm' + camel_name
if children[0]:
sub_parser_camel_case = children[0] + 'Parser'
else:
sub_parser_camel_case = (camel_name[:-1] + 'Parser')
return {
'type_name': type_name,
'name': name,
'top_node_name': top_node_name,
'camel_name': camel_name,
'parser_name': typ + 'Parser',
'attribute_name': attribute_name,
'field_name': field_name,
'typ': typ,
'timestamp': datetime.datetime.now(),
'sub_parser_camel_case': sub_parser_camel_case,
'sub_type': children[0]
}
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/python
"""
Pull a oAuth protected page from foursquare.
Expects ~/.oget to contain (one on each line):
CONSUMER_KEY
CONSUMER_KEY_SECRET
USERNAME
PASSWORD
Don't forget to chmod 600 the file!
"""
import httplib
import os
import re
import sys
import urllib
import urllib2
import urlparse
import user
from xml.dom import pulldom
from xml.dom import minidom
import oauth
"""From: http://groups.google.com/group/foursquare-api/web/oauth
@consumer = OAuth::Consumer.new("consumer_token","consumer_secret", {
:site => "http://foursquare.com",
:scheme => :header,
:http_method => :post,
:request_token_path => "/oauth/request_token",
:access_token_path => "/oauth/access_token",
:authorize_path => "/oauth/authorize"
})
"""
SERVER = 'api.foursquare.com:80'
CONTENT_TYPE_HEADER = {'Content-Type' :'application/x-www-form-urlencoded'}
SIGNATURE_METHOD = oauth.OAuthSignatureMethod_HMAC_SHA1()
AUTHEXCHANGE_URL = 'http://api.foursquare.com/v1/authexchange'
def parse_auth_response(auth_response):
return (
re.search('<oauth_token>(.*)</oauth_token>', auth_response).groups()[0],
re.search('<oauth_token_secret>(.*)</oauth_token_secret>',
auth_response).groups()[0]
)
def create_signed_oauth_request(username, password, consumer):
oauth_request = oauth.OAuthRequest.from_consumer_and_token(
consumer, http_method='POST', http_url=AUTHEXCHANGE_URL,
parameters=dict(fs_username=username, fs_password=password))
oauth_request.sign_request(SIGNATURE_METHOD, consumer, None)
return oauth_request
def main():
url = urlparse.urlparse(sys.argv[1])
# Nevermind that the query can have repeated keys.
parameters = dict(urlparse.parse_qsl(url.query))
password_file = open(os.path.join(user.home, '.oget'))
lines = [line.strip() for line in password_file.readlines()]
if len(lines) == 4:
cons_key, cons_key_secret, username, password = lines
access_token = None
else:
cons_key, cons_key_secret, username, password, token, secret = lines
access_token = oauth.OAuthToken(token, secret)
consumer = oauth.OAuthConsumer(cons_key, cons_key_secret)
if not access_token:
oauth_request = create_signed_oauth_request(username, password, consumer)
connection = httplib.HTTPConnection(SERVER)
headers = {'Content-Type' :'application/x-www-form-urlencoded'}
connection.request(oauth_request.http_method, AUTHEXCHANGE_URL,
body=oauth_request.to_postdata(), headers=headers)
auth_response = connection.getresponse().read()
token = parse_auth_response(auth_response)
access_token = oauth.OAuthToken(*token)
open(os.path.join(user.home, '.oget'), 'w').write('\n'.join((
cons_key, cons_key_secret, username, password, token[0], token[1])))
oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer,
access_token, http_method='POST', http_url=url.geturl(),
parameters=parameters)
oauth_request.sign_request(SIGNATURE_METHOD, consumer, access_token)
connection = httplib.HTTPConnection(SERVER)
connection.request(oauth_request.http_method, oauth_request.to_url(),
body=oauth_request.to_postdata(), headers=CONTENT_TYPE_HEADER)
print connection.getresponse().read()
#print minidom.parse(connection.getresponse()).toprettyxml(indent=' ')
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/python
import os
import subprocess
import sys
BASEDIR = '../main/src/com/joelapenna/foursquare'
TYPESDIR = '../captures/types/v1'
captures = sys.argv[1:]
if not captures:
captures = os.listdir(TYPESDIR)
for f in captures:
basename = f.split('.')[0]
javaname = ''.join([c.capitalize() for c in basename.split('_')])
fullpath = os.path.join(TYPESDIR, f)
typepath = os.path.join(BASEDIR, 'types', javaname + '.java')
parserpath = os.path.join(BASEDIR, 'parsers', javaname + 'Parser.java')
cmd = 'python gen_class.py %s > %s' % (fullpath, typepath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
cmd = 'python gen_parser.py %s > %s' % (fullpath, parserpath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
| Python |
#!/usr/bin/python
import logging
from xml.dom import minidom
from xml.dom import pulldom
BOOLEAN = "boolean"
STRING = "String"
GROUP = "Group"
# Interfaces that all FoursquareTypes implement.
DEFAULT_INTERFACES = ['FoursquareType']
# Interfaces that specific FoursqureTypes implement.
INTERFACES = {
}
DEFAULT_CLASS_IMPORTS = [
]
CLASS_IMPORTS = {
# 'Checkin': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Venue': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Tip': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
}
COMPLEX = [
'Group',
'Badge',
'Beenhere',
'Checkin',
'CheckinResponse',
'City',
'Credentials',
'Data',
'Mayor',
'Rank',
'Score',
'Scoring',
'Settings',
'Stats',
'Tags',
'Tip',
'User',
'Venue',
]
TYPES = COMPLEX + ['boolean']
def WalkNodesForAttributes(path):
"""Parse the xml file getting all attributes.
<venue>
<attribute>value</attribute>
</venue>
Returns:
type_name - The java-style name the top node will have. "Venue"
top_node_name - unadultured name of the xml stanza, probably the type of
java class we're creating. "venue"
attributes - {'attribute': 'value'}
"""
doc = pulldom.parse(path)
type_name = None
top_node_name = None
attributes = {}
level = 0
for event, node in doc:
# For skipping parts of a tree.
if level > 0:
if event == pulldom.END_ELEMENT:
level-=1
logging.warn('(%s) Skip end: %s' % (str(level), node))
continue
elif event == pulldom.START_ELEMENT:
logging.warn('(%s) Skipping: %s' % (str(level), node))
level+=1
continue
if event == pulldom.START_ELEMENT:
logging.warn('Parsing: ' + node.tagName)
# Get the type name to use.
if type_name is None:
type_name = ''.join([word.capitalize()
for word in node.tagName.split('_')])
top_node_name = node.tagName
logging.warn('Found Top Node Name: ' + top_node_name)
continue
typ = node.getAttribute('type')
child = node.getAttribute('child')
# We don't want to walk complex types.
if typ in COMPLEX:
logging.warn('Found Complex: ' + node.tagName)
level = 1
elif typ not in TYPES:
logging.warn('Found String: ' + typ)
typ = STRING
else:
logging.warn('Found Type: ' + typ)
logging.warn('Adding: ' + str((node, typ)))
attributes.setdefault(node.tagName, (typ, [child]))
logging.warn('Attr: ' + str((type_name, top_node_name, attributes)))
return type_name, top_node_name, attributes
| Python |
#!/usr/bin/python
#------------------------------------------------------------------------------
# $Id: formatedstring.py 3 2008-10-17 09:35:32Z 2derand $
#
# creator 2derand
#------------------------------------------------------------------------------
def convertFormatedLine(line,format,formatDeffs):
def cflGet(line,j,out,dump):
rv = ''
while line[j]<>out:
rv += line[j]
j+=1
if j==len(line):
return (rv,j)
if out==' ':
if line[j]=='\t' or line[j]==' ':
out=line[j]
if len(rv)>=dump[1] and dump[1]<>0 and line[j]<>out:
print 'asd'
return (rv,j)
j+=1
while line[j]==out:
j+=1
if j>=len(line): break
return (rv,j)
def cflGetName(dict,name):
i=0
rv='%s%d'%(name,i)
while dict.has_key(rv):
i+=1
rv='%s%d'%(name,i)
return rv
def cflMagic(dict):
i=0
while dict.has_key('year%d'%i):
if dict.has_key('month%d'%i) and dict.has_key('day%d'%i):
dt = '%s-%s-%s'%(dict['year%d'%i],dict['month%d'%i],dict['day%d'%i])
del dict['year%d'%i],dict['month%d'%i],dict['day%d'%i]
if dict.has_key('hour%d'%i):
dt += ' %s:'%dict['hour%d'%i]
del dict['hour%d'%i]
if dict.has_key('min%d'%i):
dt += '%s:'%dict['min%d'%i]
del dict['min%d'%i]
if dict.has_key('sec%d'%i):
dt += '%s'%dict['sec%d'%i]
del dict['sec%d'%i]
else:
dt += '00'
else:
dt += '00:'
if dict.has_key('sec%d'%i):
dt += '%s'%dict['sec%d'%i]
del dict['sec%d'%i]
else:
dt += '00'
dict[cflGetName(dict,'date')] = dt
i+=1
return dict
i=0
j=0
rv = {}
while i<len(format)-1:
if formatDeffs.has_key(format[i]):
(val,j) = cflGet(line,j,format[i+1],formatDeffs[format[i]])
rv[cflGetName(rv,formatDeffs[format[i]][0])] = val
i+=1
if formatDeffs.has_key(format[i]):
(val,j) = cflGet(line,j,'',formatDeffs[format[i]])
rv[cflGetName(rv,formatDeffs[format[i]][0])] = val
return cflMagic(rv)
if (__name__=='__main__'):
GC_FORMAT_FORMAT = {
'order':('Y','M','D','h','m','s','p','o','c','d','l','r','u','t'),
'Y':('year',4,'year',),
'M':('month',2,'month'),
'D':('day',2,'day'),
'h':('hour',2,'hour'),
'm':('min',2,'min'),
's':('sec',2,'sec'),
'p':('profit',0,'profit'),
'o':('open',0,'open price(points)'),
'c':('close',0,'close price(points)'),
'd':('dir',1,'direction'),
'l':('lots',2,'lots'),
'r':('drawdown',0,'drawdown'),
'u':('runup',0,'run-up'),
't':('activetime',0,'position time'),
}
line = '15.09.2008 09:38 l 5 1.4323 15.09.2008 11:10 1.4276'
format = 'D.M.Y h:m d l o D.M.Y h:m c'
print '\033[1;37mline:\033[0m\t%s'%line
print '\033[1;37mformat:\033[0m\t%s'%format
print '\033[1;37mresult:\033[0m',convertFormatedLine(line,format,GC_FORMAT_FORMAT)
| Python |
#!/usr/bin/python
#------------------------------------------------------------------------------
# $Id$
#
# creator 2derand
#------------------------------------------------------------------------------
def convertFormatedLine(line,format,formatDeffs):
def cflGet(line,j,out,dump):
rv = ''
while line[j]<>out:
rv += line[j]
j+=1
if j==len(line):
return (rv,j)
if out==' ':
if line[j]=='\t' or line[j]==' ':
out=line[j]
if len(rv)>=dump[1] and dump[1]<>0 and line[j]<>out:
print 'asd'
return (rv,j)
j+=1
while line[j]==out:
j+=1
if j>=len(line): break
return (rv,j)
def cflGetName(dict,name):
i=0
rv='%s%d'%(name,i)
while dict.has_key(rv):
i+=1
rv='%s%d'%(name,i)
return rv
def cflMagic(dict):
i=0
while dict.has_key('year%d'%i):
if dict.has_key('month%d'%i) and dict.has_key('day%d'%i):
dt = '%s-%s-%s'%(dict['year%d'%i],dict['month%d'%i],dict['day%d'%i])
del dict['year%d'%i],dict['month%d'%i],dict['day%d'%i]
if dict.has_key('hour%d'%i):
dt += ' %s:'%dict['hour%d'%i]
del dict['hour%d'%i]
if dict.has_key('min%d'%i):
dt += '%s:'%dict['min%d'%i]
del dict['min%d'%i]
if dict.has_key('sec%d'%i):
dt += '%s'%dict['sec%d'%i]
del dict['sec%d'%i]
else:
dt += '00'
else:
dt += '00:'
if dict.has_key('sec%d'%i):
dt += '%s'%dict['sec%d'%i]
del dict['sec%d'%i]
else:
dt += '00'
dict[cflGetName(dict,'date')] = dt
i+=1
return dict
i=0
j=0
rv = {}
while i<len(format)-1:
if formatDeffs.has_key(format[i]):
(val,j) = cflGet(line,j,format[i+1],formatDeffs[format[i]])
rv[cflGetName(rv,formatDeffs[format[i]][0])] = val
i+=1
if formatDeffs.has_key(format[i]):
(val,j) = cflGet(line,j,'',formatDeffs[format[i]])
rv[cflGetName(rv,formatDeffs[format[i]][0])] = val
return cflMagic(rv)
if (__name__=='__main__'):
GC_FORMAT_FORMAT = {
'order':('Y','M','D','h','m','s','p','o','c','d','l','r','u','t'),
'Y':('year',4,'year',),
'M':('month',2,'month'),
'D':('day',2,'day'),
'h':('hour',2,'hour'),
'm':('min',2,'min'),
's':('sec',2,'sec'),
'p':('profit',0,'profit'),
'o':('open',0,'open price(points)'),
'c':('close',0,'close price(points)'),
'd':('dir',1,'direction'),
'l':('lots',2,'lots'),
'r':('drawdown',0,'drawdown'),
'u':('runup',0,'run-up'),
't':('activetime',0,'position time'),
}
line = '15.09.2008 09:38 l 5 1.4323 15.09.2008 11:10 1.4276'
format = 'D.M.Y h:m d l o D.M.Y h:m c'
print '\033[1;37mline:\033[0m\t%s'%line
print '\033[1;37mformat:\033[0m\t%s'%format
print '\033[1;37mresult:\033[0m',convertFormatedLine(line,format,GC_FORMAT_FORMAT)
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.