nntp improvements
[org.ibex.mail.git] / src / org / ibex / mail / protocol / NNTP.java
1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
4
5 // 500 unrec. command
6 // 501 syntax error
7 // 503 optional subfeature not supported 
8 // Xref header
9 // LIST EXTENSIONS is probably incomplete
10
11 package org.ibex.mail.protocol;
12 import org.ibex.util.*;
13 import org.ibex.io.*;
14 import org.ibex.mail.*;
15 import org.ibex.mail.target.*;
16 import org.ibex.jinetd.*;
17 import java.io.*;
18 import java.net.*;
19 import java.util.*;
20 import java.text.*;
21
22 /** NNTP send/recieve */
23 public class NNTP {
24
25     public static final DateFormat dateFormat = new SimpleDateFormat("yyyyMMDDhhmmss");
26
27     public static class No  extends RuntimeException { int code = 400; }                                       // 4xx response codes
28     public static class Bad extends RuntimeException { int code = 500; public Bad(String s) { super(s); } }    // 5xx response codes
29
30     public static class Group {
31         public Group(String n, boolean p, int f, int l, int c) { this.name=n;this.post=p;this.first=f;this.last=l;this.count=c;}
32         public final String  name;    // case insensitive
33         public final boolean post;
34         public final int     first;
35         public final int     last;
36         public final int     count;   // an approximation; must be >= actual number
37     }
38
39     public static class Article {
40         public Article(int num, Message message) { this.message = message; this.num = num; }
41         public final int     num;
42         public final Message message;
43     }
44
45     public static interface Server {
46         public Group    group(String s);
47         public boolean  ihave(String messageid);
48         public Article  next();
49         public Article  last();
50         public boolean  postok();
51         public void     post(Message m) throws IOException;
52         public Article  article(String messageid,  boolean head, boolean body);
53         public Article  article(int    messagenum, boolean head, boolean body);
54         public Group[]  list();
55         public Group[]  newgroups(Date d, String[] distributions);
56         public String[] newnews(String[] groups, Date d, String[] distributions);
57     }
58
59     public static class MailboxWrapper implements Server {
60         private final Mailbox root;
61         private Mailbox current;
62         private int ptr = 0;
63         private boolean post;
64         public MailboxWrapper(Mailbox root) { this(root, false); }
65         public MailboxWrapper(Mailbox root, boolean post) { this.root = root; this.post = post; }
66         public boolean  postok() { return post; }
67         public void     post(Message m) throws IOException { current.accept(m); }
68
69         public Group    group(String s)         {
70             ptr = 0;
71             Group g = getgroup(s);
72             if (g==null) return null;
73             setgroup(s);
74             return g;
75         }
76
77         public boolean  ihave(String messageid) { /* FEATURE */ return false; }
78
79         public Article  next()                  { return article(ptr++, false, false); }
80         public Article  last()                  { return article(ptr--, false, false); }
81         public Article  article(String i, boolean h, boolean b) { return article(Query.header("message-id",i),h,b); }
82         public Article  article(int    n, boolean h, boolean b) { ptr = n; return article(Query.messagenum(n,n),h,b); }
83         private Article article(Query q,  boolean head, boolean body) {
84             Mailbox.Iterator it = current.iterator(q);
85             if (!it.next()) return null;
86             try {
87                 Message m = body ? it.cur() : Message.newMessage(new Fountain.StringFountain(it.head() + "\r\n"));
88                 return new Article(it.num(), m);
89             } catch (Exception e) { return null; }
90         }
91         public Group[]  list() { return list(root, ""); }
92         private Group[] list(Mailbox who, String prefix) {
93             Vec v = new Vec();
94             if (who == null) who = root;
95             String[] s = who.children();
96             for(int i=0; i<s.length; i++) {
97                 v.addElement(new Group(prefix + s[i], true, 0, 0, 0)); // FIXME numbers
98                 Group[] g2 = list(who.slash(s[i], false), prefix + s[i] + ".");
99                 for(int j=0; j<g2.length; j++) v.addElement(g2[j]);
100             }
101             Group[] ret = new Group[v.size()];
102             v.copyInto(ret);
103             return ret;
104         }
105
106         private void setgroup(String s) {
107             Mailbox ncurrent = root;
108             for(StringTokenizer st = new StringTokenizer(s, ".");
109                 ncurrent != null && st.hasMoreTokens();
110                 ncurrent = ncurrent.slash(st.nextToken(), false));
111             if (ncurrent!=null) current=ncurrent;
112         }
113         private Group getgroup(String s) {
114             Mailbox box = root;
115             for(StringTokenizer st = new StringTokenizer(s, "."); box!=null && st.hasMoreTokens(); box = box.slash(st.nextToken(), false));
116             if (box==null) return null;
117             return new Group(s, true, 1, box.count(Query.all()), box.count(Query.all()));
118         }
119
120         public Group[]  newgroups(Date d, String[] distributions) { /* FEATURE */ return new Group[] { }; }
121         public String[] newnews(String[] groups, Date d, String[] distributions) { /* FIXME */  return null; }
122     }
123
124     public static class Listener {
125         private Server api = null;
126         private Login login;
127         private Connection conn;
128         public Listener(Login l) { this.login = l; }
129
130         private void println(String s) { Log.warn("[nntp-write]", s); conn.println(s); }
131         private void println() { Log.warn("[nntp-write]", ""); conn.println(""); }
132         private void print(String s) { Log.warn("[nntp-write]", s); conn.print(s); }
133
134         private void article(String numOrMessageId, boolean head, boolean body) {
135             String s = numOrMessageId.trim();
136             Article a;
137             if (s.startsWith("<")) a = api.article(s.substring(0, s.length() - 1), head, body);
138             else                   a = api.article(Integer.parseInt(s), head, body);
139             if (a == null) {
140                 println("423 No such article.");
141                 return;
142             }
143             int code = (head && body) ? 220 : head ? 221 : body ? 222 : 223;
144             println(code + " " + a.num + " <" + a.message.messageid + "> get ready for some stuff...");
145             if (head) println(a.message.headers.getString());
146             if (head && body) println();
147             if (body) {
148                 Stream stream = a.message.getBody().getStream();
149                 while(true) {
150                     s = stream.readln();
151                     if (s == null) break;
152                     if (s.startsWith(".")) print(".");
153                     println(s);
154                 }
155             }
156             println(".");
157         }
158         public void handleRequest(Connection conn) {
159             this.conn = conn;
160             conn.setTimeout(30 * 60 * 1000);
161             conn.setNewline("\r\n");
162             println("200 " + conn.vhost + " [" + NNTP.class.getName() + "]");
163             String user = null;
164             String pass = null;
165             Account account = login.anonymous();
166             this.api = account == null ? null : new MailboxWrapper(account.getMailbox(NNTP.class), true);
167             for(String line = conn.readln(); line != null; line = conn.readln()) try {
168                 Log.warn("[nntp-read]", line);
169                 StringTokenizer st = new StringTokenizer(line, " ");
170                 String command = st.nextToken().toUpperCase();
171                 if (command.equals("AUTHINFO")) {
172                     // FIXME technically the RFC says we need to use this info to generate a SEnder: header...
173                     String uop = st.nextToken().toUpperCase();
174                     if (uop.equals("USER")) {
175                         user = st.nextToken();
176                         println("381 More authentication required");
177                         continue;
178                     } else if (uop.equals("PASS")) {
179                         pass = st.nextToken();
180                         account = login.login(user, pass);
181                         if (account == null) { println("502 Invalid"); continue; }
182                         Mailbox box = account.getMailbox(NNTP.class);
183                         this.api = new MailboxWrapper(box, true);
184                         println("281 Good to go");
185                         continue;
186                     }
187                     throw new Bad("wtf are you talking about?");
188                 }
189                 if (this.api == null) {
190                     if (user == null) { println("480 Authentication required"); continue; }
191                     if (pass == null) { println("381 Password required"); continue; }
192                 }
193                 if        (command.equals("ARTICLE"))   { article(st.hasMoreTokens() ? st.nextToken() : null, true,  true); 
194                 } else if (command.equals("HEAD"))      { article(st.hasMoreTokens() ? st.nextToken() : null, true,  false); 
195                 } else if (command.equals("DATE"))      {
196                     // FIXME must be GMT
197                     println("111 " + dateFormat.format(new Date()));
198                 } else if (command.equals("MODE"))      {
199                     if (st.hasMoreTokens()) {
200                         String arg = st.nextToken();
201                         if (arg.equalsIgnoreCase("STREAM"));
202                         //streaming = true;
203                         println("203 Streaming permitted");
204                     } else {
205                         println("201 Hello, you can post.");
206                     }
207                 } else if (command.equals("BODY"))      { article(st.hasMoreTokens() ? st.nextToken() : null, false, true); 
208                 } else if (command.equals("STAT"))      { article(st.hasMoreTokens() ? st.nextToken() : null, false, false); 
209                 } else if (command.equals("HELP"))      { println("100 you are beyond help."); println(".");
210                 } else if (command.equals("SLAVE"))     { println("220 I don't care");
211                 } else if (command.equals("XOVER"))     {
212                     println("224 Overview information follows");
213                     MailboxWrapper api = (MailboxWrapper)this.api;
214                     String range = st.hasMoreTokens() ? st.nextToken() : (api.ptr+"-"+api.ptr);
215                     int start = Integer.parseInt(range.substring(0, range.indexOf('-')));
216                     int end   = Integer.parseInt(range.substring(range.indexOf('-') + 1));
217                     Mailbox.Iterator it = api.current.iterator(Query.messagenum(start, end));
218                     while(it.next()) {
219                         try {
220                             Message m = it.cur();
221                             println(it.num()+"\t"+m.subject+"\t"+m.from+"\t"+m.date+"\t"+m.messageid+"\t"+
222                                     m.headers.get("references") + "\t" + m.getLength() + "\t" + m.getNumLines());
223                         } catch (Exception e) { Log.error(this, e); }
224                     }
225                     println(".");
226                 } else if (command.equals("LAST"))      {
227                     Article a = api.last(); println("223 "+a.num+" "+a.message.messageid+" ok");
228                 } else if (command.equals("NEXT"))      {
229                     Article a = api.next(); println("223 "+a.num+" "+a.message.messageid+" ok");
230                 } else if (command.equals("QUIT"))      { println("205 Bye."); conn.close(); return; 
231                 } else if (command.equals("GROUP"))     {
232                     Group g = api.group(st.nextToken().toLowerCase());
233                     if (g==null) println("411 no such group");
234                     else         println("211 " + g.count + " " + g.first + " " + g.last + " " + g.name);
235                 } else if (command.equals("NEWGROUPS") || command.equals("NEWNEWS")) { 
236                     // FIXME: * and ! unsupported
237                     // NEWNEWS is often not supported
238                     String groups = command.equals("NEWNEWS") ? st.nextToken() : null;
239                     String datetime = st.nextToken() + " " + st.nextToken();
240                     String gmt = st.nextToken();
241                     String distributions = gmt.equals("GMT") ? (st.hasMoreTokens() ? st.nextToken() : "") : gmt;
242                     while(st.hasMoreTokens()) distributions += " " + st.nextToken();
243
244                     // FIXME deal with GMT
245                     Date d = new Date();
246                     try {
247                         d = new SimpleDateFormat("yyMMDD HHMMSS").parse(datetime);
248                     } catch (ParseException pe) {
249                         Log.warn(this, pe);
250                     }
251                     distributions = distributions.trim();
252                     if (distributions.startsWith("<")) distributions = distributions.substring(1, distributions.length() - 1);
253
254                     st = new StringTokenizer(distributions, ",");
255                     String[] dists = new String[st.countTokens()];
256                     for(int i=0; st.hasMoreTokens(); i++) dists[i] = st.nextToken();
257
258                     if (command.equals("NEWGROUPS")) {
259                         Group[] g = api.newgroups(d, dists);
260                         println("231 list of groups follows");
261                         for(int i=0; i<g.length; i++)
262                             println(g[i].name + " " + g[i].last + " " + g[i].first + " " + (g[i].post ? "y" : "n"));
263                         println(".");
264                     } else {
265                         st = new StringTokenizer(groups, ",");
266                         String[] g = new String[st.countTokens()];
267                         for(int i=0; st.hasMoreTokens(); i++) g[i] = st.nextToken();
268                         String[] a = api.newnews(g, d, dists);
269                         println("230 list of article messageids follows");
270                         for(int i=0; i<a.length; i++) println(a[i]);
271                         println(".");
272                     }
273
274                 } else if (command.equals("POST"))      { 
275                     // FIXME
276                     // add NNTP-Posting-Host header
277                     // Path header: prepend <myname>, (any punctuation separates the list)
278                     // Expires header: the date when expiration happens (??) should we ignore this?
279                     // Control header: body is the command.  Inteprert posts to all.all.ctl as control messages,
280                     //                 use Subject line if no Cntrol line
281                     // "Approved" line is used for moderaion
282                     // Xref: drop this header if you see it
283
284                     // Control messages
285                     //   cancel <Message-ID>      (do not forward if I am unable to cancel locally)
286                     //   ihave/sendme:            do not support
287                     //   newgroup <groupname> [moderated] -- body of message is a description of the group
288                     //   rmgroup  <groupname>
289
290                     boolean postok = api.postok();
291                     if (!postok) {
292                         println("440 no posting allowed");
293                     } else {
294                       println("340 send the article");
295                       StringBuffer buf = new StringBuffer();
296                       while(true) {
297                         String s = conn.readln();
298                         if (s == null) throw new RuntimeException("connection closed");
299                         if (s.equals(".")) break;
300                         if (s.startsWith(".")) s = s.substring(1);
301                         buf.append(s + "\r\n");
302                       }
303                       String body = buf.toString();
304                       try {
305                           Message m = Message.newMessage(new Fountain.StringFountain(body));
306                           if (m.headers.get("newsgroups")==null)
307                               println("441 posted messages must have a Newsgroups header per RFC 977");
308                           else if (m.headers.get("newsgroups").indexOf('*')!=-1)
309                               println("441 Newsgroups header in posted messages may not contain wildcards (*) per RFC 977");
310                           else if (m.headers.get("subject")==null)
311                               println("441 posted messages must have a Subject header per RFC 977");
312                           //                          else if (m.headers.get("path")==null)
313                           //println("441 posted messages must have a Path header per RFC 977");
314                           else if (m.headers.get("from")==null)
315                               println("441 posted messages must have a From header per RFC 977");
316                           else if (m.headers.get("date")==null)
317                               println("441 posted messages must have a Date header per RFC 977");
318                           else {
319                               api.post(m);
320                               println("240 article posted ok");
321                           }
322                       } catch (Exception e) {
323                           e.printStackTrace();
324                           println("441 posting failed: " + e);
325                       }
326                     }
327
328                 } else if (command.equals("XROVER"))      { 
329                     // equivalent to "XHDR References"
330                 } else if (command.equals("XHDR"))      { 
331                     // argument: header name
332                     // argument: 1 | 1- | 1-2 | <mid> | nothing (use current article)
333                     println("221 yep");
334                     // print art#+header for all matching messages
335                     println(".");
336                     // 412 if no group selected and numeric form used
337                     // 430 if <mid> and not found
338                     // 420 if no messages in range
339                 } else if (command.equals("XPAT"))      { 
340                     // just like XHDR, but a pattern follows the last argument (may contain whitespace)
341                     println("221 yep");
342                     // print 
343                     println(".");
344                 } else if (command.equals("LIST"))      { 
345                     if (st.hasMoreTokens()) {
346                         String argument = st.nextToken().toUpperCase();
347                         if (argument.equalsIgnoreCase("EXTENSIONS")) {
348                             println("202 Extensions supported:");
349                             println("STREAMING");
350                             println("");
351                             println(".");
352                         } else if (argument.equals("ACTIVE")) {
353                             String wildmat = st.hasMoreTokens() ? st.nextToken() : null;
354                             // FIXME: deal with wildmat
355                             // just like list, but only show active groups
356                             throw new Bad("not implemented yet");
357                         } else if (argument.equals("SUBSCRIPTIONS")) {
358                             // FIXME: show 215, default subscription list for new users, period
359                         } else if (argument.equals("OVERVIEW.FMT")) {
360                             println("215 Overview format:");
361                             println("Subject:");
362                             println("From:");
363                             println("Date:");
364                             println("Message-ID:");
365                             println("References:");
366                             println("Bytes:");
367                             println("Lines:");
368                             //println("Xref:full");
369                             println(".");
370                         } else if (argument.equals("NEWSGROUPS")) {
371                             String wildmat = st.hasMoreTokens() ? st.nextToken() : null;
372                             // respond 215, print each newsgroup, a space, and the description; end with lone period
373                         } else {
374                             // barf here
375                         }
376                     } else {
377                         Group[] g = api.list();
378                         println("215 list of groups follows");
379                         for(int i=0; i<g.length; i++)
380                             println(g[i].name + " " + g[i].last + " " + g[i].first + " " + (g[i].post ? "y" : "n"));
381                         println(".");
382                     }
383
384                 } else if (command.equals("LISTGROUP"))     {
385                     String groupname = st.hasMoreTokens() ? st.nextToken() : null;
386                     // 211, all article numbers in group, period.  Set article ptr to first item in group
387
388                 } else if (command.equals("XGTITLE"))     {
389                     String wildmat = st.hasMoreTokens() ? st.nextToken() : null;
390                     // 282, then identical to LIST NEWSGROUP
391
392                 } else if (command.equals("CHECK"))     {
393                     // FIXME: may be pipelined; must spawn threads
394                     String mid = st.nextToken();
395                     boolean want = api.ihave(mid);
396                     if (!want) {
397                         println("438 "+ mid+" No thanks");
398                     } else {
399                         println("238 "+mid+" Yes, I'd like that");
400                     }
401
402                 } else if (command.equals("TAKETHIS"))     {
403                     // FIXME: may be pipelined
404                     String mid = st.nextToken();
405                     // MUST read message here
406                     /*
407                     if (!want) {
408                         println("439 "+ mid+" Transfer failed");
409                     } else {
410                         println("239 "+mid+" Rock on.");
411                     }
412                     */
413
414                 } else if (command.equals("IHAVE"))     {
415                     boolean want = api.ihave(st.nextToken());
416                     if (!want) {
417                         println("435 No thanks");
418                     } else {
419                         println("335 Proceed");
420                         // FIXME read article here
421                         println("235 Got it");
422                     }
423                 } else {
424                     throw new Bad("wtf are you talking about?");
425                 }
426             } catch (No n)  { println(n.code + " " + n.getMessage());
427             } catch (Bad b) { println(b.code + " " + b.getMessage()); Log.warn(this, b); }
428             conn.close();
429         }
430     }
431 }