Source

orange / install-scripts / orngServer / orngServerFilesServer.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
import sys
sys.path.insert(0,"../CherryPy-3.1.0")

import cherrypy
print "Loaded CherryPy version", cherrypy.__version__

import os
import shutil
import re
import hashlib
import threading
import cgi
pj = os.path.join
import datetime

basedir = pj(os.getcwd(), "..", "orngServerData")

userfilename = '../orngServerFilesUsers.txt'

def readUserFile():
    s = open(userfilename, 'rt').read()
    umap = {}
    for line in s.splitlines():
        try:
            uname, passw = line.split(',')
            umap[uname] = passw
        except:
            pass
    print "USERS", umap.keys()
    return umap

def noBodyProcess():
    """Sets cherrypy.request.process_request_body = False, giving
    us direct control of the file upload destination. By default
    cherrypy loads it to memory, we are directing it to disk."""
    #cherrypy.request.process_request_body = False
    print "noBodyProcess"
    print "LOGIN", cherrypy.request.login
    print "PROCESS RB", cherrypy.request.process_request_body
    if not cherrypy.request.login:
        cherrypy.request.process_request_body = False
    
cherrypy.tools.noBodyProcess = cherrypy.Tool('on_start_resource', noBodyProcess, priority=20)

class FileInfo(object):

    separ = '|||||'

    def __init__(self, fname):
        self.fname = fname
        self.set()

    def set(self, name=None, protection=None, datetime=None, title=None, tags=[]):
        self.name = name
        self.protection = protection
        self.datetime = datetime
        self.title = title
        self.tags = tags
    
    def load(self):
        f = open(self.fname, 'rb')
        cont = f.read()
        f.close()
        #print "CONT", cont
        name, protection, datetime, title, tags = cont.splitlines()
        tags = tags.split(";")
        self.set(name, protection, datetime, title, tags)

    def userInfo(self):
        return self.separ.join([\
            str(os.stat(self.fname + ".file").st_size), \
            str(self.datetime), \
            self.title, \
            ";".join(self.tags) \
            ])

    def save(self, fname=None):
        if not fname:
            fname = self.fname
        f = open(fname, 'wb')
        cont = '\n'.join([self.name, self.protection, str(self.datetime), \
            self.title, ";".join(self.tags)])
        #print "WRITING", cont
        f.write(cont)
        f.close()

    def exists(self):
        """
        If file info already exists as a file.
        """
        return self.protection != None


"""
Only one client can edit data for now!
FIXME: allow multiple clients changing different files.
Try locking a specific basename!
"""
sem = threading.BoundedSemaphore()

def lock(**kwargs):
    #print "locking"
    sem.acquire()

def unlock(**kwargs):
    sem.release()
    #print "unlocking"

cherrypy.tools.lock = cherrypy.Tool('on_start_resource', lock, priority=2)
cherrypy.tools.unlock = cherrypy.Tool('on_end_request', unlock)
"""
End of simple locking tools
"""

rec = re.compile("[^A-Za-z0-9\-\.\_]")
def safeFilename(s):
    return rec.sub("", s)

def hash(s):
    """
    May hashing function.
    """
    return hashlib.sha256(s).hexdigest()

def baseDomain(domain):
    domain = safeFilename(domain) #force safe domain
    return pj(basedir, domain)

def baseFilename(domain, filename):
    """
    Return base filename for saving on disk: composed of only
    lowercase characters. First part are first 100 alphanumeric
    characters from the filename, next its hash.
    """
    return pj(baseDomain(domain), \
        safeFilename(filename.lower())[:100] + "." + hash(filename))

def fileInfo(domain, filename):
    """
    Each file is saved in two files: its index and its data.
    It is possible that multiple files get the same name. Therefore
    enumerate them. If filename is the same also in index, then this
    is the same file.
    Returns file's FileInfo. If file does not exists, then its fileinfo
    has only attribute fname.
    """
    basename = baseFilename(domain, filename)
    candidate = 1
    filei = None
    while 1:
        try: 
            fileit = FileInfo(basename + "." + str(candidate))
            fileit.load()
            if fileit.name == filename:
                filei = fileit
                break
        except IOError:
            break # no file - file is free to be taken
        candidate += 1
    if not filei:
        filei = FileInfo(basename + "." + str(candidate))
    return filei

