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