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