em_server.rb 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  1. #!/usr/bin/env ruby
  2. require 'eventmachine'
  3. require 'digest/md5'
  4. require 'fiber'
  5. require 'geoip'
  6. require 'socket'
  7. require 'timeout'
  8. require './em_server_accounts.rb'
  9. require './em_server_initqwserverlist.rb'
  10. $version = "0.6em_specservers_dupe_election"
  11. $debug = 0
  12. class GameServers
  13. attr_accessor :gameservers # now, @gameservers is accessible via GameServers.gameservers
  14. def initialize
  15. @gameservers = Hash.new
  16. @gameservers.default = {
  17. :reverse_dns => "",
  18. :hostname_dns => "",
  19. :cool_dns => "",
  20. :type => "",
  21. :serverinfos => "",
  22. :timestamp => 0,
  23. }
  24. @gameservers["blah:blah"]
  25. wat = Hash.new(@gameservers["blah:blah"])
  26. wat
  27. wat.store(:reverse_dns, "6")
  28. @gameservers.merge(wat)
  29. p @gameservers
  30. p @gameservers.default
  31. wat = Hash.new(@gameservers["blah:blah"])
  32. wat
  33. wat.store(:hostname_dns, "12")
  34. @gameservers.merge(wat)
  35. p @gameservers
  36. p @gameservers.default
  37. end
  38. def scanserver(iphostport, type="qw", force=false)
  39. put_log "scanserver drin"
  40. if iphostport =~ /^(\d+\.\d+\.\d+\.\d+):(\d{1,5})/
  41. iphost = $1
  42. ipport = $2
  43. if type == "qw"
  44. #p current
  45. # check if it already exists
  46. #if @gameservers["#{iphost}:#{ipport}"][:timestamp] > 0
  47. # if old general data, then freshly get general data...
  48. # if @gameservers["#{iphost}:#{ipport}"][:timestamp] + 60 * 60 * 20 < Time.now.utc.to_i || force == true
  49. # end # of old
  50. #else
  51. current = Hash.new
  52. serverinfos = qwstatus(iphost, ipport)
  53. current.store(:serverinfos, serverinfos)
  54. current.store(:reverse_dns, find_reverse_dname(iphost))
  55. current.store(:hostname_dns, qw_find_dname_by_serverinfos(serverinfos))
  56. current.store(:type, "qw")
  57. # set new timestamp
  58. current.store(:timestamp, Time.now.utc.to_i)
  59. @gameservers.store("#{iphost}:#{ipport}", current) # save it all.
  60. current.store(:cool_dns, find_cooldns(iphost, ipport))
  61. @gameservers.store("#{iphost}:#{ipport}", current) # save it all.
  62. #put_log "the saved one: #{@gameservers.fetch("#{iphost}:#{ipport}").fetch(:cool_dns)}"
  63. #puts "ALL"
  64. #p @gameservers
  65. #puts "DEFAULT of the hash"
  66. #p @gameservers.default
  67. #end
  68. end # of type qw
  69. end # of check form of iphostport parameter
  70. end # of scan()
  71. def scanserverlist(gs_array, type="qw")
  72. put_log "scanserverlist drin"
  73. gs_array.each do
  74. |gserver|
  75. scanserver(gserver, type)
  76. end
  77. put_log "End of scanning."
  78. #put_log "foppa: #{@gameservers.fetch("89.104.194.146:27501")} "
  79. end # of scanserverlist()
  80. def get_cool_dns(iphost, ipport)
  81. put_log "get_cool_dns drin"
  82. cool_dns = @gameservers.fetch("#{iphost}:#{ipport}").fetch(:cool_dns)
  83. put_log "cool_dns for #{iphost}:#{ipport} is: #{cool_dns}"
  84. return cool_dns
  85. rescue
  86. scanserver("#{iphost}:#{ipport}", "qw")
  87. cool_dns = @gameservers.fetch("#{iphost}:#{ipport}").fetch(:cool_dns)
  88. put_log "cool_dns for #{iphost}:#{ipport} is: #{cool_dns}"
  89. return cool_dns
  90. end
  91. private # all following methods are private
  92. # returns serverinfo hash
  93. def qwstatus(iphost, ipport)
  94. put_log "qwstatus drin"
  95. udp_payload = [0xFF, 0xFF, 0xFF, 0xFF]
  96. udp_payload.concat(string2bytearray("status 23"))
  97. udp_payload.concat([0x0a]) # linefeed at the end
  98. udp_payload = udp_payload.pack("C*")
  99. #p udp_payload
  100. Timeout::timeout(2) do
  101. begin
  102. u2 = UDPSocket.new
  103. #put_log "#{iphost} #{ipport} #{udp_payload}"
  104. u2.send(udp_payload, 0, iphost, ipport)
  105. #put_log "sent"
  106. the_return = u2.recv(500)
  107. u2.close
  108. #put_log "muh #{the_return}"
  109. if the_return =~ /\W\W\W\Wn\\(.+)$/
  110. line = $1
  111. #put_log "line #{line}"
  112. matches = line.scan(/(.+?)\\(.+?)(\\|$)/)
  113. the_hash = Hash.new
  114. matches.each {
  115. |k, v, _|
  116. the_hash[k] = "#{v}"
  117. }
  118. return the_hash
  119. else
  120. return false
  121. end
  122. rescue Exception => e
  123. puts e.message
  124. end # of begin
  125. end # of Timeout
  126. end
  127. def find_cooldns_full(iphost, ipport)
  128. targetname = iphost
  129. # resolve it to a dns name (reverse lookup)
  130. if targetname == iphost # if it is still default
  131. put_log "Ip not resolved .. we try hostname dns finder"
  132. targetname = qw_find_dname_in_hostnames(iphost, ipport)
  133. end
  134. # resolve it to a dns name (reverse lookup)
  135. if targetname == iphost
  136. put_log "Still no resolve .. we try reverse dns lookup"
  137. targetname = find_reverse_dname(iphost)
  138. end
  139. return targetname
  140. end
  141. def find_cooldns(iphost, ipport)
  142. put_log "find_cooldns drin"
  143. current = @gameservers["#{iphost}:#{ipport}"] # only use this for reading...
  144. my_cooldns = iphost
  145. # we still haven't found a cool dns
  146. if (my_cooldns == iphost) && (not current[:hostname_dns].to_s.empty?)
  147. put_log "Try if #{current[:hostname_dns]} resolves to #{iphost}"
  148. begin
  149. ip_of_hostnamedns = Resolv.getaddress(current[:hostname_dns])
  150. if ip_of_hostnamedns && (ip_of_hostnamedns == iphost)
  151. # ok, we take it.
  152. put_log "Ok, we take #{current[:hostname_dns]} for #{iphost} here.."
  153. my_cooldns = current[:hostname_dns]
  154. else
  155. put_log "Found #{current[:hostname_dns]} but #{ip_of_hostnamedns} is not #{iphost}"
  156. end
  157. rescue Exception => e
  158. my_cooldns = iphost
  159. end
  160. end
  161. # we still haven't found a cool dns
  162. unless current[:reverse_dns].to_s.empty?
  163. if my_cooldns == iphost
  164. rdns = current[:reverse_dns]
  165. # if the resulting dns name...
  166. # .. is too long, use ip-address instead.
  167. # .. has too many dots, use ip-address instead.
  168. # .. has too many numbers, use ip-address instead.
  169. if rdns.length > 21 || rdns.split(".").size > 3 || rdns.scan(/\d/).size > 3
  170. put_log "cutting down host_name: #{rdns}, because:"
  171. put_log "length: #{rdns.length}"
  172. put_log "chunks count: #{rdns.split(".").size}"
  173. put_log "num count: #{rdns.scan(/\d/).size}"
  174. else
  175. my_cooldns = rdns
  176. end # of Resolv.getname
  177. end
  178. end
  179. put_log "COOOOOOOOOOOOLDNS: #{my_cooldns}"
  180. my_cooldns
  181. end
  182. def find_reverse_dname(iphost)
  183. put_log "find_reverse_dname drin"
  184. dname = Resolv.getname(iphost)
  185. ip_of_dname = Resolv.getaddress(dname)
  186. if ip_of_dname == iphost
  187. return dname
  188. end
  189. rescue
  190. iphost
  191. end
  192. def qw_find_dname_by_udp(iphost, ipport)
  193. targetname = iphost # set a default
  194. # get hostname from a qw status packet! perhaps there's a DNS name inside, which we can use!
  195. status = qwstatus(iphost, ipport)
  196. p status
  197. if status["hostname"] =~ /([\w\.-]{3,}\.\w{2,4})/
  198. hostnamedns = $1.downcase
  199. begin
  200. ip_of_hostnamedns = Resolv.getaddress(hostnamedns)
  201. if ip_of_hostnamedns && (ip_of_hostnamedns == iphost)
  202. # ok, we take it.
  203. put_log "Ok, we take #{hostnamedns} for #{iphost} here.."
  204. targetname = hostnamedns
  205. else
  206. put_log "Found #{hostnamedns} but #{ip_of_hostnamedns} is not #{iphost}"
  207. end
  208. rescue Exception => e
  209. targetname = iphost
  210. end
  211. end
  212. targetname
  213. end
  214. def qw_find_dname_by_serverinfos(serverinfos)
  215. hostnamedns = ""
  216. begin
  217. hostname = serverinfos.fetch("hostname")
  218. if hostname =~ /([\w\.-]{3,}\.\w{2,4})/
  219. hostnamedns = $1.downcase
  220. end
  221. return hostnamedns
  222. rescue
  223. return ""
  224. end
  225. end
  226. end # of Class GameServers!
  227. def string2bytearray(text)
  228. return_array = Array.new
  229. text.each_byte{
  230. |b|
  231. return_array.push(b)
  232. }
  233. return_array
  234. end
  235. def put_log(msg)
  236. puts "#{Time.now.utc.strftime("%Y-%m-%d %H:%M:%S")}: #{msg}"
  237. end
  238. module CentralProtocolHandler
  239. @@connected_clients = Array.new
  240. @@broadcasts = Hash.new
  241. put_log "Server started"
  242. # default method that is being run on connection!
  243. def post_init # connection of someone starts here...
  244. @username = nil
  245. @my_servers = Hash.new
  246. @my_servers.default = {
  247. "active" => 0,
  248. "s-p" => "false",
  249. "ping" => 8888,
  250. }
  251. end
  252. ### setters
  253. def set_my_servers(server, key, value)
  254. current = Hash.new
  255. current.store(key, value)
  256. @my_servers[server] = @my_servers[server].merge(current)
  257. end
  258. def specbot_set_sp(username, server, value)
  259. @@connected_clients.each {|c|
  260. if c.username == username
  261. c.set_my_servers(server, "s-p", value)
  262. end
  263. }
  264. end
  265. ### getters
  266. def entered_username?
  267. !@username.nil? && !@username.empty? # then it's true
  268. end
  269. def username
  270. @username
  271. end
  272. def my_active_servers(active = true)
  273. unless @my_servers.nil? || @my_servers.empty?
  274. if active
  275. rethash = Hash.new
  276. @my_servers.each_pair{|k, v|
  277. if v["active"] == 1
  278. rethash[k] = @my_servers[k]
  279. end
  280. }
  281. rethash
  282. else
  283. @my_servers
  284. end
  285. end
  286. end
  287. def specbot_servers(flat = true)
  288. the_servers = Hash.new
  289. @@connected_clients.each {|c|
  290. if flat
  291. unless c.my_active_servers.nil? || c.my_active_servers.empty?
  292. the_servers = the_servers.merge(c.my_active_servers)
  293. end
  294. else
  295. unless c.my_active_servers.nil? || c.my_active_servers.empty?
  296. the_servers[c.username] = c.my_active_servers
  297. end
  298. end
  299. }
  300. the_servers
  301. end
  302. def specbot_ping(server)
  303. ms = my_active_servers(false)
  304. unless ms.nil?
  305. si = ms[server]
  306. p1 = si.fetch("ping").to_s.to_i
  307. return p1
  308. else
  309. return 8888
  310. end
  311. end
  312. def specbot_active?(server)
  313. ms = my_active_servers(false)
  314. unless ms.nil?
  315. si = ms[server]
  316. a1 = si.fetch("active")
  317. else
  318. a1 = 0
  319. end
  320. if a1 == 1
  321. return 1
  322. else
  323. return 0
  324. end
  325. end
  326. def specbot_sp?(server)
  327. ms = my_active_servers(false)
  328. unless ms.nil?
  329. si = ms[server]
  330. a1 = si.fetch("s-p")
  331. else
  332. a1 = "false"
  333. end
  334. if a1 == "true"
  335. return true
  336. else
  337. return false
  338. end
  339. end
  340. def my_maxservers
  341. if @my_maxservers.nil? || @my_maxservers.empty?
  342. nil
  343. else
  344. @my_maxservers
  345. end
  346. end
  347. def my_roles
  348. $user_roles[@username]
  349. end
  350. def my_cmds
  351. my_roles.collect {|v| $role_commands[v]}.flatten
  352. end
  353. # returns online users by default by searching through saved connections
  354. def ousers
  355. users = Array.new
  356. @@connected_clients.each {|c| users.push(c.username)}
  357. users
  358. end # of ousers
  359. # returns online users by searching through saved connections that have the specified role
  360. def ousers_by_role(role)
  361. users = Array.new
  362. @@connected_clients.each {|c|
  363. if c.my_roles.include?(role)
  364. users.push(c.username)
  365. end
  366. }
  367. users
  368. end
  369. # returns connections by searching through saved connections that have the specified role
  370. def connections_by_role(role)
  371. conns = Array.new
  372. @@connected_clients.each {|c|
  373. if c.my_roles.include?(role)
  374. conns.push(c)
  375. end
  376. }
  377. conns
  378. end
  379. ### checkers
  380. def allowed_cmd(inputmessage)
  381. my_cmds.each{|c|
  382. #print "A #{c} B #{inputmessage}\n"
  383. if inputmessage =~ /^#{c}/
  384. return true
  385. end
  386. }
  387. false
  388. end
  389. def online(user)
  390. if ousers.include? user
  391. true
  392. else
  393. false
  394. end
  395. end
  396. ### actions
  397. def specbot_dupecheck()
  398. put_log "specbot_dupecheck drin"
  399. conns = connections_by_role("specbot")
  400. # if this connection has a same key than another connection
  401. # then fight .. which connection should have that server unassigned. REQ_PING
  402. # the one with the better ping will win and the one with the worse ping will get a new free server slot ;)
  403. # we have at least 2 bots... > 1
  404. conns.repeated_combination(2){|c|
  405. c1 = c[0]
  406. c2 = c[1]
  407. unless c1 == c2
  408. unless c1.my_active_servers.nil? || c2.my_active_servers.nil?
  409. dupes = c1.my_active_servers.keys & c2.my_active_servers.keys
  410. if dupes.size > 0
  411. # damn, there's dupes.
  412. put_log "the dupes are: #{dupes.join(", ")} on #{c1.username} and #{c2.username}"
  413. dupes.each{|d|
  414. write_user("REQ_PING #{d}", c1.username)
  415. write_user("REQ_PING #{d}", c2.username)
  416. EventMachine.add_timer 2, proc {
  417. p1 = c1.specbot_ping(d)
  418. p2 = c2.specbot_ping(d)
  419. a1 = c1.specbot_active?(d)
  420. a2 = c2.specbot_active?(d)
  421. if p1 <= p2
  422. unless a2 == 0
  423. write_user("REQ_UNASSIGN #{d}", c2.username)
  424. end
  425. else
  426. unless a1 == 0
  427. write_user("REQ_UNASSIGN #{d}", c1.username)
  428. end
  429. end
  430. }
  431. }
  432. end
  433. end
  434. end
  435. }
  436. end # of specbot_dupecheck
  437. # searches through our hash of saved connections and writes them a messages.
  438. def write_user(input, username = nil)
  439. if username.nil? || username.empty?
  440. username = @username
  441. end
  442. if @@connected_clients.find { |c| c.username == username }
  443. connection = @@connected_clients.find { |c| c.username == username }
  444. put_log("to #{username}: #{input}")
  445. sometime = "#{Time.now.utc.strftime("%Y-%m-%d %H:%M:%S %z")}"
  446. line = "#{sometime}: #{input}\n"
  447. connection.send_data line
  448. end
  449. end # of write_user
  450. # searches through roles and writes those users on their connections
  451. def write_role(role, input, *exempts)
  452. #find users with role
  453. users = Array.new
  454. $user_roles.each {|k, v|
  455. if v.include? role
  456. users.push(k)
  457. end
  458. }
  459. # find users that are online and inside Array "users"
  460. lala = Array.new
  461. users.each {|v|
  462. if ousers.include? v
  463. lala.push(v)
  464. end
  465. }
  466. # now write to them
  467. lala.each {|user|
  468. if not exempts.include? user
  469. write_user(input, user)
  470. end
  471. }
  472. end # of write_role()
  473. # what happens with what input?!
  474. def inputting(input)
  475. put_log("SYS #{@username} typed: #{input}")
  476. #write_user("SYS You typed: #{input}")
  477. if input =~ /^([A-Z_]+)/
  478. cmd = $1
  479. end
  480. # now we have the cmd .. or not ;)
  481. if input =~ /^[A-Z_]+ (.+)/
  482. payload = $1
  483. end
  484. # now we can use payload
  485. if allowed_cmd(cmd)
  486. ### typical system commands follow
  487. if cmd == "PING"
  488. write_user("PONG")
  489. elsif cmd == "C"
  490. if payload =~ /^(.+)$/
  491. write_role($default_role, "C #{@username}: #{$1}")
  492. else
  493. write_user("SYS Format is C <chattext>")
  494. end
  495. elsif cmd == "WHO"
  496. ousers.each {|ouser| write_user("WHO_RE #{ouser} ROLES: #{$user_roles[ouser].join(", ")}")}
  497. elsif cmd == "PART"
  498. write_user("SYS Goodbye '#{@username}'.")
  499. write_role($default_role, "PARTED User '#{@username}' leaves the party.", @username)
  500. return "bye"
  501. ### now for the good stuff, broadcasting role
  502. elsif cmd == "REQ_BC"
  503. # help with format .. but send the raw payload
  504. if payload =~ /^(.+),(.+),(.+),'(.+)','(.+)'$/
  505. # n f s ni txt
  506. error = 0
  507. # $&
  508. # The string matched by the last successful pattern match in this scope, or nil if the last pattern match failed. (Mnemonic: like & in some editors.) This variable is r
  509. network = $1
  510. freqname = $2
  511. source = $3
  512. nickname = $4
  513. text = $5
  514. if not network =~ /^(QWalt)|(QDEV)/
  515. write_user("SYS Network name #{network} is unknown: QWalt or QDEV allowed.")
  516. error = 1
  517. end
  518. if not freqname =~ /^(-qw-)|(-spam-)|(-dev-)/
  519. write_user("SYS Frequency name is unknown #{freqname}")
  520. error = 1
  521. end
  522. if source =~ /^(#.+)|(qw:\/\/)|(http:\/\/)/
  523. else
  524. write_user("SYS Source string is not in the form ^(#.+)|(qw:\/\/)|(http:\/\/) was: #{source}")
  525. error = 1
  526. end
  527. if not nickname =~ /^.+/
  528. write_user("SYS Nickname string is not in the form ^.+ #{nickname}")
  529. error = 1
  530. end
  531. if not text =~ /^.+/
  532. write_user("SYS Message string is not in the form ^.+ #{text}")
  533. error = 1
  534. end
  535. else # of payload has format
  536. write_user("SYS Command format is REQ_BC <network>,<frequency>,<source/channel>,'<nickname>','<message>'")
  537. error = 1
  538. end # of payload has format
  539. if error == 0
  540. # send REQ_BC to the corresponding role.
  541. bcid = Digest::MD5.hexdigest("%d %s %s %s %s %s" % [Time.now.utc.to_i, network, freqname, source, nickname, text])
  542. # so it only reaches the issuer of REQ_BC
  543. write_user("BC_ID #{bcid} for: #{network},#{freqname},#{source}")
  544. @@broadcasts[bcid] = @username
  545. # qw:// ip resolving
  546. if source =~ /^qw:\/\/(.+):(\d+)(.*)$/
  547. # ip address is 15 in length
  548. iphost = $1
  549. targetname = iphost # set a default
  550. ipport = $2
  551. rest = $3
  552. if iphost =~ /^\d+\.\d+\.\d+\.\d+/
  553. targetname = $gs.get_cool_dns(iphost, ipport)
  554. # find country code
  555. cc = GeoIP.new('GeoIP.dat').country(iphost)[3].to_s.downcase
  556. rest.prepend " #{cc}" unless cc.nil? || cc.empty? || targetname =~ /\.#{cc}$/
  557. end # if ip is x.x.x.x
  558. source = "qw://#{targetname}:#{ipport}#{rest}"
  559. end # of if source qw://x.x.x.x:portzzz
  560. # resolve
  561. finalmessage = "BC %s %s,%s,%s,'%s','%s'" % [bcid, network, freqname, source, nickname, text]
  562. write_role("broadcast", finalmessage, @username) # write to the role with the exempt of myself.
  563. end
  564. #end of REQ_BC here..
  565. elsif cmd == "BC_RE"
  566. if payload =~ /^(.+) (.+)=(\d+),(.+)=(\d+)$/
  567. bcid = $1
  568. user_string = $2
  569. user_count = $3
  570. item_string = $4
  571. item_count = $5
  572. payload = "%s %s=%d,%s=%d" % [bcid, user_string, user_count, item_string, item_count]
  573. # according bcid it is possible to get the originating user.. so send only to his topic!
  574. if @@broadcasts[bcid]
  575. to_user = @@broadcasts[bcid]
  576. write_user("SYS Broadcast reply bcid: #{bcid} underway to #{to_user}.")
  577. write_user("#{cmd} #{payload}", to_user)
  578. else
  579. write_user("SYS Broadcast reply bcid: #{bcid} underway.")
  580. write_role("broadcast", "#{cmd} #{payload}", @username)
  581. end
  582. else # of bc_re format check
  583. put_log "SYS Format is BC_RE <bcid> <userstring>=<usercount>,<itemstring>=<itemcount>"
  584. end
  585. ### the specbot-admin ROLE does ...
  586. elsif cmd == "REQ_ASSIGN"
  587. if payload =~ /^([a-zA-Z_\.]+) (\d+\.\d+\.\d+\.\d+:\d{1,5})[,]?(true|false)?/
  588. specbot = $1
  589. hostport = $2
  590. sp = $3
  591. if sp == "true"
  592. specbot_set_sp(specbot, hostport, sp)
  593. write_user("REQ_ASSIGN #{hostport},#{sp}", specbot)
  594. else
  595. write_user("REQ_ASSIGN #{hostport}", specbot)
  596. end
  597. else # of format check
  598. write_user("SYS Format is REQ_ASSIGN <specbot> <ip:port>[,<s-p;true or false>]")
  599. end
  600. elsif cmd == "REQ_UNASSIGN"
  601. if payload =~ /^([a-zA-Z_\.]+) (\d+\.\d+\.\d+\.\d+:\d{1,5})/
  602. specbot = $1
  603. hostport = $2
  604. write_user("REQ_UNASSIGN #{hostport}", specbot)
  605. else # of format check
  606. write_user("SYS Format is REQ_UNASSIGN <specbot> <ip:port>")
  607. end
  608. elsif cmd == "REQ_PING"
  609. if payload =~ /^([a-zA-Z_\.]+) (\d+\.\d+\.\d+\.\d+:\d{1,5})/
  610. specbot = $1
  611. hostport = $2
  612. write_user("REQ_PING #{hostport}", specbot)
  613. else # of format check
  614. write_user("SYS Format is REQ_PING <specbot> <ip:port>")
  615. end
  616. elsif cmd == "REQ_ASSIGNMENTS"
  617. if payload =~ /^([a-zA-Z_\.]+)/
  618. specbot = $1
  619. write_user("REQ_ASSIGNMENTS give me your assignments", specbot)
  620. else # of format check
  621. write_user("SYS Format is REQ_ASSIGNMENTS <specbot>")
  622. end
  623. elsif cmd == "REQ_MAXSERVERS"
  624. if payload =~ /^([a-zA-Z_\.]+)/
  625. specbot = $1
  626. write_user("REQ_MAXSERVERS how many do you do?", specbot)
  627. else # of format check
  628. write_user("SYS Format is REQ_MAXSERVERS <specbot>")
  629. end
  630. elsif cmd == "DUPECHECK"
  631. write_user("SYS specbot server monitoring dupecheck started")
  632. # start the central function for dupechecking:
  633. specbot_dupecheck()
  634. elsif cmd == "ELECTION"
  635. write_user("SYS specbot server ping election on global server list started")
  636. # start the central function for server election:
  637. all_servers = specbot_servers()
  638. put_log("#{all_servers}")
  639. write_user("SYS active unique server count: #{all_servers.size}")
  640. conns = connections_by_role("specbot")
  641. #für jeden server, jeden ping der einzelnen bots vergleichen..
  642. #falls ping info noch nicht vorhanden (>5000), dann einfordern
  643. all_servers.each_key{|k|
  644. put_log("SYS bots race for #{k} now..")
  645. conns.each{|c|
  646. ping = c.specbot_ping(k)
  647. if ping > 5000
  648. write_user("REQ_PING #{k}", c.username)
  649. end
  650. }
  651. EventMachine.add_timer 5, proc {
  652. lastbest = 5000
  653. winner = ""
  654. conns.each{|c|
  655. ping = c.specbot_ping(k)
  656. put_log("SYS #{ping} of #{c.username} to #{k}")
  657. if ping < lastbest
  658. lastbest = ping
  659. winner = c
  660. put_log("SYS - current best bot for #{k} is #{c.username}")
  661. end
  662. }
  663. put_log("SYS --> best bot for #{k} is #{winner.username}")
  664. conns.each{|c|
  665. a = c.specbot_active?(k)
  666. unless c == winner
  667. unless a == 0
  668. write_user("REQ_UNASSIGN #{k}", c.username)
  669. end
  670. end
  671. if c == winner
  672. unless a == 1
  673. as = all_servers[k]
  674. sp = as.fetch("s-p")
  675. if sp == "true" || sp == "1"
  676. write_user("REQ_ASSIGN #{k},true", c.username)
  677. else
  678. write_user("REQ_ASSIGN #{k}", c.username)
  679. end
  680. end
  681. end
  682. }
  683. } # end of timer
  684. } # end of all active servers loop
  685. ### the specbot ROLE does ...
  686. elsif cmd == "ASSIGNMENTS_RE"
  687. if payload =~ /^(\d+\.\d+\.\d+\.\d+:\d{1,5}),(.*),(.*)/
  688. hostport = $1
  689. sp = $2
  690. ping = $3.chomp
  691. p hostport
  692. p sp
  693. p ping
  694. current = Hash.new()
  695. current.store("active", 1)
  696. current.store("s-p", sp)
  697. current.store("ping", ping)
  698. # save the hash current to the hash @my_servers
  699. @my_servers[hostport] = @my_servers[hostport].merge(current)
  700. p @my_servers
  701. # save new hash to a config file or sth. fixme
  702. end
  703. #end of ASSIGNMENTS_RE here..
  704. elsif cmd == "MAXSERVERS_RE"
  705. if payload =~ /^(\d+)/
  706. @my_maxservers = $1
  707. end
  708. #end of MAXSERVERS_RE here..
  709. elsif cmd == "PING_RE"
  710. if payload =~ /^(\d+\.\d+\.\d+\.\d+:\d{1,5}),(.*)/
  711. hostport = $1
  712. ping = $2
  713. current = Hash.new()
  714. current.store("ping", ping)
  715. # save the hash current to the hash @my_servers
  716. @my_servers[hostport] = @my_servers[hostport].merge(current)
  717. p @my_servers
  718. # save new hash to a config file or sth. fixme
  719. end
  720. #end of PING_RE here..
  721. elsif cmd == "ASSIGN_RE"
  722. #assign_re should only be issued when a req_assign was issued to the specbot before
  723. if payload =~ /^(\d+\.\d+\.\d+\.\d+:\d{1,5}) ([A-Z]+)[\s]?(.*)/
  724. hostport = $1
  725. good = $2
  726. reason = $3
  727. if good == "OK"
  728. current = Hash.new()
  729. current.store("active", 1)
  730. @my_servers[hostport] = @my_servers[hostport].merge(current) # this way it preserves previously saved ping values
  731. write_user("REQ_PING #{hostport}")
  732. put_log "SYS #{username} assigned to #{hostport} and asked ping for it."
  733. write_role("specbot_admin", "SYS #{username} assigned to #{hostport} and asked ping for it.")
  734. else
  735. put_log "SYS #{username} failed to assign #{hostport}, reason: '#{reason}'"
  736. write_role("specbot_admin", "SYS #{username} failed to assign #{hostport}, reason: '#{reason}'")
  737. end
  738. end
  739. #end of ASSIGN_RE here..
  740. elsif cmd == "UNASSIGN_RE"
  741. if payload =~ /^(\d+\.\d+\.\d+\.\d+:\d{1,5}) ([A-Z]+)[\s]?(.*)/
  742. hostport = $1
  743. good = $2
  744. reason = $3
  745. if good == "OK"
  746. current = Hash.new()
  747. current.store("active", 0)
  748. @my_servers[hostport] = @my_servers[hostport].merge(current) # this way it preserves previously saved ping values
  749. put_log "SYS #{username} unassigned #{hostport}"
  750. write_role("specbot_admin", "SYS #{username} unassigned #{hostport}")
  751. else
  752. put_log "SYS #{username} failed to unassign #{hostport}, reason: '#{reason}'"
  753. write_role("specbot_admin", "SYS #{username} failed to unassign #{hostport}, reason: '#{reason}'")
  754. end
  755. end
  756. #end of UNASSIGN_RE here..
  757. elsif cmd == "REQ_DNS"
  758. # help with format .. but send the raw payload
  759. if payload =~ /^(\d+\.\d+\.\d+\.\d+):(\d{1,5})/
  760. iphost = $1
  761. ipport = $2
  762. targetname = $gs.get_cool_dns(iphost, ipport)
  763. write_user("DNS_RE #{iphost}:#{ipport} #{targetname}") # write back to asking user.
  764. else # of payload has format
  765. write_user("SYS Command format is REQ_DNS <serverip>:<serverport>")
  766. error = 1
  767. end # of if payload has format
  768. #end of REQ_DNS here..
  769. end
  770. else # of if allowed command
  771. if input.length > 15
  772. input = input.slice(0,14) + ".."
  773. end
  774. write_user("SYS Command '#{input}' not allowed, your commands are: #{my_cmds.join(", ")}.")
  775. end # of if allowed command
  776. end # of inputting!
  777. # default method that is being run on receiving data!
  778. def receive_data(data) # connection receives a line on the server end
  779. data = data.chomp unless data.chomp.nil?
  780. data.each_line do |line|
  781. unless line.empty?
  782. if entered_username? # oh, it's a known user
  783. # it's alive! kill ping timer, set a new one:
  784. if @ping_timer
  785. EventMachine.cancel_timer(@ping_timer)
  786. end
  787. @ping_timer = EventMachine.add_periodic_timer 180, proc { write_user("PING alive?") }
  788. # work on input
  789. inputter = inputting(line)
  790. if inputter == "bye"
  791. close_connection
  792. end
  793. else # of username known, then it seems to be the first connect
  794. # and this line is the user name coming in!
  795. username = line
  796. if online(username)
  797. put_log "SYS User '#{username}' tried to double connect. Say bye bye."
  798. send_data "SYS Hey '#{username}', only one connection allowed. Bye.\n"
  799. EventMachine.add_timer 1, proc {
  800. write_user("PING check forced", username)
  801. close_connection
  802. }
  803. return false
  804. end
  805. if $user_roles.any? {|k| k.include? username}
  806. @username = username
  807. @@connected_clients.push(self)
  808. @ping_timer = EventMachine.add_periodic_timer 90, proc { write_user("PING alive?") }
  809. # starting a pinger
  810. put_log("SYS '#{@username}' connected. Online now: #{ousers.join(", ")}")
  811. write_user("HELLO Hi user '#{@username}'! How are you? I'm '#{$version}'")
  812. write_user("ROLES #{my_roles.join(", ")}")
  813. write_user("COMMANDS #{my_cmds.join(", ")}")
  814. write_role($default_role, "JOINED User '#{@username}' just joined the party.", @username)
  815. # if that guy is a specbot, ask it for his current list
  816. if my_roles.include?("specbot")
  817. EventMachine.add_timer 2, proc {
  818. write_user("REQ_MAXSERVERS how many can you do?")
  819. write_user("REQ_ASSIGNMENTS gimme all your servers")
  820. }
  821. # if more than 1 specbots are connected, then we want to activate the dupe-check.
  822. if connections_by_role("specbot").size > 1
  823. # in 6 seconds we start it. by then, we should have the full serverlists of all bots
  824. EventMachine.add_timer 6, proc {
  825. put_log("this guy: #{username} triggers the dupecheck now")
  826. specbot_dupecheck
  827. }
  828. end
  829. end
  830. else
  831. put_log "SYS User '#{username}' unknown to me. Saying bye."
  832. send_data "SYS User '#{username}' unknown to me. Bye.\n"
  833. # disconnect him
  834. close_connection
  835. end
  836. end # of username known
  837. end # of unless line.empty?
  838. end # of data.each_line
  839. end # of receive data
  840. # default method that is being run on disconnection!
  841. def unbind # a connection goes bye bye
  842. if @username
  843. @@connected_clients.delete(self)
  844. if @ping_timer
  845. EventMachine.cancel_timer(@ping_timer)
  846. end
  847. put_log "SYS '#{@username}' disconnected."
  848. write_role($default_role, "SYS User '#{@username}' disconnected.", @username)
  849. end
  850. put_log "SYS Online users now: #{ousers.join(", ")}"
  851. end
  852. end
  853. def main
  854. # #run: Note that this will block current thread.
  855. $gs = GameServers.new
  856. EventMachine.run do
  857. # initial scan
  858. EM.defer do
  859. $gs.scanserverlist($qw_list, "qw") # initial scan
  860. end
  861. # periodic scan, 20 hours
  862. EventMachine.add_periodic_timer( 60 * 60 * 20 ) {
  863. EM.defer do
  864. $gs.scanserverlist($qw_list, "qw") # initial scan
  865. end
  866. }
  867. EventMachine.start_server("0.0.0.0", 7337, CentralProtocolHandler)
  868. end
  869. end # of main
  870. main