Ruby FTP server "halts" - ruby

I am trying to implement the FTP protocol in Ruby. The problem is that when the user enters the bye command my program doesn't respond (the other commands work fine). Here is some of my code (the socket parts are omitted). Can anyone tell me what is going wrong? (I know that when bye is entered the standard windows FTP program sends "QUIT".)
user_on = true
while user_on
cmd = client.recv(2000)
# THIS IS WHERE IT FREEZES
if cmd.contains? 'QUIT'
client.puts("221 Goodbye.")
client.close
user_on = false
else
puts("500 UNRECOGNIZED COMMAND")
cmd = client.recv(2000)
end
end

Related

Ruby TCPServer fails to work sometimes

I've implemented a very simple kind of server in Ruby, using TCPServer. I have a Server class with serve method:
def serve
# Do the actual serving in a child process
#pid = fork do
# Trap signal sent by #stop or by pressing ^C
Signal.trap('INT') { exit }
# Create a new server on port 2835 (1 ounce = 28.35 grams)
server = TCPServer.new('localhost', 2835)
#logger.info 'Listening on http://localhost:2835...'
loop do
socket = server.accept
request_line = socket.gets
#logger.info "* #{request_line}"
socket.print "message"
socket.close
end
end
end
and a stop method:
def stop
#logger.info 'Shutting down'
Process.kill('INT', #pid)
Process.wait
#pid = nil
end
I run my server from the command line, using:
if __FILE__ == $0
server = Server.new
server.logger = Logger.new(STDOUT)
server.logger.formatter = proc { |severity, datetime, progname, msg| "#{msg}\n" }
begin
server.serve
Process.wait
rescue Interrupt
server.stop
end
end
The problem is that, sometimes, when I do ruby server.rb from my terminal, the server starts, but when I try to make a request on localhost:2835, it fails. Only after several requests it starts serving some pages. In other cases, I need to stop/start the server again for it to properly serve pages. Why is this happening? Am I doing something wrong? I find this very weird...
The same things applies to my specs: I have some specs defined, and some Capybara specs. Before each test I create a server and start it and after each test I stop the server. And the problem persists: tests sometimes pass, sometimes fail because the requested page could not be found.
Is there something fishy going on with my forking?
Would appreciate any answer because I have no more place to look...
Your code is not an HTTP server. It is a TCP server that sends the string "message" over the socket after receiving a newline.
The reason that your code isn't a valid HTTP server is that it doesn't conform to the HTTP protocol. One of the many requirements of the HTTP protocol is that the server respond with a message of the form
HTTP/1.1 <code> <reason>
Where <code> is a number and <reason> is a human-readable "status", like "OK" or "Server Error" or something along those lines. The string message obviously does not conform to this requirement.
Here is a simple introduction to how you might build a HTTP server in ruby: https://practicingruby.com/articles/implementing-an-http-file-server

TCP Minecraft Server in Ruby

I'm attempting to create a script in ruby that connects to a Minecraft server via TCP and fetches the current number of players much like the PHP script at http://www.webmaster-source.com/2012/07/05/checking-the-status-of-a-minecraft-server-with-php/
When running the code below I get �Took too long to log in
require 'socket'
server = TCPSocket.new '192.241.174.210', 25565
while line = server.gets
puts line
end
server.close
What am I doing wrong here?
you're not sending this:
fwrite($sock, "\xfe");
from the script you linked. You have to send that before you call read, like they do.
Basically the server is waiting for you to send data and when you don't after a timeout, you are disconnected.

Something is puzzling me about the use of ftp.nlst on a windows ftp server

So I was reading the documentation for the method nlst in the NET::FTP module (ruby-1.8.6). The source code displayed is
# File net/ftp.rb, line 602
def nlst(dir = nil)
cmd = "NLST"
if dir
cmd = cmd + " " + dir
end
files = []
retrlines(cmd) do |line|
files.push(line)
end
return files
end
So the command is written literally in the string cmd, executed via retrlines and the list of files is given back right?
The thing I don't understand is that on my windows ftp server there is no such command:
230 User logged in.
Remote system type is Windows_NT.
ftp> nlst
?Invalid command
ftp>
and yet the the method returns the file list. How is it possible? The source code doesn't appear to have an abstraction of some sort on the command and also the source code of retrlines doesn't have anything special (to me).
# File lib/net/ftp.rb, line 475
def retrlines(cmd) # :yield: line
synchronize do
with_binary(false) do
conn = transfercmd(cmd)
loop do
line = conn.gets
break if line == nil
yield(line.sub(/\r?\n\z/, ""), !line.match(/\n\z/).nil?)
end
conn.close
voidresp
end
end
end
I traced back the methods called to sendcmd inside transfercmd but I have no clue really.
The question is who is telling you ?Invalid command?
In this case it's the FTP client, not the server.
The client is just a front-end for commands that it implements, converting these front-end commands into proper FTP protocol command strings for the server.
What you're looking for is the nlist (not nlst) command in your client, which will issue the NLST FTP protocol command to the server.
ftp> help nlst
?Invalid help command nlst
ftp> help nlist
nlist nlist contents of remote directory
ftp>

Ruby Telnet Lib - Weird Response

I am trying to execute cmds on a remote CPU through telnet. While some commands sent (through Ruby's stdlib for telnet) are successful, others are giving me a weird response:
*===============================================================
Welcome to Microsoft Telnet Server.
*===============================================================
C:\Documents and Settings\UserJW>ls
Desktop
Favorites
My Documents
Start Menu
Sti_Trace.log
C:\Documents and Settings\UserJW>cd\
More?
Why is telnet giving me this "More?" response, as if expecting something?
In the code, I am simply connecting to remote CPU, logging in, and sending commands:
#connection = Net::Telnet.new(...)
#connection.login( user, pwd )
#connection.cmd(...)
Any help would be appreciated.
Thanks,
J
**EDIT:
#connection = Net::Telnet.new(
"Host" => machine,
"Prompt" => /[A-Za-z]:\\.*>\z/n,
"Timeout" => 3,
"Output_log" => output )
#connection.login( user, pwd )
#connection.cmd( 'ls' )
#connection.cmd( 'ls' )
output...
C:\Documents and Settings\UserJW>
ls
Desktop
Favorites
My Documents
Start Menu
Sti_Trace.log
C:\Documents and Settings\UserJW>
ls
More?
I can't even send more than one command, apparently. Is my Prompt regex wrong? I'm trying to allow..
C:[anything...]>
I meet a same problem with you ( ruby telnet to windows 2008 ,execute command error ).I solved it. the reason is ruby net/telnet library use error newline seperator. Must be EOL(CR+LF) but CR+NULL . But I don't know who make the bug,windows or ruby? I write a monkey patch as below:
class Net::Telnet
def print(string)
string = string.gsub(/#{IAC}/no, IAC + IAC) if #options["Telnetmode"]
if #options["Binmode"]
self.write(string)
else
if #telnet_option["BINARY"] and #telnet_option["SGA"]
self.write(string.gsub(/\n/n, CR))
elsif #telnet_option["SGA"]
self.write(string.gsub(/\n/n, EOL)) ### fix here. reaplce CR+NULL bY EOL
else
self.write(string.gsub(/\n/n, EOL))
end
end
end
end

Ruby webserver without opened port

I am looking for possibility to have ruby-based webserver communicating by pipe, not by TCP/IP. So I will send HTTP request by pipe and I want to read response by pipe. It should be used as bundled/internal webserver (RPC or something) for desktop application. I don't want to handle ports configuration when there will be more instances of my application running on same machine.
Any ideas?
Thank you in advance.
Try a UNIXSocket You use a local path to specify where the socket connection is,
not a port, and you can easily handle multiple simultaneous connections.
# server.rb
require 'socket'
File.delete( filename ) if File.exists? filename
server = UNIXServer.open( filename )
server.listen( queuesize )
puts "waiting on client connection"
while client= server.accept
puts "got client connection #{client.inspect}"
child_pid = fork do
puts "Asking the client what they want"
client.puts "Welcome to your server, what can I get for you?"
until client.eof?
line = client.gets
puts "The client wants #{line.chomp.inspect}"
end
client.close
end
puts "running server (#{child_pid})"
client.close
Process.detach(child_pid)
end
server.close
# client.rb
require 'socket'
puts "requesting server connection"
server = UNIXSocket.new( filename )
puts "got server connection #{server}"
line = server.gets
puts "The server said: #{line.chomp.inspect}"
%w{ a-pony a-puppy a-kitten a-million-dollars }.each do |item|
server.puts item
end
server.close
Pipe is for one-way communication, so there is no way you can set up webserver on that. You might try with unix socket. But really simplest solution is to use loopback (127.0.0.1). It's highly optimized, so the speed won't be a problem.
Not an answer to your question. However, if you do end up having to use a TCP/IP HTTP Server, you should ensure that it's only listening on 127.0.0.1. Listening on the local host address should be quite fast, as it won't hit the network, and will also make it a tad more secure to stop people connecting from the outside.
Thin supports unix sockets.

Resources