em_server.rb 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. #!/usr/bin/env ruby
  2. require 'eventmachine'
  3. require 'digest/md5'
  4. require 'fiber'
  5. # .. allowed commands .. ROLES = CAPABILITIES
  6. # normal users have ROLE broadcast. Roles are defined on a per-user basis .. in a config.
  7. $version = "0.2EventMachineSocketServer"
  8. $debug = 0
  9. $role_commands = Hash[
  10. "everyone" => ["PING", "WHO", "C", "PART"],
  11. "broadcast_admin" => ["BC_ID", "BC", "BC_ENDCOUNT"],
  12. "broadcast" => ["REQ_BC", "BC_RE"],
  13. "specbot_admin" => ["REQ_ASSIGN", "REQ_UNASSIGN", "REQ_PING", "REQ_ASSIGNMENTS"],
  14. "specbot" => ["ASSIGN_RE", "UNASSIGN_RE", "PING_RE", "ASSIGNMENTS_RE"],
  15. ]
  16. $default_role = "everyone"
  17. # which role is talking to which role?
  18. # effectively it says: this (local) command is sent to that (remote) topic .. that certain topic is read by that user with that role.
  19. $role_dialogs = Hash[
  20. "everyone" => ["everyone"],
  21. "broadcast_admin" => ["broadcast"],
  22. "broadcast" => ["broadcast_admin"],
  23. "specbot_admin" => ["specbot"],
  24. "specbot" => ["specbot_admin"],
  25. ]
  26. $user_roles = Hash[
  27. "paul_dev_eggdrop" => ["everyone", "broadcast"],
  28. "paul_eggdrop" => ["everyone", "broadcast"],
  29. "paul_dev_specbot" => ["everyone", "broadcast", "specbot"],
  30. "paul_specbot" => ["everyone", "broadcast", "specbot"],
  31. "qw.nu" => ["everyone", "broadcast"],
  32. "qw.nu_poster" => ["everyone", "broadcast"],
  33. "mihawk_dev_specbot" => ["everyone", "broadcast", "specbot"],
  34. "mihawk_specbot" => ["everyone", "broadcast", "specbot"],
  35. "central_brain" => ["everyone", "broadcast_admin", "specbot_admin"],
  36. ]
  37. module InterconnectionPointProtocolHandler
  38. @@connected_clients = Array.new
  39. @@broadcasts = Hash.new
  40. # default method that is being run on connection!
  41. def post_init # connection of someone starts here...
  42. @username = nil
  43. end
  44. ### getters
  45. def entered_username?
  46. !@username.nil? && !@username.empty? # then it's true
  47. end
  48. def username
  49. @username
  50. end
  51. def my_roles
  52. return $user_roles[@username]
  53. end
  54. def my_cmds
  55. return my_roles.collect {|v| $role_commands[v]}.flatten
  56. end
  57. # returns online users by default by searching through saved connections
  58. def ousers
  59. users = Array.new
  60. @@connected_clients.each {|c| users.push(c.username)}
  61. return users
  62. end # of ousers
  63. ### checkers
  64. def allowed_cmd(inputmessage)
  65. my_cmds.each{|c|
  66. #print "A #{c} B #{inputmessage}\n"
  67. if inputmessage =~ /^#{c}/
  68. return true
  69. end
  70. }
  71. return false
  72. end
  73. def online(user)
  74. if ousers.include? user
  75. return true
  76. else
  77. return false
  78. end
  79. end
  80. ### actions
  81. def put_log(msg)
  82. puts "#{Time.now.utc.strftime("%Y-%m-%d %H:%M:%S")}: #{msg}"
  83. end
  84. # searches through our hash of saved connections and writes them a messages.
  85. def write_user(input, username = nil)
  86. if not username
  87. username = @username
  88. end
  89. if connection = @@connected_clients.find { |c| c.username == username }
  90. sometime = "#{Time.now.utc.strftime("%Y-%m-%d %H:%M:%S %z")}"
  91. line = "#{sometime}: #{input}\n"
  92. connection.send_data line
  93. end
  94. end # of write_user
  95. # searches through roles and writes those users on their connections
  96. def write_role(role, input, *exempts)
  97. #find users with role
  98. users = Array.new
  99. $user_roles.each {|k, v|
  100. if v.include? role
  101. users.push(k)
  102. end
  103. }
  104. # find users that are online and inside Array "users"
  105. lala = Array.new
  106. users.each {|v|
  107. if ousers.include? v
  108. lala.push(v)
  109. end
  110. }
  111. # now write to them
  112. lala.each {|user|
  113. if not exempts.include? user
  114. write_user(input, user)
  115. end
  116. }
  117. end # of write_role()
  118. # what happens with what input?!
  119. def inputting(input)
  120. write_user("SYS You typed: #{input}")
  121. if input =~ /^([A-Z_]+)/
  122. cmd = $1
  123. end
  124. # now we have the cmd .. or not ;)
  125. if input =~ /^[A-Z_]+ (.+)/
  126. payload = $1
  127. end
  128. # now we can use payload
  129. if allowed_cmd(cmd)
  130. ### typical system commands follow
  131. if cmd == "PING"
  132. write_user("PONG")
  133. elsif cmd == "C"
  134. if payload =~ /^(.+)$/
  135. write_role($default_role, "C #{@username}: #{$1}")
  136. else
  137. write_user("SYS Format is C <chattext>")
  138. end
  139. elsif cmd == "WHO"
  140. ousers.each {|ouser| write_user("WHO_RE #{ouser} ROLES: #{$user_roles[ouser].join(", ")}")}
  141. elsif cmd == "PART"
  142. write_user("SYS Goodbye '#{@username}'.")
  143. write_role($default_role, "PARTED User '#{@username}' just left the party.", @username)
  144. return "bye"
  145. ###now for the good stuff, broadcasting
  146. elsif cmd == "REQ_BC"
  147. # help with format .. but send the raw payload
  148. if payload =~ /^(.+),(.+),(.+),'(.+)','(.+)'$/
  149. # n f s ni txt
  150. error = 0
  151. # $&
  152. # 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
  153. network = $1
  154. freqname = $2
  155. source = $3
  156. nickname = $4
  157. text = $5
  158. if not network =~ /^(QWalt)|(QDEV)/
  159. write_user("SYS Network name #{network} is unknown: QWalt or QDEV allowed.")
  160. error = 1
  161. end
  162. if not freqname =~ /^(-qw-)|(-spam-)|(-dev-)/
  163. write_user("SYS Frequency name is unknown #{freqname}")
  164. error = 1
  165. end
  166. if source =~ /^(#.+)|(qw:\/\/)|(http:\/\/)/
  167. else
  168. write_user("SYS Source string is not in the form ^(#.+)|(qw:\/\/)|(http:\/\/) was: #{source}")
  169. error = 1
  170. end
  171. if not nickname =~ /^.+/
  172. write_user("SYS Nickname string is not in the form ^.+ #{nickname}")
  173. error = 1
  174. end
  175. if not text =~ /^.+/
  176. write_user("SYS Message string is not in the form ^.+ #{text}")
  177. error = 1
  178. end
  179. else # of check syntax
  180. write_user("SYS Command format is REQ_BC <network>,<frequency>,<source/channel>,'<nickname>','<message>'")
  181. error = 1
  182. end
  183. if error == 0
  184. # send REQ_BC to the corresponding role.
  185. bcid = Digest::MD5.hexdigest("%d %s %s %s %s %s" % [Time.now.utc.to_i, network, freqname, source, nickname, text])
  186. # so it only reaches the issuer of REQ_BC
  187. write_user("BC_ID #{bcid} for: #{network},#{freqname},#{source}")
  188. @@broadcasts[bcid] = @username
  189. # qw:// ip resolving
  190. if source =~ /^qw:\/\/(.+):(\d+)(.*)$/
  191. # ip address is 15 in length
  192. iphost = $1
  193. ipport = $2
  194. rest = $3
  195. if iphost =~ /^\d+\.\d+\.\d+\.\d+/
  196. # resolve it to a dns name
  197. f = Fiber.new do
  198. Fiber.yield Resolv.getname(iphost)
  199. end
  200. host_name = f.resume
  201. #host_name = ""
  202. if host_name.nil? || host_name.empty?
  203. host_name = iphost
  204. else
  205. # if the resulting dns is too long, use ip-address instead.
  206. # if the resulting dns has too many dots, use ip-address instead.
  207. if host_name.length > 23 || host_name.split(".").size >= 4
  208. #put_log "cutting down host_name #{host_name} #{host_name.size} #{host_name.split(".").size}"
  209. host_name = iphost
  210. end
  211. end
  212. source = "qw://#{host_name}:#{ipport}#{rest}"
  213. end
  214. end # of if source qw://x.x.x.x:portzzz
  215. # resolve
  216. finalmessage = "BC %s %s,%s,%s,'%s','%s'" % [bcid, network, freqname, source, nickname, text]
  217. write_role("broadcast", finalmessage, @username) # write to the role with the exempt of myself.
  218. end
  219. #end of REQ_BC here..
  220. elsif cmd == "BC_RE"
  221. if payload =~ /^(.+) (.+)=(\d+),(.+)=(\d+)$/
  222. bcid = $1
  223. user_string = $2
  224. user_count = $3
  225. item_string = $4
  226. item_count = $5
  227. payload = "%s %s=%d,%s=%d" % [bcid, user_string, user_count, item_string, item_count]
  228. # according bcid it is possible to get the originating user.. so send only to his topic!
  229. if @@broadcasts[bcid]
  230. to_user = @@broadcasts[bcid]
  231. write_user("SYS Broadcast reply bcid: #{bcid} underway to #{to_user}.")
  232. write_user("#{cmd} #{payload}", to_user)
  233. else
  234. write_user("SYS Broadcast reply bcid: #{bcid} underway.")
  235. write_role("broadcast", "#{cmd} #{payload}", @username)
  236. end
  237. else # of bc_re format check
  238. put_log "SYS Format is BC_RE <bcid> <userstring>=<usercount>,<itemstring>=<itemcount>"
  239. end
  240. end
  241. else # of if allowed command
  242. write_user("SYS Command #{input} not allowed, your commands are: #{my_cmds.join(", ")}.")
  243. end # of if allowed command
  244. end # of inputting!
  245. # default method that is being run on receiving data!
  246. def receive_data(data) # connection receives a line on the server end
  247. line = data.chomp unless data.chomp.nil?
  248. if line
  249. if entered_username? # oh, it's a known user
  250. # it's alive!
  251. inputter = inputting(line)
  252. if inputter == "bye"
  253. close_connection
  254. end
  255. else # of username known, then it seems to be the first connect
  256. # and this line is the user name coming in!
  257. username = line
  258. if online(username)
  259. put_log "SYS User '#{username}' tried to double connect. Say bye bye."
  260. send_data "SYS Hey '#{username}', only one connection allowed. Bye.\n"
  261. EventMachine.add_timer 1, proc { close_connection }
  262. return false
  263. end
  264. if $user_roles.any? {|k| k.include? username}
  265. @username = username
  266. @@connected_clients.push(self)
  267. put_log("SYS '#{@username}' connected. Online now: #{ousers.join(", ")}")
  268. write_user("HELLO Hi user '#{@username}'! How are you? I'm '#{$version}'")
  269. write_user("ROLES #{my_roles.join(", ")}")
  270. write_user("COMMANDS #{my_cmds.join(", ")}")
  271. write_role($default_role, "JOINED User '#{@username}' just joined the party.", @username)
  272. else
  273. put_log "SYS User '#{username}' unknown to me. Saying bye."
  274. send_data "SYS User '#{username}' unknown to me. Bye.\n"
  275. # disconnect him
  276. close_connection
  277. end
  278. end # of username known
  279. end # of line
  280. end
  281. # default method that is being run on disconnection!
  282. def unbind # a connection goes bye bye
  283. if @username
  284. @@connected_clients.delete(self)
  285. put_log "SYS '#{@username}' disconnected. Online now: #{ousers.join(", ")}"
  286. end
  287. end
  288. end
  289. def main
  290. # #run: Note that this will block current thread.
  291. EventMachine.run do
  292. EventMachine.start_server("0.0.0.0", 7337, InterconnectionPointProtocolHandler)
  293. end
  294. end
  295. main