socket_central.rb 9.8 KB

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