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