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