def userFileInfo(domain, filename, protected=False):
    fi = fileInfo(domain, filename)
    if accessAllowed(fi, protected):
        return fi.userInfo()
    else:
        return "None"

def accessAllowed(fi, protected):
    """
    protected == access_code or True (allow everything) or False (public access)

    Allow access if:
    - there is no protection or
    - protected == True -> administrative account
    - fi.protection == protected and it is not "1"
    """
    #return fi.protection == "0" or protected == True or (fi.protection == protected)
    return fi.protection == "0" or protected == True or (fi.protection != "1" and fi.protection == protected)

def downloadFile(domain, filename, protected=False):
    fi = fileInfo(domain, filename)
    if accessAllowed(fi, protected):
        return cherrypy.lib.static.serve_file(fi.fname + ".file", "application/x-download", "attachment", filename)
    else:
        raise cherrypy.HTTPError(500, "File not available!")

def listFilesL(domain, protected=False):
    dir = baseDomain(domain)
    files = [ a for a in os.listdir(dir) if a[-1].isdigit() ]
    okfiles = []
    for file in files:
        fi = FileInfo(pj(dir, file))
        try:
            fi.load() 
            if fi.exists() and accessAllowed(fi, protected):
                okfiles.append(fi.name)
        except:
            pass

    return okfiles

def listFiles(domain, protected=False):
    return "|||||".join(listFilesL(domain, protected=protected))

def listdomainsL():
    dir = basedir
    files = [ a for a in os.listdir(dir) ]
    ok = []
    for file in files:
        if os.path.isdir(os.path.join(dir, file)):
            ok.append(file)
    return ok

def listdomains():
    return "|||||".join(listdomainsL())

def allFileInfosL(domain, protected=False):
    files = listFilesL(domain, protected=protected)
    out = []
    for filename in files:
        info = userFileInfo(domain, filename, protected=protected)
        out.append((filename, info))
    return out

def allFileInfos(domain, protected=False):
    ai = allFileInfosL(domain, protected=protected)
    return [ "[[[[[".join( [ a + "=====" + b for a,b in ai ] ) ]        

class RootServer:
    @cherrypy.expose
    def index(self):
        return """"""

class PublicServer:

    @cherrypy.expose
    def index(self):
        return """"""

    @cherrypy.expose
    def info(self, domain, filename, access_code=None):
        return userFileInfo(domain, filename, protected=access_code)

    @cherrypy.expose
    def allinfo(self, domain, access_code=None):
        return allFileInfos(domain, protected=access_code)

    @cherrypy.expose
    def download(self, domain, filename, access_code=None):
        return downloadFile(domain, filename, protected=access_code)

    @cherrypy.expose
    def list(self, domain, access_code=None):
        return listFiles(domain, protected=access_code)

    @cherrypy.expose
    def listdomains(self):
        return listdomains()

class SecureServer:

    @cherrypy.expose
    def index(self):
        return """"""

    @cherrypy.expose
    def info(self, domain, filename):
        return userFileInfo(domain, filename, protected=True)

    @cherrypy.expose
    def allinfo(self, domain):
        return allFileInfos(domain, protected=True)

    @cherrypy.expose
    def download(self, domain, filename):
        return downloadFile(domain, filename, protected=True)

    @cherrypy.expose
    def list(self, domain):
        return listFiles(domain, protected=True)

    @cherrypy.expose
    def createdomain(self, domain):
        """
        Creates domain. If creation is successful, return 0, else
        return error. 
        """
        dir = baseDomain(domain)
        os.mkdir(dir)
        return "0"

    @cherrypy.expose
    def removedomain(self, domain, force=False):
        """
        Removes domain. If successful return 0, else
        return error.
        """
        dir = baseDomain(domain)
        if not force:
            os.rmdir(dir)
        else:
            shutil.rmtree(dir)
        return '0'

    @cherrypy.expose
    @cherrypy.tools.lock()
    @cherrypy.tools.unlock()
    def remove(self, domain, filename):
        fi = fileInfo(domain, filename)
        if fi.exists(): #valid file
            os.remove(fi.fname)
            os.remove(fi.fname+".file")
            return "0"
        else:
            raise cherrypy.HTTPError(500, "File does not exists.")
            
    @cherrypy.expose
    @cherrypy.tools.lock()
    @cherrypy.tools.unlock()
    def upload(self, domain, filename, title, tags, data):

        fi = fileInfo(domain, filename)
        #print data.file.name

        fupl = open(fi.fname + ".uploading", 'wb')
        shutil.copyfileobj(data.file, fupl, 1024*8) #copy with buffer
        fupl.close()
        #print "transfer successful?" #TODO check this - MD5?

        #TODO is there any difference in those files?

        fupl = open(fi.fname + ".uploading", 'rb')
        ffin = open(fi.fname + ".file", 'wb')
        shutil.copyfileobj(fupl, ffin) #copy with buffer
        ffin.close()
        fupl.close()

        #remove file copy
        os.remove(fi.fname + ".uploading")

        datetime_now = str(datetime.datetime.utcnow())
        fi.datetime = datetime_now
        fi.name = filename
        if fi.protection == None:
            fi.protection = "1"  #only administrative access by default
        fi.title = title
        fi.tags = tags.split(";")

        fi.save()

    @cherrypy.expose
    @cherrypy.tools.lock()
    @cherrypy.tools.unlock()
    def protect(self, domain, filename, access_code="1"):
        fi = fileInfo(domain, filename)
        if fi.exists():
            fi.protection = access_code
            fi.save()
        else:
            raise cherrypy.HTTPError(500, "File does not exists.")

    @cherrypy.expose
    @cherrypy.tools.lock()
    @cherrypy.tools.unlock()
    def unprotect(self, domain, filename):
        #DEPRECATED
        fi = fileInfo(domain, filename)
        if fi.exists():
            fi.protection = "0"
            fi.save()
        else:
            raise cherrypy.HTTPError(500, "File does not exists.")

    @cherrypy.expose
    @cherrypy.tools.lock()
    @cherrypy.tools.unlock()
    def protection(self, domain, filename):
        fi = fileInfo(domain, filename)
        if fi.exists():
            return fi.protection
        else:
            raise cherrypy.HTTPError(500, "File does not exists.")

    @cherrypy.expose
    def listdomains(self):
        return listdomains()


"""
Tools for enforcing security measures.
Also, 
"""

def force_secure(header="Secure"):
    secure = cherrypy.request.headers.get(header, False)
    if not secure:
        raise cherrypy.HTTPError(500, "Use ssl!")

def force_insecure(header="Secure"):
    secure = cherrypy.request.headers.get(header, False)
    if secure:
        raise cherrypy.HTTPError(500, "Do not use ssl!")

cherrypy.tools.secure = cherrypy.Tool('on_start_resource', force_secure, priority=1)
cherrypy.tools.insecure = cherrypy.Tool('on_start_resource', force_insecure, priority=1)

# remove any limit on the request body size; cherrypy's default is 100MB
cherrypy.server.max_request_body_size = 0

def buildServer():
    users = readUserFile()

    conf = {'global': { 'log.screen': False,
                        'log.access_file': 'af.log',
                        'log.error_file': 'ef.log' },
            '/public': { 'tools.insecure.on': True},
            '/private': { 'tools.secure.on': True,
                       'tools.basic_auth.on': True,
                       'tools.basic_auth.realm': 'orngFileServer',
                       'tools.basic_auth.users': users,
                       'tools.basic_auth.encrypt': lambda x: x,
                      }}

    root = RootServer()
    root.public = PublicServer()
    root.private = SecureServer()

    return root, conf

if __name__ == '__main__':
    
    root, conf = buildServer()
    cherrypy.tree.mount(root, '/', conf)
    cherrypy.engine.start()
    cherrypy.engine.block()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.