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