-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathggposrv.py
executable file
·2771 lines (2392 loc) · 101 KB
/
ggposrv.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/python
# -*- coding: utf-8 -*-
#
# open source ggpo server (re)implementation
#
# (c) 2014-2015 Pau Oliva Fora (@pof)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# ggposrv.py includes portions of code borrowed from hircd.
# hircd is Copyright by Ferry Boender, 2009-2013
#
# 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 sys
import optparse
import logging
import ConfigParser
import os
import SocketServer
import socket
import select
import re
import struct
import time
import datetime
import random
import hmac
import hashlib
import json
import gzip
import traceback
import threading
import tarfile
import boto
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
import urlparse
try:
import requests
except:
pass
try:
# http://dev.maxmind.com/geoip/geoip2/geolite2/
import geoip2.database
reader = geoip2.database.Reader('GeoLite2-City.mmdb')
except:
pass
VERSION=24
MIN_CLIENT_VERSION=42
DB_ENGINE="mysql"
if DB_ENGINE=="sqlite3":
import sqlite3
PARAM="?"
elif DB_ENGINE=="mysql":
import MySQLdb
PARAM="%s"
class GGPOHttpHandler(BaseHTTPRequestHandler):
def print_dump(self):
path = self.path
if '?' in path:
path, tmp = path.split('?', 1)
o = urlparse.urlparse(self.path)
qs = urlparse.parse_qs(o.query)
out={}
if path == "/channels":
for channel in ggposerver.channels.values():
out[channel.name]=[]
for client in channel.clients:
out[channel.name].append(client.nick)
if path == "/clients":
timestamp = time.time()
for client in ggposerver.clients.values():
cli={}
cli["status"]=client.status
cli["channel"]=client.channel.name
cli["quark"]=client.quark
#cli["city"]=client.city
cli["idle"]=int(timestamp-client.lastmsgtime)
cli["country"]=client.country
cli["cc"]=client.cc
cli["version"]=client.version
out[client.nick]=cli
if path == "/games":
for quark in ggposerver.quarks.values():
if quark.p1!=None and quark.p2!=None and quark.p1.nick!=None and quark.p2.nick!=None and quark.channel!=None:
game={}
game["channel"]=quark.channel.name
game["p1"]=quark.p1.nick
game["p2"]=quark.p2.nick
game["spectators"]=len(quark.spectators)
game["useports"]=quark.useports
out[quark.quark]=game
if path == "/stats":
out["version"]='{0:.2f}'.format(VERSION/100.0)
clients = len(ggposerver.clients)
out["clients"]=clients
quarks=0
for quark in ggposerver.quarks.values():
if quark.p1!=None and quark.p2!=None and quark.p1.nick!=None and quark.p2.nick!=None:
quarks=quarks+1
out["games"]=quarks
spectators=0
connections = dict(ggposerver.connections)
for host in connections:
try:
client = ggposerver.connections[host]
if client.clienttype=="spectator":
spectators+=1
except:
pass
out["spectators"]=spectators
out["connections"]=len(ggposerver.connections)+len(ggposerver.clients)
if path == "/mute":
try:
nick=str(qs['nick'][0])
timestamp = time.time()
for client in ggposerver.clients.values():
if client.nick==nick:
cli={}
cli["status"]=client.status
cli["channel"]=client.channel.name
cli["cc"]=client.cc
cli["idle"]=int(timestamp-client.lastmsgtime)
cli["version"]=client.version
out[client.nick]=cli
client.spamhit+=10
except:
pass
if path == "/kill":
try:
nick=str(qs['nick'][0])
timestamp = time.time()
for client in ggposerver.clients.values():
if client.nick==nick:
cli={}
cli["status"]=client.status
cli["channel"]=client.channel.name
cli["cc"]=client.cc
cli["idle"]=int(timestamp-client.lastmsgtime)
cli["version"]=client.version
out[client.nick]=cli
client.handle_part(client.channel.name)
client.request.close()
ggposerver.clients.pop(client.nick)
except:
pass
if path == "/clean":
try:
limit=int(qs['limit'][0])
except:
limit=1000
try:
idle=int(qs['idle'][0])
except:
idle=0
try:
status=int(qs['status'][0])
except:
status=1
try:
clienttype=str(qs['clienttype'][0])
except:
clienttype="client"
num=0
timestamp = time.time()
if clienttype=="client":
for client in ggposerver.clients.values():
if num >= limit:
break
if client.status==status and timestamp-client.lastmsgtime > idle and client.nick!='pof':
cli={}
cli["status"]=client.status
cli["channel"]=client.channel.name
cli["cc"]=client.cc
cli["idle"]=int(timestamp-client.lastmsgtime)
cli["version"]=client.version
out[client.nick]=cli
client.handle_part(client.channel.name)
client.request.close()
ggposerver.clients.pop(client.nick)
num+=1
if clienttype=="spectator":
for host in dict(ggposerver.connections):
if num >= limit:
break
try:
client = ggposerver.connections[host]
if client.clienttype=="spectator":
cli={}
cli["quark"]=client.quark
out[str(host)]=cli
client.request.close()
num+=1
except KeyError:
pass
res = json.dumps(out, indent=4, sort_keys=True);
self.wfile.write(res)
#Handler for the GET requests
def do_GET(self):
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
# Send the message
self.print_dump()
return
class GGPOError(Exception):
"""
Exception thrown by GGPO command handlers to notify client of a server/client error.
"""
def __init__(self, code, value):
self.code = code
self.value = value
def __str__(self):
return repr(self.value)
class GGPOChannel(object):
"""
Object representing an GGPO channel.
"""
def __init__(self, name, rom, topic, motd='', chunksize=1096, port=7000):
self.name = name
self.rom = rom
self.topic = topic
self.motd = motd
self.chunksize = chunksize
self.port = port
self.clients = set()
class GGPOQuark(object):
"""
Object representing a GGPO quark: an ongoing match that can be spectated.
"""
def __init__(self, quark):
self.quark = quark
self.p1 = None
self.p1client = None
self.p2 = None
self.p2client = None
self.spectators = set()
self.recorded = False
self.useports = False
self.channel = None
self.proxyport = {}
# http://stackoverflow.com/q/12248132
def set_keepalive_linux(sock, after_idle_sec=3600, interval_sec=3, max_fails=5):
"""Set TCP keepalive on an open socket.
It activates after 3600 seconds (after_idle_sec) of idleness,
then sends a keepalive ping once every 3 seconds (interval_sec),
and closes the connection after 5 failed ping (max_fails), or 15 seconds
"""
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, after_idle_sec)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, interval_sec)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, max_fails)
def dbconnect():
if DB_ENGINE=="sqlite3":
createdb=False
dbfile = os.path.join(os.path.realpath(os.path.dirname(sys.argv[0])),'db', 'ggposrv.sqlite3')
if not os.path.exists(dbfile):
createdb=True
os.mkdir(os.path.dirname(dbfile))
conn = sqlite3.connect(dbfile)
if createdb==True:
cursor = conn.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
username TEXT COLLATE NOCASE,
password TEXT,
salt TEXT,
email TEXT,
ip TEXT,
date TEXT);""")
cursor.execute("""CREATE UNIQUE INDEX users_username_idx on users (username COLLATE NOCASE);""")
logging.info("created empty user database")
cursor.execute("""CREATE TABLE IF NOT EXISTS quarks (
id INTEGER PRIMARY KEY,
quark TEXT,
player1 TEXT,
player2 TEXT,
channel TEXT,
date TEXT,
realtime_views INTEGER,
saved_views INTEGER,
p1_country CHAR(50),
p2_country CHAR(50),
duration INTEGER);""")
cursor.execute("""CREATE UNIQUE INDEX quarks_quark_idx on quarks (quark);""")
logging.info("created empty quark database")
conn.commit()
return conn
elif DB_ENGINE=="mysql":
conn = MySQLdb.connect(host="localhost", user="ggpo", passwd="ggpo", db="ggposrv")
return conn
class GGPOClient(SocketServer.BaseRequestHandler):
"""
GGPO client connect and command handling. Client connection is handled by
the `handle` method which sets up a two-way communication with the client.
It then handles commands sent by the client by dispatching them to the
handle_ methods.
"""
def __init__(self, request, client_address, server):
self.nick = None # Client's currently registered nickname
self.host = client_address # Client's hostname / ip.
self.status = 0 # Client's status (0=available, 1=away, 2=playing)
self.clienttype = None # can be: player(fba), spectator(fba) or client
self.previous_status = None # Client's previous status (0=available, 1=away, 2=playing)
self.opponent = None # Client's opponent
self.quark = None # Client's quark (in-game uri)
self.fbaport = 0 # Emulator's fbaport
self.side = 0 # Client's side: 1=P1, 2=P2 (0=spectator before savestate, 3=spectator after savestate)
self.port = 6009 # Client's port
self.city = "null" # Client's city
self.country = "null" # Client's country
self.cc = "null" # Client's country code
self.lastmsgtime = 0 # timestamp of the last chat message
self.challengetime = 0 # timestamp of the last challenge
self.lastmsg = '' # last chat message
self.spamhit = 0 # how many times has been warned for spam
self.useports = False # set to true when we have potential problems with NAT traversal
self.version = 0 # client version
self.warnmsg = '' # Warning message (shown after match)
self.turboflag = 0 # turbo flag helper
self.send_queue = [] # Messages to send to client (strings)
self.channel = GGPOChannel("lobby",'', "The Lobby") # Channel the client is in
self.challenging = {} # users (GGPOClient instances) that this client is challenging by host
try:
set_keepalive_linux(request)
except:
pass
SocketServer.BaseRequestHandler.__init__(self, request, client_address, server)
def pad2hex(self,l):
return "".join(reversed(struct.pack('I',l)))
def sizepad(self,value):
if value==None:
return('')
l=len(value)
pdu = self.pad2hex(l)
pdu += value
return pdu
def reply(self,sequence,pdu):
length=4+len(pdu)
return self.pad2hex(length) + self.pad2hex(sequence) + pdu
def send_ack(self, sequence):
ACK='\x00\x00\x00\x00'
response = self.reply(sequence,ACK)
logging.debug('ACK to %s: %r' % (self.client_ident(), response))
self.send_queue.append(response)
def get_client_from_nick(self,nick):
try:
clients = dict(self.server.clients)
for client_nick in clients:
if client_nick == nick:
return self.server.clients[nick]
for client_nick in self.channel.clients:
if client_nick == nick:
return self.channel.clients[nick]
except KeyError:
pass
# if not found, return self
logging.info('[%s] WARNING: Could not find client: %s (returning self)' % (self.client_ident(), nick))
return self
def check_quark_format(self,quark):
a = re.compile("^challenge\-[0-9]{4}\-[0-9]{10,11}[.][0-9]{2}$")
if a.match(quark):
return True
else:
return False
def geolocate(self, ip):
iso_code=''
country=''
city=''
try:
response = reader.city(ip)
if response.country.iso_code!=None:
iso_code=str(response.country.iso_code)
if response.country.name!=None:
country=str(response.country.name)
#if response.city.name!=None:
#city=str(response.city.name)
if (response.subdivisions.most_specific.name=="Barcelona" or
response.subdivisions.most_specific.name=="Tarragona" or
response.subdivisions.most_specific.name=="Lleida" or
response.subdivisions.most_specific.name=="Girona"):
iso_code="Catalonia"
country="Catalonia"
except:
pass
return iso_code,country,city
def parse(self, data):
response = ''
logging.debug('[PARSE] from %s: %r' % (self.client_ident(), data))
length=int(data[0:4].encode('hex'),16)
if (len(data)<length-4): return()
sequence=0
if (length >= 4):
sequence=int(data[4:8].encode('hex'),16)
if (length >= 8):
command=int(data[8:12].encode('hex'),16)
if (command==0):
command = "connect"
params = sequence
if (command==1):
command = "auth"
nicklen=int(data[12:16].encode('hex'),16)
nick=data[16:16+nicklen]
passwordlen=int(data[16+nicklen:16+nicklen+4].encode('hex'),16)
password=data[20+nicklen:20+nicklen+passwordlen]
port=int(data[20+nicklen+passwordlen:24+nicklen+passwordlen].encode('hex'),16)
if len(data) > 24+nicklen+passwordlen:
version=int(data[24+nicklen+passwordlen:28+nicklen+passwordlen].encode('hex'),16)
else:
version=0
params=nick,password,port,version,sequence
if (command==2):
if self.nick==None: return()
command = "motd"
params = sequence
if (command==3):
if self.nick==None: return()
command="list"
params = sequence
if (command==4):
if self.nick==None: return()
command="users"
params = sequence
if (command==5):
if self.nick==None: return()
command="join"
channellen=int(data[12:16].encode('hex'),16)
channel=data[16:16+channellen]
params = channel,sequence
if (command==6):
if self.nick==None: return()
command="status"
status=int(data[12:16].encode('hex'),16)
params = status,sequence
if (command==7):
if self.nick==None: return()
command="privmsg"
msglen=int(data[12:16].encode('hex'),16)
msg=data[16:16+msglen]
params = msg,sequence
if (command==8):
if self.nick==None: return()
command="challenge"
nicklen=int(data[12:16].encode('hex'),16)
nick=data[16:16+nicklen]
channellen=int(data[16+nicklen:16+nicklen+4].encode('hex'),16)
channel=data[20+nicklen:20+nicklen+channellen]
params = nick,channel,sequence
if (command==9):
if self.nick==None: return()
command="accept"
nicklen=int(data[12:16].encode('hex'),16)
nick=data[16:16+nicklen]
channellen=int(data[16+nicklen:16+nicklen+4].encode('hex'),16)
channel=data[20+nicklen:20+nicklen+channellen]
params = nick,channel,sequence
if (command==0xa):
if self.nick==None: return()
command="decline"
nicklen=int(data[12:16].encode('hex'),16)
nick=data[16:16+nicklen]
params = nick,sequence
if (command==0xb):
command="getpeer"
quarklen=int(data[12:16].encode('hex'),16)
quark=data[16:16+quarklen]
fbaport=int(data[16+quarklen:16+quarklen+4].encode('hex'),16)
params = quark,fbaport,sequence
if (command==0xc):
command="getnicks"
quarklen=int(data[12:16].encode('hex'),16)
quark=data[16:16+quarklen]
params = quark,sequence
if (command==0xf):
command="fba_privmsg"
quarklen=int(data[12:16].encode('hex'),16)
quark=data[16:16+quarklen]
msglen=int(data[16+quarklen:16+quarklen+4].encode('hex'),16)
msg=data[20+quarklen:20+quarklen+msglen]
params = quark,msg,sequence
if (command==0x10):
if self.nick==None: return()
command="watch"
nicklen=int(data[12:16].encode('hex'),16)
nick=data[16:16+nicklen]
params = nick,sequence
if (command==0x11):
command="savestate"
quarklen=int(data[12:16].encode('hex'),16)
quark=data[16:16+quarklen]
block1=data[16+quarklen:20+quarklen]
block2=data[20+quarklen:24+quarklen]
#buflen=int(data[24+quarklen:24+quarklen+4].encode('hex'),16)
#gamebuf=data[28+quarklen:28+quarklen+buflen]
gamebuf=data[24+quarklen:length+4]
params = quark,block1,block2,gamebuf,sequence
if (command==0x12):
command="gamebuffer"
quarklen=int(data[12:16].encode('hex'),16)
quark=data[16:16+quarklen]
#buflen=int(data[16+quarklen:16+quarklen+4].encode('hex'),16)
#gamebuf=data[20+quarklen:20+quarklen+buflen]
gamebuf=data[20+quarklen:length+4]
params = quark,gamebuf,sequence
if (command==0x13):
command="ggpotv"
quarklen=int(data[12:16].encode('hex'),16)
quark=data[16:16+quarklen]
gamebuf=data[20+quarklen:length+4]
params = quark,gamebuf,sequence
if (command==0x14):
command="spectator"
quarklen=int(data[12:16].encode('hex'),16)
quark=data[16:16+quarklen]
params = quark,sequence
if (command==0x1c):
if self.nick==None: return()
command="cancel"
nicklen=int(data[12:16].encode('hex'),16)
nick=data[16:16+nicklen]
params = nick,sequence
if command in ["join", "challenge", "decline", "cancel", "accept", "getnicks", "watch", "spectator"]:
logging.info('[%s] SEQUENCE: %d COMMAND: %s %s' % (self.client_ident(),sequence,command,params[0]))
elif command in ["savestate", "list", "users", "ggpotv"]:
logging.debug('[%s] SEQUENCE: %d COMMAND: %s' % (self.client_ident(),sequence,command))
else:
logging.info('[%s] SEQUENCE: %d COMMAND: %s' % (self.client_ident(),sequence,command))
try:
handler = getattr(self, 'handle_%s' % (command), None)
if not handler:
logging.info('[%s] No handler for command: %s. Full line: %r' % (self.client_ident(), command, data))
if self.nick==None: return()
command="unknown"
params = sequence
handler = getattr(self, 'handle_%s' % (command), None)
response = handler(params)
except AttributeError, e:
raise e
logging.error('[%s] ERROR (1) %s in command %s' % (self.client_ident(), e, command))
except GGPOError, e:
response = '[%s] ERROR (2) %s %s in command %s' % (self.client_ident(), e.code, e.value, command)
logging.error('%s' % (response))
except Exception, e:
response = '[%s] ERROR (3) %s in command %s' % (self.client_ident(), repr(e), command)
logging.error('%s' % (response))
raise
if (len(data) > length+4 ):
pdu=data[length+4:]
self.parse(pdu)
return response
def handle(self):
logging.info('[%s] Client connected' % (self.client_ident(), ))
data=''
while True:
try:
ready_to_read, ready_to_write, in_error = select.select([self.request], [], [], 0.1)
except Exception, e:
logging.debug('[%s] ERROR: %s' % (self.client_ident(), e))
break
# Write any commands to the client
while self.send_queue:
msg = self.send_queue.pop(0)
#logging.debug('[SEND] to %s: %r' % (self.client_ident(), msg))
try:
self.request.send(msg)
except:
logging.info('[%s] Can\'t send data. Finishing ' % (self.client_ident(), ))
self.finish()
# See if the client has any commands for us.
if len(ready_to_read) == 1 and ready_to_read[0] == self.request:
try:
dataread=self.request.recv(16384)
data+=dataread
if not dataread:
break
#logging.debug('[RECV] from %s: %r' % (self.client_ident(), data))
while (len(data)-4 > int(data[0:4].encode('hex'),16)):
length=int(data[0:4].encode('hex'),16)
response = self.parse(data[0:length+4])
data=data[length+4:]
if len(data)-4 == int(data[0:4].encode('hex'),16):
response = self.parse(data)
data=''
if response:
logging.debug('<<<<<<>>>>>to %s: %r' % (self.client_ident(), response))
#self.request.send(response)
except Exception, e:
logging.info('[%s] Can\'t read data. Finishing. ERROR: %s' % (self.client_ident(), repr(e)))
self.finish()
self.request.close()
def get_peer_from_quark(self, quark):
"""
Returns a GGPOClient object representing our FBA peer's ggpofba connection, or self if not found
"""
connections = dict(self.server.connections)
for host in connections:
try:
client = self.server.connections[host]
if client.clienttype=="player" and client.quark==quark and client.host!=self.host:
return client
except KeyError:
pass
return self
def get_myclient_from_quark(self, quark):
"""
Returns a GGPOClient object representing our own client connection, or self if not found
"""
try:
quarkobject = self.server.quarks[quark]
if quarkobject.p1client!=None and self.nick!=None:
if quarkobject.p1client.nick == self.nick:
return quarkobject.p1client
if quarkobject.p2client!=None and self.nick!=None:
if quarkobject.p2client.nick == self.nick:
return quarkobject.p2client
except KeyError:
pass
clients = dict(self.server.clients)
for nick in clients:
client = self.get_client_from_nick(nick)
if client.clienttype=="client" and client.quark==quark and client.host[0]==self.host[0]:
return client
return self
def get_myclient_from_quark_and_peer(self, quark, peer):
"""
Returns a GGPOClient object representing our own client connection, or self if not found
"""
clients = dict(self.server.clients)
for nick in clients:
client = self.get_client_from_nick(nick)
if client.clienttype=="client" and client.quark==quark and client.nick!=peer.nick:
return client
return self
def handle_fba_privmsg(self, params):
"""
Handle sending messages inside the FBA emulator.
"""
quark, msg, sequence = params
# send the ACK to the client
#self.send_ack(sequence)
peer=self.get_peer_from_quark(quark)
# send the in-game chat messages to the client
# this helps people using experimental blitter that can't see the OSD text
try:
quarkobject = self.server.quarks[quark]
if quarkobject.p1.nick==self.nick:
mypeer = quarkobject.p2client
myself = quarkobject.p1client
else:
mypeer = quarkobject.p1client
myself = quarkobject.p2client
negseq=4294967294 #'\xff\xff\xff\xfe'
response = self.reply(negseq,self.sizepad("System")+self.sizepad('GAME: <'+self.nick+'> '+msg))
logging.debug('to %s: %r' % (mypeer.client_ident(), response))
mypeer.send_queue.append(response)
logging.debug('to %s: %r' % (myself.client_ident(), response))
myself.send_queue.append(response)
except:
pass
negseq=4294967288 #'\xff\xff\xff\xf8'
pdu=self.sizepad(quark)
pdu+=self.sizepad(self.nick)
pdu+=self.sizepad(msg)
response = self.reply(negseq,pdu)
logging.debug('to %s: %r' % (peer.client_ident(), response))
peer.send_queue.append(response)
logging.debug('to %s: %r' % (self.client_ident(), response))
self.send_queue.append(response)
def handle_gamebuffer(self, params):
quark, gamebuf, sequence = params
negseq=4294967284 #'\xff\xff\xff\xf4'
pdu=gamebuf
response = self.reply(negseq,pdu)
connections = dict(self.server.connections)
for host in connections:
try:
client = self.server.connections[host]
if client.clienttype=="spectator" and client.quark==quark and client.side==0:
logging.debug('to %s: %r' % (client.client_ident(), response))
client.send_queue.append(response)
client.side=3
except KeyError:
pass
# record match for future broadcast
try:
quarkobject = self.server.quarks[quark]
except KeyError:
return()
if quarkobject.p1.nick==None and quarkobject.p2.nick==None and quarkobject.channel.name=='lobby':
self.finish()
return()
if self.check_quark_format(quark) and quarkobject.recorded == False:
quarkobject.recorded=True
# match started successfully, reset useports on both clients:
quarkobject.p1client.useports=False
quarkobject.p2client.useports=False
quarkobject.p1client.warnmsg=''
quarkobject.p2client.warnmsg=''
# store player nicknames
date = datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")
conn = dbconnect()
cursor = conn.cursor()
sql = "INSERT INTO quarks (quark, player1, player2, channel, date, realtime_views, saved_views, p1_country, p2_country, duration) VALUES ("+PARAM+","+PARAM+","+PARAM+","+PARAM+","+PARAM+",0,0,"+PARAM+","+PARAM+",-1)"
try:
cursor.execute(sql, [quark, quarkobject.p1.nick, quarkobject.p2.nick, quarkobject.channel.name, date, quarkobject.p1client.cc, quarkobject.p2client.cc])
conn.commit()
except:
# close the connection if we can't add the quark into the db
conn.close()
self.finish()
return()
conn.close()
# store initial savestate (gamebuffer)
quarkfile = os.path.join(os.path.realpath(os.path.dirname(sys.argv[0])),'quarks', 'quark-'+quark+'-gamebuffer.fs')
if not os.path.exists(quarkfile):
try:
os.mkdir(os.path.dirname(quarkfile))
except:
pass
f=open(quarkfile, 'wb')
f.write(response)
f.close()
def handle_savestate(self, params):
quark, block1, block2, gamebuf, sequence = params
# send ACK to the player
self.send_ack(sequence)
negseq=4294967283 #'\xff\xff\xff\xf3'
pdu=block2+block1+gamebuf
response = self.reply(negseq,pdu)
connections = dict(self.server.connections)
for host in connections:
try:
client = self.server.connections[host]
if client.clienttype=="spectator" and client.quark==quark and client.side==3:
logging.debug('to %s: %r' % (client.client_ident(), response))
client.send_queue.append(response)
except KeyError:
pass
# record match for future broadcast
try:
quarkobject = self.server.quarks[quark]
except KeyError:
return()
if self.check_quark_format(quark) and quarkobject.recorded == True:
quarkfile = os.path.join(os.path.realpath(os.path.dirname(sys.argv[0])),'quarks', 'quark-'+quark+'-savestate.fs')
if not os.path.exists(quarkfile):
try:
os.mkdir(os.path.dirname(quarkfile))
except:
pass
try:
f=open(quarkfile, 'ab')
f.write(response)
f.close()
except IOError:
logging.debug('[%s] IOError in command savestate' % (self.client_ident()))
def handle_getnicks(self, params):
quark, sequence = params
# to replay a saved quark
try:
quarkobject = self.server.quarks[quark]
except KeyError:
# make sure the quark format is valid
if not self.check_quark_format(quark):
return()
dbfile = os.path.join(os.path.realpath(os.path.dirname(sys.argv[0])),'db', 'ggposrv.sqlite3')
if not os.path.exists(dbfile):
return()
conn = dbconnect()
cursor = conn.cursor()
sql = "SELECT player1, player2, channel FROM quarks WHERE quark=" + PARAM
cursor.execute(sql, [(quark)])
player1,player2,channel=cursor.fetchone()
conn.close()
if channel=='':
channel="lobby"
if channel=='ssf2t':
channel="ssf2xj"
if player1=='' and player2=='':
return()
# if the quark file is not present in the local cache, retrieve it from S3
quarkfile = os.path.join(os.path.realpath(os.path.dirname(sys.argv[0])),'quarks', 'quark-'+quark+'-gamebuffer.fs')
if not os.path.exists(quarkfile):
bucket_name = 'fightcade.quarks'
conn = boto.connect_s3()
bucket = conn.get_bucket(bucket_name, validate=False)
tarball = 'quark-'+quark+'.tar'
k = bucket.get_key(tarball)
tarball_fullpath = os.path.join(os.path.realpath(os.path.dirname(sys.argv[0])),'quarks',tarball)
k.get_contents_to_filename(tarball_fullpath)
tar = tarfile.open(tarball_fullpath)
tar.extractall(path=os.path.join(os.path.realpath(os.path.dirname(sys.argv[0])),'quarks'))
tar.close()
os.remove(tarball_fullpath)
# we keep the quark in the local cache & remove it from S3
k.delete()
pdu='\x00\x00\x00\x00'
pdu+=self.sizepad(player1)
pdu+=self.sizepad(player2)
pdu+='\x00\x00\x00\x00'
pdu+=self.pad2hex(0)
response = self.reply(sequence,pdu)
logging.debug('to %s: %r' % (self.client_ident(), response))
self.request.send(response)
# now broadcast the quark to the client
f=open(quarkfile, 'rb')
response = f.read()
f.close()
logging.debug('to %s: %r' % (self.client_ident(), response))
self.request.send(response)
self.side=3
quarkfile = os.path.join(os.path.realpath(os.path.dirname(sys.argv[0])),'quarks', 'quark-'+quark+'-savestate.fs')
if not os.path.exists(quarkfile):
quarkfile = os.path.join(os.path.realpath(os.path.dirname(sys.argv[0])),'quarks', 'quark-'+quark+'-savestate.fs.gz')
if not os.path.exists(quarkfile):
return()
if quarkfile.endswith(".gz"):
f=gzip.open(quarkfile)
else:
f=open(quarkfile)
try:
CHUNKSIZE=self.server.channels[channel].chunksize
except:
CHUNKSIZE=1096
response = f.read(CHUNKSIZE)
while (response):
time.sleep(0.8)
try:
logging.debug('to %s: %r' % (self.client_ident(), response))
self.request.send(response)
except:
logging.debug('[%s]: spectator disconnected from broadcast' % (self.client_ident()))
break
response = f.read(CHUNKSIZE)
f.close()
self.finish()
return()
i=0
while True:
if (quarkobject.p1 != None and quarkobject.p2 != None) or i>=30:
break
i=i+1
time.sleep(1)
pdu='\x00\x00\x00\x00'
if (i<30):
pdu+=self.sizepad(quarkobject.p1.nick)
pdu+=self.sizepad(quarkobject.p2.nick)
else:
# avoid crashing fba if we can't get our peer
pdu+='\x00\x00\x00\x00'
pdu+='\x00\x00\x00\x00'
pdu+='\x00\x00\x00\x00'
if self.clienttype=="player":