-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy patheyefiserver.py
executable file
·1103 lines (882 loc) · 39.6 KB
/
eyefiserver.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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
* Copyright (c) 2009, Jeffrey Tchang
* Additional *pike
* -- additional logging and email notification (JP)
* All rights reserved.
*
*
* THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY
* EXPRESS 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 COPYRIGHT HOLDER 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.
"""
import cgi
import time
from datetime import timedelta
import random
import sys
import os
import socket
import thread
import StringIO
import traceback
import errno
import tempfile
import hashlib
import binascii
import select
import tarfile
import xml.sax
from xml.sax.handler import ContentHandler
import xml.dom.minidom
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import BaseHTTPServer
import httplib
import SocketServer
import logging
import logging.handlers
import atexit
from signal import SIGTERM
import signal
#pike
from datetime import datetime
import ConfigParser
DEFAULTS = {'upload_uid': '-1', 'upload_gid': '-1', 'geotag_enable': '0'}
import math
import subprocess
class Daemon:
"""
A generic daemon class.
Usage: subclass the Daemon class and override the run() method
"""
def __init__(self,
pidfile,
stdin='/dev/null',
stdout='/dev/null',
stderr='/dev/null',
):
try:
self.stderr = sys.argv[3]
except:
self.stderr = stderr
self.stdin = stdin
self.stdout = stdout
self.pidfile = pidfile
def daemonize(self):
"""
do the UNIX double-fork magic, see Stevens' "Advanced
Programming in the UNIX Environment" for details (ISBN 0201563177)
http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
"""
try:
pid = os.fork()
if pid > 0:
# exit first parent
# sys.exit(0)
return 0
except OSError, e:
sys.stderr.write("fork #1 failed: %d (%s)\n" \
% (e.errno, e.strerror))
sys.exit(1)
# decouple from parent environment
os.chdir("/")
os.setsid()
os.umask(0)
# do second fork
try:
pid = os.fork()
if pid > 0:
# exit from second parent
# sys.exit(0)
return 1
except OSError, e:
sys.stderr.write("fork #2 failed: %d (%s)\n" \
% (e.errno, e.strerror))
sys.exit(1)
# redirect standard file descriptors
sys.stdout.flush()
sys.stderr.flush()
si = file(self.stdin, 'r')
so = file(self.stdout, 'a+')
se = file(self.stderr, 'a+', 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
# write pidfile
atexit.register(self.delpid)
pid = str(os.getpid())
file(self.pidfile,'w+').write("%s\n" % pid)
def delpid(self):
os.remove(self.pidfile)
def start(self):
"""
Start the daemon
"""
# Check for a pidfile to see if the daemon already runs
try:
pf = file(self.pidfile,'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if pid:
message = "pidfile %s already exist. Daemon already running?\n"
sys.stderr.write(message % self.pidfile)
return 1
# Start the daemon
forkresult = self.daemonize()
if forkresult==None:
self.run()
return forkresult
def stop(self):
"""
Stop the daemon
"""
# Get the pid from the pidfile
try:
pf = file(self.pidfile,'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if not pid:
message = "pidfile %s does not exist. Daemon not running?\n"
sys.stderr.write(message % self.pidfile)
return 1
# Try killing the daemon process
try:
while 1:
os.kill(pid, SIGTERM)
time.sleep(0.1)
except OSError, err:
err = str(err)
if err.find("No such process") > 0:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
else:
print str(err)
sys.exit(1)
def restart(self):
"""
Restart the daemon
"""
# Get the pid from the pidfile
try:
pf = file(self.pidfile,'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if pid:
# Try killing the daemon process
try:
while 1:
os.kill(pid, SIGTERM)
time.sleep(0.1)
except OSError, err:
err = str(err)
if err.find("No such process") > 0:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
else:
print str(err)
return 1
# Start the daemon
forkresult = self.daemonize()
if forkresult==None:
self.run()
return forkresult
def reload(self):
"""
Reload configuration
"""
# Get the pid from the pidfile
try:
pf = file(self.pidfile,'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if not pid:
message = "pidfile %s does not exist. Daemon not running?\n"
sys.stderr.write(message % self.pidfile)
return 1
# Try killing the daemon process
try:
os.kill(pid, signal.SIGUSR1)
except OSError, err:
print str(err)
def status(self):
"""
Check daemon status
"""
# Get the pid from the pidfile
try:
pf = file(self.pidfile,'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if not pid:
message = "pidfile %s does not exist. Daemon not running?\n"
sys.stderr.write(message % self.pidfile)
return 1
def run(self):
"""
You should override this method when you subclass Daemon. It will be called after the process has been
daemonized by start() or restart().
"""
"""
General architecture notes
This is a standalone Eye-Fi Server that is designed to take the place of the Eye-Fi Manager.
Starting this server creates a listener on port 59278. I use the BaseHTTPServer class included
with Python. I look for specific POST/GET request URLs and execute functions based on those
URLs.
"""
# Create the main logger
eyeFiLogger = logging.Logger("eyeFiLogger",logging.DEBUG)
# Create two handlers. One to print to the log and one to print to the console
consoleHandler = logging.StreamHandler(sys.stdout)
# Set how both handlers will print the pretty log events
eyeFiLoggingFormat = logging.Formatter("[%(asctime)s][%(funcName)s] - %(message)s",'%m/%d/%y %I:%M%p')
consoleHandler.setFormatter(eyeFiLoggingFormat)
# Append both handlers to the main Eye Fi Server logger
eyeFiLogger.addHandler(consoleHandler)
def fix_ownership(path, uid, gid):
if uid != -1 and gid != -1:
os.chown(path, uid, gid)
# Eye Fi XML SAX ContentHandler
class EyeFiContentHandler(ContentHandler):
# These are the element names that I want to parse out of the XML
elementNamesToExtract = ["macaddress","cnonce","transfermode","transfermodetimestamp","fileid","filename","filesize","filesignature"]
# For each of the element names I create a dictionary with the value to False
elementsToExtract = {}
# Where to put the extracted values
extractedElements = {}
def __init__(self):
self.extractedElements = {}
for elementName in self.elementNamesToExtract:
self.elementsToExtract[elementName] = False
def startElement(self, name, attributes):
# If the name of the element is a key in the dictionary elementsToExtract
# set the value to True
if name in self.elementsToExtract:
self.elementsToExtract[name] = True
def endElement(self, name):
# If the name of the element is a key in the dictionary elementsToExtract
# set the value to False
if name in self.elementsToExtract:
self.elementsToExtract[name] = False
def characters(self, content):
for elementName in self.elementsToExtract:
if self.elementsToExtract[elementName] == True:
self.extractedElements[elementName] = content
# Implements an EyeFi server
class EyeFiServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
# ---------------
# (JP) track session details (# files, size)
global_counter = 0
session_counter = 0
session_upload_size = 0
session_files = ""
session_start_time = 0
# ---------------
def serve_forever(self):
while self.run:
try:
self.handle_request()
except select.error, e:
if e[0] != errno.EINTR:
raise e
def reload_config(self, signum, frame):
try:
configfile = sys.argv[2]
eyeFiLogger.info("Reloading configuration " + configfile)
self.config.read(configfile)
except:
eyeFiLogger.error("Error reloading configuration")
def stop_server(self, signum, frame):
try:
eyeFiLogger.info("Eye-Fi server stopped ")
self.stop()
except:
eyeFiLogger.error("Error stopping server")
def server_bind(self):
BaseHTTPServer.HTTPServer.server_bind(self)
self.socket.settimeout(None)
signal.signal(signal.SIGUSR1, self.reload_config)
signal.signal(signal.SIGTERM, self.stop_server)
signal.signal(signal.SIGINT, self.stop_server)
self.run = True
def get_request(self):
while self.run:
try:
connection, address = self.socket.accept()
eyeFiLogger.debug("Incoming connection from client %s" % address[0])
# ---------------
# (JP) set start time if not set
if (self.session_start_time == 0):
self.session_start_time = time.time()
# ---------------
connection.settimeout(None)
return (connection, address)
except socket.timeout:
self.socket.close()
pass
def stop(self):
self.run = False
# alt serve_forever method for python <2.6
# because we want a shutdown mech ..
#def serve(self):
# while self.run:
# self.handle_request()
# self.socket.close()
# This class is responsible for handling HTTP requests passed to it.
# It implements the two most common HTTP methods, do_GET() and do_POST()
class EyeFiRequestHandler(BaseHTTPRequestHandler):
# pike: these seem unused ?
protocol_version = 'HTTP/1.1'
sys_version = ""
server_version = "Eye-Fi Agent/2.0.4.0 (Windows XP SP2)"
def do_QUIT (self):
eyeFiLogger.debug("Got StopServer request .. stopping server")
self.send_response(200)
self.end_headers()
self.server.stop()
def do_GET(self):
try:
#eyeFiLogger.debug(self.command + " " + self.path + " " + self.request_version)
SOAPAction = ""
# eyeFiLogger.debug("Headers received in GET request:")
for headerName in self.headers.keys():
for headerValue in self.headers.getheaders(headerName):
# eyeFiLogger.debug(headerName + ": " + headerValue)
if( headerName == "soapaction"):
SOAPAction = headerValue
self.send_response(200)
self.send_header('Content-type','text/html')
# I should be sending a Content-Length header with HTTP/1.1 but I am being lazy
# self.send_header('Content-length', '123')
self.end_headers()
self.wfile.write(self.client_address)
self.wfile.write(self.headers)
self.close_connection = 0
except:
eyeFiLogger.error("Got an an exception:")
eyeFiLogger.error(traceback.format_exc())
raise
def do_POST(self):
try:
# eyeFiLogger.debug(self.command + " " + self.path + " " + self.request_version)
SOAPAction = ""
contentLength = ""
# Loop through all the request headers and pick out ones that are relevant
# eyeFiLogger.debug("Headers received in POST request:")
for headerName in self.headers.keys():
for headerValue in self.headers.getheaders(headerName):
if( headerName == "soapaction"):
SOAPAction = headerValue
if( headerName == "content-length"):
contentLength = int(headerValue)
# eyeFiLogger.debug(headerName + ": " + headerValue)
# Read contentLength bytes worth of data
# eyeFiLogger.debug("Attempting to read " + str(contentLength) + " bytes of data")
# postData = self.rfile.read(contentLength)
try:
from StringIO import StringIO
import tempfile
except ImportError:
eyeFiLogger.debug("No StringIO module")
chunksize = 1048576 # 1MB
mem = StringIO()
while 1:
remain = contentLength - mem.tell()
if remain <= 0: break
chunk = self.rfile.read(min(chunksize, remain))
if not chunk: break
mem.write(chunk)
print remain
print "Finished"
postData = mem.getvalue()
mem.close()
# eyeFiLogger.debug("Finished reading " + str(contentLength) + " bytes of data")
# Perform action based on path and SOAPAction
# A SOAPAction of StartSession indicates the beginning of an EyeFi authentication request
if((self.path == "/api/soap/eyefilm/v1") and (SOAPAction == "\"urn:StartSession\"")):
eyeFiLogger.debug("Got StartSession request")
response = self.startSession(postData)
contentLength = len(response)
# eyeFiLogger.debug("StartSession response: " + response)
self.send_response(200)
self.send_header('Date', self.date_time_string())
self.send_header('Pragma','no-cache')
self.send_header('Server','Eye-Fi Agent/2.0.4.0 (Windows XP SP2)')
self.send_header('Content-Type','text/xml; charset="utf-8"')
self.send_header('Content-Length', contentLength)
self.end_headers()
self.wfile.write(response)
self.wfile.flush()
self.handle_one_request()
# GetPhotoStatus allows the card to query if a photo has been uploaded
# to the server yet
if((self.path == "/api/soap/eyefilm/v1") and (SOAPAction == "\"urn:GetPhotoStatus\"")):
eyeFiLogger.debug("Got GetPhotoStatus request")
response = self.getPhotoStatus(postData)
contentLength = len(response)
# eyeFiLogger.debug("GetPhotoStatus response: " + response)
self.send_response(200)
self.send_header('Date', self.date_time_string())
self.send_header('Pragma','no-cache')
self.send_header('Server','Eye-Fi Agent/2.0.4.0 (Windows XP SP2)')
self.send_header('Content-Type','text/xml; charset="utf-8"')
self.send_header('Content-Length', contentLength)
self.end_headers()
self.wfile.write(response)
self.wfile.flush()
# If the URL is upload and there is no SOAPAction the card is ready to send a picture to me
if((self.path == "/api/soap/eyefilm/v1/upload") and (SOAPAction == "")):
# eyeFiLogger.debug("Got upload request")
response = self.uploadPhoto(postData)
contentLength = len(response)
# eyeFiLogger.debug("Upload response: " + response)
self.send_response(200)
self.send_header('Date', self.date_time_string())
self.send_header('Pragma','no-cache')
self.send_header('Server','Eye-Fi Agent/2.0.4.0 (Windows XP SP2)')
self.send_header('Content-Type','text/xml; charset="utf-8"')
self.send_header('Content-Length', contentLength)
self.end_headers()
self.wfile.write(response)
self.wfile.flush()
# If the URL is upload and SOAPAction is MarkLastPhotoInRoll
if((self.path == "/api/soap/eyefilm/v1") and (SOAPAction == "\"urn:MarkLastPhotoInRoll\"")):
# eyeFiLogger.debug("Got MarkLastPhotoInRoll request")
response = self.markLastPhotoInRoll(postData)
contentLength = len(response)
# eyeFiLogger.debug("MarkLastPhotoInRoll response: " + response)
self.send_response(200)
self.send_header('Date', self.date_time_string())
self.send_header('Pragma','no-cache')
self.send_header('Server','Eye-Fi Agent/2.0.4.0 (Windows XP SP2)')
self.send_header('Content-Type','text/xml; charset="utf-8"')
self.send_header('Content-Length', contentLength)
self.send_header('Connection', 'Close')
self.end_headers()
self.wfile.write(response)
self.wfile.flush()
# ---------------
# format upload size
uploaded_str = human_size(self.server.session_upload_size)
# elapsed time (secs)
elapsed_time = time.time() - self.server.session_start_time
# formated into HH:MM:SS
elapsed_str = str(timedelta(seconds=elapsed_time))
eyeFiLogger.debug("upload complete: duration: " + elapsed_str + ", uploaded: " + str(self.server.session_counter) + ", size: " + uploaded_str + ", total(history): " + str(self.server.global_counter))
# (JP) send notification on upload complete
subprocess.call(['/usr/local/bin/eyefi-notify.sh', str(self.server.session_counter), uploaded_str, self.server.session_files])
# reset session counters
self.server.session_files = ""
self.server.session_counter = 0
self.server.session_upload_size = 0
self.server.session_start_time = 0;
# ---------------
except:
eyeFiLogger.error("Got an an exception:")
eyeFiLogger.error(traceback.format_exc())
raise
# Handles MarkLastPhotoInRoll action
def markLastPhotoInRoll(self,postData):
# Create the XML document to send back
doc = xml.dom.minidom.Document()
SOAPElement = doc.createElementNS("http://schemas.xmlsoap.org/soap/envelope/","SOAP-ENV:Envelope")
SOAPElement.setAttribute("xmlns:SOAP-ENV","http://schemas.xmlsoap.org/soap/envelope/")
SOAPBodyElement = doc.createElement("SOAP-ENV:Body")
markLastPhotoInRollResponseElement = doc.createElement("MarkLastPhotoInRollResponse")
SOAPBodyElement.appendChild(markLastPhotoInRollResponseElement)
SOAPElement.appendChild(SOAPBodyElement)
doc.appendChild(SOAPElement)
return doc.toxml(encoding="UTF-8")
# Handles receiving the actual photograph from the card.
# postData will most likely contain multipart binary post data that needs to be parsed
def uploadPhoto(self,postData):
# Take the postData string and work with it as if it were a file object
postDataInMemoryFile = StringIO.StringIO(postData)
# Get the content-type header which looks something like this
# content-type: multipart/form-data; boundary=---------------------------02468ace13579bdfcafebabef00d
contentTypeHeader = self.headers.getheaders('content-type').pop()
# eyeFiLogger.debug(contentTypeHeader)
# Extract the boundary parameter in the content-type header
headerParameters = contentTypeHeader.split(";")
# eyeFiLogger.debug(headerParameters)
boundary = headerParameters[-1].split("=")
boundary = boundary[1].strip()
# eyeFiLogger.debug("Extracted boundary: " + boundary)
# eyeFiLogger.debug("uploadPhoto postData: " + postData)
# Parse the multipart/form-data
form = cgi.parse_multipart(postDataInMemoryFile, {"boundary":boundary,"content-disposition":self.headers.getheaders('content-disposition')})
# eyeFiLogger.debug("Available multipart/form-data: " + str(form.keys()))
# Parse the SOAPENVELOPE using the EyeFiContentHandler()
soapEnvelope = form['SOAPENVELOPE'][0]
# eyeFiLogger.debug("SOAPENVELOPE: " + soapEnvelope)
handler = EyeFiContentHandler()
parser = xml.sax.parseString(soapEnvelope,handler)
# eyeFiLogger.debug("Extracted elements: " + str(handler.extractedElements))
imageTarfileName = handler.extractedElements["filename"]
#pike
uid = self.server.config.getint('EyeFiServer','upload_uid')
gid = self.server.config.getint('EyeFiServer','upload_gid')
file_mode = self.server.config.get('EyeFiServer','upload_file_mode')
dir_mode = self.server.config.get('EyeFiServer','upload_dir_mode')
# eyeFiLogger.debug("Using uid/gid %d/%d"%(uid,gid))
# eyeFiLogger.debug("Using file_mode " + file_mode)
# eyeFiLogger.debug("Using dir_mode " + dir_mode)
geotag_enable = int(self.server.config.getint('EyeFiServer','geotag_enable'))
if geotag_enable:
geotag_accuracy = int(self.server.config.get('EyeFiServer','geotag_accuracy'))
imageTarPath = os.path.join(tempfile.gettempdir(), imageTarfileName)
# eyeFiLogger.debug("Generated path " + imageTarPath)
fileHandle = open(imageTarPath, 'wb')
# eyeFiLogger.debug("Opened file " + imageTarPath + " for binary writing")
fileHandle.write(form['FILENAME'][0])
# eyeFiLogger.debug("Wrote file " + imageTarPath)
image_size = fileHandle.tell()
fileHandle.close()
# eyeFiLogger.debug("Closed file " + imageTarPath)
# eyeFiLogger.debug("Extracting TAR file " + imageTarPath)
try:
imageTarfile = tarfile.open(imageTarPath)
except ReadError, error:
eyeFiLogger.error("Failed to open %s" % imageTarPath)
raise
for member in imageTarfile.getmembers():
# If timezone is a daylight savings timezone, and we are
# currently in daylight savings time, then use the altzone
if time.daylight != 0 and time.localtime().tm_isdst != 0:
timeoffset = time.altzone
else:
timeoffset = time.timezone
timezone = timeoffset / 60 / 60 * -1
imageDate = datetime.fromtimestamp(member.mtime) - timedelta(hours=timezone)
uploadDir = imageDate.strftime(self.server.config.get('EyeFiServer','upload_dir'))
# eyeFiLogger.debug("Creating folder " + uploadDir)
if not os.path.isdir(uploadDir):
os.makedirs(uploadDir)
fix_ownership(uploadDir, uid, gid)
if file_mode != "":
os.chmod(uploadDir, int(dir_mode))
f=imageTarfile.extract(member, uploadDir)
imagePath = os.path.join(uploadDir, member.name)
# eyeFiLogger.debug("imagePath " + imagePath)
os.utime(imagePath, (member.mtime + timeoffset, member.mtime + timeoffset))
fix_ownership(imagePath, uid, gid)
if file_mode != "":
os.chmod(imagePath, int(file_mode))
if geotag_enable>0 and member.name.lower().endswith(".log"):
eyeFiLogger.debug("Processing LOG file " + imagePath)
try:
imageName = member.name[:-4]
shottime, aps = list(self.parselog(imagePath,imageName))
aps = self.getphotoaps(shottime, aps)
loc = self.getlocation(aps)
if loc['status']=='OK' and float(loc['accuracy'])<=geotag_accuracy:
xmpName=imageName+".xmp"
xmpPath=os.path.join(uploadDir, xmpName)
eyeFiLogger.debug("Writing XMP file " + xmpPath)
self.writexmp(xmpPath,float(loc['location']['lat']),float(loc['location']['lng']))
fix_ownership(xmpPath, uid, gid)
if file_mode != "":
os.chmod(xmpPath, int(file_mode))
except:
eyeFiLogger.error("Error processing LOG file " + imagePath)
# eyeFiLogger.debug("Closing TAR file " + imageTarPath)
imageTarfile.close()
# eyeFiLogger.debug("Deleting TAR file " + imageTarPath)
os.remove(imageTarPath)
# Create the XML document to send back
doc = xml.dom.minidom.Document()
SOAPElement = doc.createElementNS("http://schemas.xmlsoap.org/soap/envelope/","SOAP-ENV:Envelope")
SOAPElement.setAttribute("xmlns:SOAP-ENV","http://schemas.xmlsoap.org/soap/envelope/")
SOAPBodyElement = doc.createElement("SOAP-ENV:Body")
uploadPhotoResponseElement = doc.createElement("UploadPhotoResponse")
successElement = doc.createElement("success")
successElementText = doc.createTextNode("true")
successElement.appendChild(successElementText)
uploadPhotoResponseElement.appendChild(successElement)
SOAPBodyElement.appendChild(uploadPhotoResponseElement)
SOAPElement.appendChild(SOAPBodyElement)
doc.appendChild(SOAPElement)
# (JP) track uploaded files during session
self.server.session_counter += 1;
self.server.global_counter += 1;
self.server.session_upload_size += image_size
self.server.session_files = self.server.session_files + "\n" + imagePath
# format upload size
uploaded_str = human_size(image_size)
eyeFiLogger.debug("Uploaded #" + str(self.server.session_counter) + ": " + imagePath + ", size: " + uploaded_str)
return doc.toxml(encoding="UTF-8")
def parselog(self,logfile,filename):
shottime = 0
aps = {}
for line in open(logfile):
time, timestamp, act = line.strip().split(",", 2)
act = act.split(",")
act, args = act[0], act[1:]
if act in ("AP", "NEWAP"):
aps.setdefault(args[0], []).append({"time": int(time),"pwr": int(args[1])})
elif act == "NEWPHOTO":
if filename==args[0]:
shottime = int(time)
elif act == "POWERON":
if shottime>0:
return shottime, aps
shottime = 0
aps = {}
if shottime>0:
return shottime, aps
def getphotoaps(self, time, aps):
geotag_lag = int(self.server.config.get('EyeFiServer','geotag_lag'))
newaps = []
for mac in aps:
lag = min([(abs(ap["time"] - time), ap["pwr"]) for ap in aps[mac]], key=lambda a: a[0])
if lag[0] <= geotag_lag:
newaps.append({"mac": mac, "pwr": lag[1]})
return newaps
def getlocation(self, aps):
try:
geourl = 'maps.googleapis.com'
headers = {"Host": geourl}
params = "?browser=none&sensor=false"
for ap in aps:
params+='&wifi=mac:'+'-'.join([ap['mac'][2*d:2*d+2] for d in range(6)])+'|ss:'+str(int(math.log10(ap['pwr']/100.0)*10-50))
conn = httplib.HTTPSConnection(geourl)
conn.request("GET", "/maps/api/browserlocation/json"+params, "", headers)
resp = conn.getresponse()
result = resp.read()
conn.close()
except:
eyeFiLogger.debug("Error connecting to geolocation service")
return None
try:
try:
import simplejson as json
except ImportError:
import json
return json.loads(result)
except:
try:
import re
result=result.replace("\n"," ")
loc={}
loc['location']={}
loc['location']['lat']=float(re.sub(r'.*"lat"\s*:\s*([\d.]+)\s*[,}\n]+.*',r'\1',result))
loc['location']['lng']=float(re.sub(r'.*"lng"\s*:\s*([\d.]+)\s*[,}\n]+.*',r'\1',result))
loc['accuracy']=float(re.sub(r'.*"accuracy"\s*:\s*([\d.]+)\s*[,\}\n]+.*',r'\1',result))
loc['status']=re.sub(r'.*"status"\s*:\s*"(.*?)"\s*[,}\n]+.*',r'\1',result)
return loc
except:
eyeFiLogger.debug("Geolocation service response contains no coordinates: " + result)
return None
def writexmp(self,name,latitude,longitude):
if latitude>0:
ref="N"
else:
ref="S"
latitude=str(abs(latitude)).split('.')
latitude[1]=str(float('0.'+latitude[1])*60)
latitude=','.join(latitude)+ref
if longitude>0:
ref="E"
else:
ref="W"
longitude=str(abs(longitude)).split('.')
longitude[1]=str(float('0.'+longitude[1])*60)
longitude=','.join(longitude)+ref
FILE = open(name,"w")
FILE.write("<?xpacket begin='\xef\xbb\xbf' id='W5M0MpCehiHzreSzNTczkc9d'?>\n<x:xmpmeta xmlns:x='adobe:ns:meta/' x:xmptk='EyeFiServer'>\n<rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>\n<rdf:Description rdf:about='' xmlns:exif='http://ns.adobe.com/exif/1.0/'>\n<exif:GPSLatitude>"+latitude+"</exif:GPSLatitude>\n<exif:GPSLongitude>"+longitude+"</exif:GPSLongitude>\n<exif:GPSVersionID>2.2.0.0</exif:GPSVersionID>\n</rdf:Description>\n</rdf:RDF>\n</x:xmpmeta>\n<?xpacket end='w'?>\n")
FILE.close()
def getPhotoStatus(self,postData):
handler = EyeFiContentHandler()
parser = xml.sax.parseString(postData,handler)
# Create the XML document to send back
doc = xml.dom.minidom.Document()
SOAPElement = doc.createElementNS("http://schemas.xmlsoap.org/soap/envelope/","SOAP-ENV:Envelope")
SOAPElement.setAttribute("xmlns:SOAP-ENV","http://schemas.xmlsoap.org/soap/envelope/")
SOAPBodyElement = doc.createElement("SOAP-ENV:Body")
getPhotoStatusResponseElement = doc.createElement("GetPhotoStatusResponse")
getPhotoStatusResponseElement.setAttribute("xmlns","http://localhost/api/soap/eyefilm")
fileidElement = doc.createElement("fileid")
fileidElementText = doc.createTextNode("1")
fileidElement.appendChild(fileidElementText)
offsetElement = doc.createElement("offset")
offsetElementText = doc.createTextNode("0")
offsetElement.appendChild(offsetElementText)
getPhotoStatusResponseElement.appendChild(fileidElement)
getPhotoStatusResponseElement.appendChild(offsetElement)
SOAPBodyElement.appendChild(getPhotoStatusResponseElement)
SOAPElement.appendChild(SOAPBodyElement)
doc.appendChild(SOAPElement)
return doc.toxml(encoding="UTF-8")
def _get_mac_uploadkey_dict(self):
macs = {}
upload_keys = {}
for key, value in self.server.config.items('EyeFiServer'):
if key.find('upload_key_') == 0:
index = int(key[11:])
upload_keys[index] = value
elif key.find('mac_') == 0:
index = int(key[4:])
macs[index] = value
d = {}
for key in macs.keys():
d[macs[key]] = upload_keys[key]
return d
def startSession(self, postData):
# eyeFiLogger.debug("Delegating the XML parsing of startSession postData to EyeFiContentHandler()")
handler = EyeFiContentHandler()
parser = xml.sax.parseString(postData,handler)
# eyeFiLogger.debug("Extracted elements: " + str(handler.extractedElements))
# Retrieve it from C:\Documents and Settings\<User>\Application Data\Eye-Fi\Settings.xml
mac_to_uploadkey_map = self._get_mac_uploadkey_dict()
mac = handler.extractedElements["macaddress"]
upload_key = mac_to_uploadkey_map[mac]
# eyeFiLogger.debug("Got MAC address of " + mac)
# eyeFiLogger.debug("Setting Eye-Fi upload key to " + upload_key)
credentialString = mac + handler.extractedElements["cnonce"] + upload_key
# eyeFiLogger.debug("Concatenated credential string (pre MD5): " + credentialString)
# Return the binary data represented by the hexadecimal string
# resulting in something that looks like "\x00\x18V\x03\x04..."
binaryCredentialString = binascii.unhexlify(credentialString)
# Now MD5 hash the binary string
m = hashlib.md5()
m.update(binaryCredentialString)
# Hex encode the hash to obtain the final credential string
credential = m.hexdigest()
# Create the XML document to send back
doc = xml.dom.minidom.Document()
SOAPElement = doc.createElementNS("http://schemas.xmlsoap.org/soap/envelope/","SOAP-ENV:Envelope")
SOAPElement.setAttribute("xmlns:SOAP-ENV","http://schemas.xmlsoap.org/soap/envelope/")
SOAPBodyElement = doc.createElement("SOAP-ENV:Body")
startSessionResponseElement = doc.createElement("StartSessionResponse")
startSessionResponseElement.setAttribute("xmlns","http://localhost/api/soap/eyefilm")
credentialElement = doc.createElement("credential")
credentialElementText = doc.createTextNode(credential)
credentialElement.appendChild(credentialElementText)
snonceElement = doc.createElement("snonce")
snonceElementText = doc.createTextNode("%x" % random.getrandbits(128))
snonceElement.appendChild(snonceElementText)
transfermodeElement = doc.createElement("transfermode")
transfermodeElementText = doc.createTextNode(handler.extractedElements["transfermode"])
transfermodeElement.appendChild(transfermodeElementText)
transfermodetimestampElement = doc.createElement("transfermodetimestamp")
transfermodetimestampElementText = doc.createTextNode(handler.extractedElements["transfermodetimestamp"])
transfermodetimestampElement.appendChild(transfermodetimestampElementText)
upsyncallowedElement = doc.createElement("upsyncallowed")
upsyncallowedElementText = doc.createTextNode("true")
upsyncallowedElement.appendChild(upsyncallowedElementText)
startSessionResponseElement.appendChild(credentialElement)
startSessionResponseElement.appendChild(snonceElement)
startSessionResponseElement.appendChild(transfermodeElement)
startSessionResponseElement.appendChild(transfermodetimestampElement)
startSessionResponseElement.appendChild(upsyncallowedElement)
SOAPBodyElement.appendChild(startSessionResponseElement)
SOAPElement.appendChild(SOAPBodyElement)
doc.appendChild(SOAPElement)
return doc.toxml(encoding="UTF-8")
def stopEyeFi():
configfile = sys.argv[2]
eyeFiLogger.info("Reading config " + configfile)
config = ConfigParser.SafeConfigParser(defaults=DEFAULTS)
config.read(configfile)