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