Wednesday, March 28, 2007

Knowing the protocol : POP

Abstract: telnet pop.mail.net 110

Knowing the protocol
Knowing a protocol can be useful on many occasions.
  • You can test a service you are installing
  • You can diagnose a problem when your friend tells you "It doesn't work !"
  • If you have a problem you can solve it by yourself
Yesterday I had to download 32000 mails from the pop server, and my poor mail client (no, fetchmail is not the only one available) couldn't withstand it. The problem is that it did not delete already downloaded mails on the server. I didn't want to try again with for sure the same result.

Knowing POP protocol
I will only present a sample connection, for the full description, you can read the RFC.

A pop session is really simple. In bold is what you provide :
$ telnet pop.mail.net 110
Trying 127.0.0.1...
Connected to pop.mail.net.
Escape character is '^]'.
+OK <23594.1175023984@pop.mail.net>
USER jdoe
+OK
PASS xxx
+OK
LIST
+OK
1 1235
.
RETR 1
[...]
+OK
DELE 1
+OK
QUIT
Connection closed by foreign host.

[...] is the real content of the mail.
Now we can proceed to mass mail deletion.

Scripting
We will use nc instead of telnet because it is more easy to use it for scripting.
First we are going to prepare a command file that we'll send to the pop server.

$ # the login part
$ echo "USER jdoe" > file1
$ echo "PASS xxx" >> file1

$ # the deletion part
$ for i in $(seq 1 15000); do echo DELE $i ; done > file2

$ # the end
$ echo "QUIT" >> file2

Why 2 different files ? Because we'll need to have a break after the login to let the server process the command. Otherwise it rejects us.

Why include QUIT ? Because the pop server doesn't validate DELE commands if we don't quit properly.

Now the command that does the trick:
$ cat file1 - file2 | nc pop.mail.net 110

We first send file1, then we wait for user input, then we send file2. Standard output is not changed, so you can still see what's happening.

Once you see that the login is accepted, you can end standard input by pressing ctrl-d and the command continues with file2.

Notice that there is a different method with a bit less control but that is autonomous.
$ (cat file1 ; sleep 2; cat file2) | nc pop.mail.net 110

No comments: