CapsAdmin

Untitled

Nov 1st, 2012
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 11.06 KB | None | 0 0
  1. local F = string.format
  2.  
  3. luasocket = {}
  4. luasocket.debug = true
  5.  
  6. luasocket.socket = socket
  7.  
  8. local http = {}
  9.  
  10. function http.HeaderToTable(header)
  11.     local tbl = {}
  12.  
  13.     for key, line in pairs(header:Explode("\n")) do
  14.         if #line ~= 0 then
  15.             local key, value = line:match("(.+):%s+(.+)")
  16.             if key and value then
  17.                 tbl[key] = value
  18.             end
  19.         end
  20.     end
  21.  
  22.     return tbl
  23. end
  24.  
  25. function http.TableToHeader(tbl)
  26.     local str = ""
  27.  
  28.     for key, value in pairs(tbl) do
  29.         str = str .. tostring(key) .. ": " .. tostring(value) .. "\n"
  30.     end
  31.  
  32.     return str
  33. end
  34.  
  35. function http.Get(url, callback, header)
  36.     check(url, "string")
  37.     check(header, "string", "nil")
  38.     check(callback, "function", "nil", "false")
  39.  
  40.     url = url:gsub("http://", "")
  41.     callback = callback or PrintTable
  42.  
  43.     local host, get = url:match("(.-)/(.+)")
  44.  
  45.     if not get then
  46.         host = url:gsub("/", "")
  47.         get = ""
  48.     end
  49.  
  50.     local socket = luasocket.Client("tcp")
  51.     socket:Connect(host, 80)
  52.    
  53.     socket:Send(F("GET /%s HTTP/1.1\r\n", get))
  54.     socket:Send(F("Host: %s\r\n", host))
  55.     socket:Send("User-Agent: oohh\r\n")
  56.     socket:Send("\r\n")
  57.     socket:SetMaxTimeouts(5000)
  58.        
  59.     local header = ""
  60.     local content = ""
  61.     local status
  62.     local isheader = true
  63.        
  64.     function socket:OnReceive(line)    
  65.         if not status then
  66.             status = line
  67.         end
  68.  
  69.         if isheader then
  70.             if #line == 0 then
  71.                 isheader = false
  72.             else
  73.                 header = header  .. line .. "\n"
  74.             end
  75.         else
  76.             content = content .. line .. "\n"
  77.         end
  78.     end
  79.    
  80.     function socket:OnClose()
  81.         local ok, err = pcall(callback, {content = content, header = http.HeaderToTable(header), status = status})
  82.         if err then
  83.             print(err)
  84.         end
  85.     end
  86. end
  87.  
  88. luasocket.http = http
  89.  
  90. do -- tcp socket meta
  91.     local sockets = {}
  92.  
  93.     hook.Add("LuaClose", "socket_close", function()
  94.         for key, sock in pairs(sockets) do
  95.             if sock:IsValid() then
  96.                 sock:Remove()
  97.             else
  98.                 table.remove(sockets, key)
  99.             end
  100.         end
  101.     end)
  102.  
  103.     timer.Create("socket_think", 0, 0, function()
  104.         for key, sock in pairs(sockets) do
  105.             if sock:IsValid() then
  106.                 local res, err = pcall(sock.Think, sock)
  107.                 if err then
  108.                     print(err)
  109.                 end
  110.             else
  111.                 table.remove(sockets, key)
  112.             end
  113.         end
  114.     end)
  115.  
  116.     local function assert(res, err)
  117.         if not res then
  118.             error(res, 3)
  119.         end
  120.         return res
  121.     end
  122.  
  123.     local function new_socket(override, META, typ)
  124.         typ = typ or "tcp"
  125.         typ = typ:lower()
  126.  
  127.         if typ == "udp" or typ == "tcp" then
  128.             local self = {}
  129.  
  130.             self.socket = override or assert(luasocket.socket[typ]())
  131.             self.socket:settimeout(0)
  132.             self.socket_type = typ
  133.  
  134.             local obj = setmetatable(self, META)
  135.             obj:Initialize()
  136.             table.insert(sockets, obj)
  137.  
  138.             return obj
  139.         end
  140.     end
  141.  
  142.     local function remove_socket(self)
  143.         self.socket:close()
  144.         for key, sock in pairs(sockets) do
  145.             if sock == self then
  146.                 table.remove(sockets, key)
  147.                 break
  148.             end
  149.         end
  150.         timer.Simple(0.1, function() MakeNULL(self) end)
  151.     end
  152.  
  153.     do -- client
  154.         local CLIENT = {}
  155.         CLIENT.__index = CLIENT
  156.  
  157.         function CLIENT:Initialize()
  158.             self.Buffer = {}
  159.         end
  160.  
  161.         function CLIENT:__tostring()
  162.             return string.format("client_%s[%s][%s]", self.socket_type, self:GetIP() or "none", self:GetPort() or "0")
  163.         end
  164.  
  165.         function CLIENT:DebugPrintf(fmt, a,b,c,d,e,f,g)
  166.             a = tostring(a)
  167.             b = tostring(b)
  168.             c = tostring(c)
  169.             d = tostring(d)
  170.             e = tostring(e)
  171.             f = tostring(f)
  172.             g = tostring(g)
  173.             if luasocket.debug then
  174.                 print(string.format("%s - " .. fmt, tostring(self), a,b,c,d,e,f,g))
  175.             end
  176.         end
  177.  
  178.         function CLIENT:Connect(ip, port)
  179.             check(ip, "string")
  180.             check(port, "number")
  181.  
  182.             self.socket:settimeout(0)
  183.             if self.socket_type == "tcp" then
  184.                 self.socket:connect(ip, port)
  185.             else
  186.                 self.socket:setpeername(ip, port)
  187.             end
  188.             self.socket:settimeout(0)
  189.  
  190.             self.connecting = true
  191.         end
  192.  
  193.         function CLIENT:Send(str, instant)
  194.             if self.socket_type == "tcp" then
  195.                 if instant then
  196.                     local bytes,b,c,d = self.socket:send(str)
  197.  
  198.                     if bytes then
  199.                         if self.OnSend then
  200.                             self:OnSend(data, bytes, b,c,d)
  201.                         end
  202.                         self:DebugPrintf("sucessfully sent %q", data)
  203.                     end
  204.                 else
  205.                     table.insert(self.Buffer, str)
  206.                 end
  207.             else
  208.                 self.socket:send(str)
  209.             end
  210.         end
  211.  
  212.         function CLIENT:Think()
  213.             local sock = self.socket
  214.             sock:settimeout(0)
  215.  
  216.             if self.connecting then
  217.                 local res, err = sock:getpeername()
  218.                 if res then
  219.                     -- ip, port = res, err
  220.  
  221.                     self.connected = true
  222.                     self.connecting = nil
  223.                     if self.OnConnect then
  224.                         self:OnConnect(res, err)
  225.                     end
  226.  
  227.                     self:DebugPrintf("connected to %s:%s", res, err)
  228.  
  229.                     self.Timeouts = 0
  230.                 elseif err == "timeout" or err == "getpeername failed" then
  231.                     self:Timeout()
  232.                 else
  233.                     if self.OnError then
  234.                         self:DebugPrintf("errored: %s", err)
  235.                         self:OnError(err)
  236.                     end
  237.                     self.connecting = nil
  238.                     self:DebugPrintf("errored: %s", err)
  239.                 end
  240.             end
  241.  
  242.             if self.socket_type == "tcp" and self.connected then
  243.                 while true do
  244.                     local data = self.Buffer[1]
  245.                     if data then
  246.                         local bytes,b,c,d = sock:send(data)
  247.  
  248.                         if bytes then
  249.                             if self.OnSend then
  250.                                 self:OnSend(data, bytes, b,c,d)
  251.                             end
  252.                             self:DebugPrintf("sucessfully sent %q", data)
  253.                             table.remove(self.Buffer, 1)
  254.                         end
  255.                     else
  256.                         break
  257.                     end
  258.                 end
  259.  
  260.                 local data, err, partial = sock:receive("*l")
  261.                 if not data and partial ~= "" then
  262.                     data = partial
  263.                 end
  264.  
  265.                 self:DebugPrintf("receive: %s, %s, %s, %i", data or "", err or "", partial or "", self.Timeouts)
  266.                
  267.                 if data then
  268.                     if self.OnReceive then
  269.                         self:OnReceive(data)
  270.                     end
  271.                     self:DebugPrintf("received %q", data)
  272.                     self.Timeouts = 0
  273.                 elseif err == "timeout" then
  274.                     self:Timeout()
  275.                 elseif err == "Socket is not connected" then
  276.                     --self.connected = false
  277.                     --self.connecting = true
  278.                 elseif err == "closed" then
  279.                     self:DebugPrintf("wants to close", client)
  280.                     if self.OnClose then
  281.                         self:OnClose()
  282.                     end
  283.                     self:Remove()
  284.                 elseif self.OnError then
  285.                     self:OnError(err)
  286.                     self:DebugPrintf("errored: %s", err)
  287.                 end
  288.             end
  289.         end
  290.  
  291.         CLIENT.MaxTimeouts = 100
  292.         CLIENT.Timeouts = 0
  293.  
  294.         function CLIENT:Timeout()
  295.             if not self.OnTimeout or self:OnTimeout(self.Timeouts) ~= false then
  296.                 self.Timeouts = self.Timeouts + 1
  297.                 if self.Timeouts > self.MaxTimeouts then
  298.                     if self.OnClose then
  299.                         self:OnClose()
  300.                     end
  301.                    
  302.                     self:Remove()
  303.                 end
  304.             end
  305.         end
  306.  
  307.         function CLIENT:SetMaxTimeouts(num)
  308.             self.MaxTimeouts = num
  309.         end
  310.  
  311.         function CLIENT:Remove()
  312.             remove_socket(self)
  313.         end
  314.  
  315.         function CLIENT:OnClose()
  316.             self:Remove()
  317.         end
  318.  
  319.         function CLIENT:IsConnected()
  320.             return self.connected == true
  321.         end
  322.  
  323.         function CLIENT:IsSending()
  324.             return #self.Buffer > 0
  325.         end
  326.  
  327.         function CLIENT:GetIP()
  328.             local ip, port = self.socket:getpeername()
  329.             return ip
  330.         end
  331.  
  332.         function CLIENT:GetPort()
  333.             local ip, port = self.socket:getpeername()
  334.             return ip and port or nil
  335.         end
  336.  
  337.         function CLIENT:IsValid()
  338.             return true
  339.         end
  340.  
  341.         function luasocket.Client(typ)
  342.             return new_socket(nil, CLIENT, typ)
  343.         end
  344.  
  345.         luasocket.ClientMeta = CLIENT
  346.     end
  347.  
  348.     do -- server
  349.         local SERVER = {}
  350.         SERVER.__index = SERVER
  351.  
  352.         function SERVER:Initialize()
  353.             self.Clients = {}
  354.         end
  355.  
  356.         function SERVER:__tostring()
  357.             return string.format("server_%s[%s][%s]", self.socket_type, self:GetIP() or "nil", self:GetPort() or "nil")
  358.         end
  359.  
  360.         function SERVER:DebugPrintf(fmt, ...)
  361.             if luasocket.debug then
  362.                 printf("%s - " .. fmt, self, ...)
  363.             end
  364.         end
  365.  
  366.         function SERVER:GetClients()
  367.             local copy = {}
  368.             for key, client in pairs(self.Clients) do
  369.                 if client.IsValid and client:IsValid() then
  370.                     table.insert(copy, client)
  371.                 else
  372.                     table.remove(self.Clients, key)
  373.                 end
  374.             end
  375.             return copy
  376.         end
  377.  
  378.         function SERVER:Host(ip, port)
  379.             ip = ip or "*"
  380.             port = port or 0
  381.  
  382.             if self.socket_type == "tcp" then
  383.                 self.socket:settimeout(0)
  384.                 self.socket:setoption("reuseaddr", true)
  385.                 self.socket:bind(ip, port)
  386.                 self.socket:listen()
  387.                 self.socket:settimeout(0)
  388.                 self.ready = true
  389.             elseif self.socket_type == "udp" then
  390.                 self.socket:settimeout(0)
  391.                 self.socket:setsockname(ip, port)
  392.                 self.socket:settimeout(0)
  393.                 self.ready = true
  394.             end
  395.         end
  396.  
  397.         function SERVER:Send(data, ip, port)
  398.             check(ip, "string")
  399.  
  400.             if self.socket_type == "tcp" then
  401.                 for key, client in pairs(self:GetClients()) do
  402.                     if client:GetIP() == ip and (not port or (port == client:GetPort())) then
  403.                         client:Send(data)
  404.                         break
  405.                     end
  406.                 end
  407.             elseif self.socket_type == "udp" then
  408.                 check(port, "number")
  409.                 self.socket:sendto(data, ip, port)
  410.             end
  411.         end
  412.  
  413.         SERVER.Bind = SERVER.Host
  414.  
  415.         function SERVER:Think()
  416.             if not self.ready then return end
  417.  
  418.             if self.socket_type == "udp" then
  419.                 local data, ip, port = self.socket:receivefrom()
  420.  
  421.                 if data then
  422.                     if self.OnReceive then
  423.                         self:OnReceive(data, ip, port)
  424.                     end
  425.  
  426.                     self:DebugPrintf("received %s from %s:%s", data, ip, port)
  427.                 elseif ip ~= "timeout" then
  428.                     self:DebugPrintf("%s errored: ", client, err)
  429.                 end
  430.             elseif self.socket_type == "tcp" then
  431.                 local sock = self.socket
  432.                 sock:settimeout(0)
  433.  
  434.                 local ls_client, err = sock:accept()
  435.  
  436.                 if ls_client then
  437.                     local client = new_socket(ls_client, luasocket.ClientMeta, "tcp")
  438.                     client.connected = true
  439.                     table.insert(self.Clients, client)
  440.  
  441.                     if self.OnClientConnected then
  442.                         if self:OnClientConnected(client, client:GetIP(), client:GetPort()) == false then
  443.                             client:Remove()
  444.                         end
  445.                     end
  446.                     self:DebugPrintf("%s connected", client)
  447.                 end
  448.  
  449.                 for _, client in pairs(self:GetClients()) do
  450.                     local data, err, partial = client.socket:receive()
  451.                     if data then
  452.  
  453.                         if self.OnReceive then
  454.                             self:OnReceive(data, client)
  455.                         end
  456.  
  457.                         if client.OnSend then
  458.                             client:OnSend(data)
  459.                         end
  460.  
  461.                         self:DebugPrintf("received %s from %s", data, client)
  462.  
  463.                     elseif err == "closed" then
  464.                         self:DebugPrintf("%s wants to close", client)
  465.                         if not self.OnClientClose or self:OnClientClose(client) ~= false then
  466.                             if client.OnClose then
  467.                                 client:OnClose()
  468.                             end
  469.                            
  470.                             client:Remove()
  471.                         end
  472.                     elseif err == "timeout" then
  473.                         --client:Timeout() -- hmm
  474.                     else
  475.                         if self.OnClientError then
  476.                             self:OnClientError(client, err)
  477.                         end
  478.                         if client.OnError then
  479.                             client:DebugPrintf("errored: %s", err)
  480.                             client:OnError(err)
  481.                         end
  482.                         self:DebugPrintf("%s errored: ", client, err)
  483.                     end
  484.                 end
  485.             end
  486.         end
  487.  
  488.         function SERVER:Remove()
  489.             remove_socket(self)
  490.         end
  491.  
  492.         function SERVER:IsValid()
  493.             return true
  494.         end
  495.  
  496.         function SERVER:GetIP()
  497.             local ip, port = self.socket:getsockname()
  498.             return ip
  499.         end
  500.  
  501.         function SERVER:GetPort()
  502.             local ip, port = self.socket:getsockname()
  503.             return ip and port or nil
  504.         end
  505.  
  506.         function luasocket.Server(typ)
  507.             return new_socket(nil, SERVER, typ)
  508.         end
  509.  
  510.         luasocket.ServerMeta = SERVER
  511.     end
  512. end
Advertisement
Add Comment
Please, Sign In to add comment