socket_central.rb 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. #!/usr/bin/ruby
  2. # vim: expandtab tabstop=2 shiftwidth=2 softtabstop=2 autoindent:
  3. require 'rubygems'
  4. require 'socket'
  5. require 'digest/md5'
  6. require 'timeout'
  7. # .. allowed commands .. ROLES = CAPABILITIES
  8. # normal users have ROLE broadcast. Roles are defined on a per-user basis .. in a config.
  9. $version = "0.15TCPServer"
  10. $debug = 0
  11. $role_commands = Hash[
  12. "everyone" => ["PING", "WHO", "C", "PART"],
  13. "broadcast_admin" => ["BC_ID", "BC", "BC_ENDCOUNT"],
  14. "broadcast" => ["REQ_BC", "BC_RE"],
  15. "specbot_admin" => ["REQ_ASSIGN", "REQ_UNASSIGN", "REQ_PING", "REQ_ASSIGNMENTS"],
  16. "specbot" => ["ASSIGN_RE", "UNASSIGN_RE", "PING_RE", "ASSIGNMENTS_RE"],
  17. ]
  18. $default_role = "everyone"
  19. # which role is talking to which role?
  20. # effectively it says: this (local) command is sent to that (remote) topic .. that certain topic is read by that user with that role.
  21. $role_dialogs = Hash[
  22. "everyone" => ["everyone"],
  23. "broadcast_admin" => ["broadcast"],
  24. "broadcast" => ["broadcast_admin"],
  25. "specbot_admin" => ["specbot"],
  26. "specbot" => ["specbot_admin"],
  27. ]
  28. $user_roles = Hash[
  29. "paul_dev_eggdrop" => ["everyone", "broadcast"],
  30. "paul_eggdrop" => ["everyone", "broadcast"],
  31. "paul_dev_specbot" => ["everyone", "broadcast", "specbot"],
  32. "paul_specbot" => ["everyone", "broadcast", "specbot"],
  33. "qw.nu" => ["everyone", "broadcast"],
  34. "qw.nu_poster" => ["everyone", "broadcast"],
  35. "mihawk_dev_specbot" => ["everyone", "broadcast", "specbot"],
  36. "mihawk_specbot" => ["everyone", "broadcast", "specbot"],
  37. "central_brain" => ["everyone", "broadcast_admin", "specbot_admin"],
  38. ]
  39. STDOUT.sync = true
  40. # display loop ... it is displaying the display_queue
  41. def displaying(client, user)
  42. #client.puts "#{user} connected."
  43. begin
  44. loop do
  45. while line = $display_queue[user][0]
  46. client.puts line
  47. $display_queue[user].delete_at(0)
  48. end
  49. sleep 0.1
  50. end
  51. rescue Exception => e
  52. puts e.message
  53. puts e.backtrace.inspect
  54. end
  55. end
  56. def write_user(user, input)
  57. if online_users.user(user)
  58. sometime = "#{Time.now.utc.strftime("%Y-%m-%d %H:%M:%S %z")}"
  59. line = "#{sometime}: #{input}"
  60. $display_queue[user].push(line)
  61. end
  62. end
  63. def kill_conn(c, user, t_display)
  64. sleep 0.5
  65. # delete the key out off $display_queue
  66. $display_queue.delete(user)
  67. # shut down displaying thread and connection
  68. t_display.exit
  69. # shut down connection
  70. c.close
  71. end
  72. def online_users
  73. def user(user)
  74. if online_users.include? user
  75. return true
  76. else
  77. return false
  78. end
  79. end
  80. ousers = Array.new
  81. $display_queue.each_key {|k| ousers.push(k)}
  82. return ousers
  83. end
  84. def write_role(role, input, *exempts)
  85. #find users with role
  86. users = Array.new
  87. $user_roles.each {|k, v|
  88. if v.include? role
  89. users.push(k)
  90. end
  91. }
  92. # find users that are online and inside Array "users"
  93. lala = Array.new
  94. users.each {|v|
  95. if $display_queue.has_key? v
  96. lala.push(v)
  97. end
  98. }
  99. # now write to them
  100. lala.each {|user|
  101. if not exempts.include? user then
  102. write_user(user, input)
  103. end
  104. }
  105. end
  106. def allowed_cmd(user, inputmessage)
  107. my_cmds(user).each{|c|
  108. #print "A #{c} B #{inputmessage}\n"
  109. if inputmessage =~ /^#{c}/
  110. return true
  111. end
  112. }
  113. return false
  114. end
  115. # what happens with what input?!
  116. def inputting(user, input)
  117. write_user(user, "SYS You typed: #{input}")
  118. if input =~ /^([A-Z_]+)/
  119. cmd = $1
  120. end
  121. # now we have the cmd .. or not ;)
  122. if input =~ /^[A-Z_]+ (.+)/
  123. payload = $1
  124. end
  125. # now we can use payload
  126. if allowed_cmd(user, cmd)
  127. ### typical system commands follow
  128. if cmd == "PING"
  129. write_user(user, "PONG")
  130. elsif cmd == "C"
  131. if payload =~ /^(.+)$/
  132. write_role($default_role, "C #{user}: #{$1}")
  133. else
  134. write_user(user, "SYS Format is C <chattext>")
  135. end
  136. elsif cmd == "WHO"
  137. write_user(user, "WHO_RE #{online_users.join(", ")}")
  138. elsif cmd == "PART"
  139. write_user(user, "SYS Goodbye '#{user}'.")
  140. write_role($default_role, "PARTED User '#{user}' just left the party.", user)
  141. return false
  142. ###now for the good stuff, broadcasting
  143. elsif cmd == "REQ_BC"
  144. # help with format .. but send the raw payload
  145. if payload =~ /^(.+),(.+),(.+),'(.+)','(.+)'$/
  146. # n f s ni txt
  147. error = 0
  148. # $&
  149. # 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
  150. network = $1
  151. freqname = $2
  152. source = $3
  153. nickname = $4
  154. text = $5
  155. if not network =~ /^(QWalt)|(QDEV)/
  156. write_user(user, "SYS Network name #{network} is unknown: QWalt or QDEV allowed.")
  157. error = 1
  158. end
  159. if not freqname =~ /^(-qw-)|(-spam-)|(-dev-)/
  160. write_user(user, "SYS Frequency name is unknown #{freqname}")
  161. error = 1
  162. end
  163. if not source =~ /^(#.+)|(qw:\/\/)|(http:\/\/)/
  164. write_user(user, "SYS Source string is not in the form ^(#.+)|(qw:\/\/)|(http:\/\/) was: #{source}")
  165. error = 1
  166. end
  167. if not nickname =~ /^.+/
  168. write_user(user, "SYS Nickname string is not in the form ^.+ #{nickname}")
  169. error = 1
  170. end
  171. if not text =~ /^.+/
  172. write_user(user, "SYS Message string is not in the form ^.+ #{text}")
  173. error = 1
  174. end
  175. else # of check syntax
  176. write_user(user, "SYS Command format is REQ_BC <network>,<frequency>,<source/channel>,'<nickname>','<message>'")
  177. error = 1
  178. end
  179. if error == 0
  180. # send REQ_BC to the corresponding role.
  181. bcid = Digest::MD5.hexdigest("%d %s %s %s %s %s" % [Time.now.utc.to_i, network, freqname, source, nickname, text])
  182. # so it only reaches the issuer of REQ_BC
  183. write_user(user, "BC_ID #{bcid} for: #{network},#{freqname},#{source}")
  184. $broadcasts[bcid] = user
  185. finalmessage = "BC %s %s,%s,%s,'%s','%s'" % [bcid, network, freqname, source, nickname, text]
  186. write_role("broadcast", finalmessage, user) # write to the role with the exempt of myself.
  187. end
  188. #end of REQ_BC here..
  189. elsif cmd == "BC_RE"
  190. if payload =~ /^(.+) (.+)=(\d+),(.+)=(\d+)$/
  191. bcid = $1
  192. user_string = $2
  193. user_count = $3
  194. item_string = $4
  195. item_count = $5
  196. payload = "%s %s=%d,%s=%d" % [bcid, user_string, user_count, item_string, item_count]
  197. # according bcid it is possible to get the originating user.. so send only to his topic!
  198. if $broadcasts[bcid]
  199. to_user = $broadcasts[bcid]
  200. write_user(user, "SYS Broadcast reply bcid: #{bcid} underway to #{to_user}.")
  201. write_user(to_user, "#{cmd} #{payload}")
  202. else
  203. write_user(user, "SYS Broadcast reply bcid: #{bcid} underway.")
  204. write_role("broadcast", "#{cmd} #{payload}", user)
  205. end
  206. else # of bc_re format check
  207. put_log "SYS Format is BC_RE <bcid> <userstring>=<usercount>,<itemstring>=<itemcount>"
  208. end
  209. end
  210. else # of if allowed command
  211. write_user(user, "SYS Command #{input} not allowed, your commands are: #{my_cmds(user).join(", ")}.")
  212. end # of if allowed command
  213. end
  214. def my_roles(user)
  215. return $user_roles[user]
  216. end
  217. def my_cmds(user)
  218. myroles = my_roles(user)
  219. mycmds = myroles.collect {|v| $role_commands[v]}.flatten
  220. return mycmds
  221. end
  222. def thinking(c, user, t_display)
  223. put_log "#{user} connected. Online now: #{online_users.join(", ")}"
  224. if not $user_roles.any? {|k, v| k.include? user}
  225. put_log "SYS User '#{user}' unknown to me. Saying bye."
  226. write_user(user, "SYS User '#{user}' unknown to me. Bye.")
  227. return false
  228. end
  229. write_user(user, "HELLO Hi user '#{user}'! How are you? I'm '#{$version}'")
  230. write_user(user, "ROLES #{my_roles(user).join(", ")}")
  231. write_user(user, "COMMANDS #{my_cmds(user).join(", ")}")
  232. write_role($default_role, "JOINED User '#{user}' just joined the party.", user)
  233. # reading the client input ... to write it somewhere, possibly to the client himself.
  234. begin
  235. input = nil
  236. while input != "PART" do
  237. begin
  238. status = Timeout::timeout(90) do
  239. input = c.gets.chomp # waits for user input
  240. execution = inputting(user, input)
  241. end
  242. rescue Exception => e
  243. write_user(user, "PING Still alive?") # if writing fails, then it may be a broken pipe .. so it will lose the connection and delete the user from the online user list.
  244. end
  245. end
  246. rescue Exception => e
  247. puts e.message
  248. puts e.backtrace.inspect
  249. put_log "#{user} lost connection."
  250. end
  251. end
  252. def pingtimer(c, user)
  253. end
  254. def spawn_server
  255. $display_queue = Hash.new
  256. $broadcasts = Hash.new
  257. server = TCPServer.new 7337
  258. Thread.abort_on_exception = true
  259. loop do
  260. Thread.start(server.accept) do |c|
  261. user = c.gets.chomp # waits for user name input
  262. # only one connection from a user allowed - we don't handle multiple display_queues for one user!!!!!11111
  263. if online_users.user(user)
  264. user = c.puts "Only one connection allowed per user."
  265. c.close
  266. else
  267. $display_queue[user] = Array.new
  268. #p $display_queue # ok we can take $display_queue to check for online users.
  269. # this thread reads what others want you to read ..
  270. t_user_display = Thread.new{ displaying(c, user) }
  271. begin
  272. execution = thinking(c, user, t_user_display)
  273. if not execution
  274. # shut down displaying thread and connection
  275. kill_conn(c, user, t_user_display)
  276. end
  277. rescue Exception => e
  278. puts e.message
  279. puts e.backtrace.inspect
  280. kill_conn(c, user, t_user_display)
  281. end # of rescue
  282. put_log "Online now: #{online_users.join(", ")}"
  283. end
  284. end
  285. end
  286. end
  287. def put_debug(msg)
  288. if $debug == 1
  289. puts msg
  290. end
  291. end
  292. def put_log(msg)
  293. puts "#{Time.now.strftime("%Y-%m-%d %H:%M:%S %z")}: #{msg}"
  294. end
  295. spawn_server