Changeset 1a6b49c


Ignore:
Timestamp:
Aug 23, 2005 9:25:49 PM (15 years ago)
Author:
zzz <zzz@…>
Branches:
master
Children:
5ec6dca6
Parents:
c7b75df3
git-author:
jrandom <jrandom> (08/23/05 21:25:49)
git-committer:
zzz <zzz@…> (08/23/05 21:25:49)
Message:

2005-08-23 jrandom

  • Removed the concept of "no bandwidth limit" - if none is specified, its 16KBps in/out.
  • Include ack packets in the per-peer cwin throttle (they were part of the bandwidth limit though).
  • Tweak the SSU cwin operation to get more accurrate estimates under congestions.
  • SSU improvements to resend more efficiently.
  • Added a basic scheduler to eepget to fetch multiple files sequentially.
Files:
10 added
27 edited

Legend:

Unmodified
Added
Removed
  • apps/syndie/java/src/net/i2p/syndie/Archive.java

    rc7b75df3 r1a6b49c  
    3131    private ArchiveIndex _index;
    3232    private EntryExtractor _extractor;
     33    private String _defaultSelector;
    3334   
    3435    public static final String METADATA_FILE = "meta.snm";
     
    5152        _index = null;
    5253        _extractor = new EntryExtractor(ctx);
     54        _defaultSelector = ctx.getProperty("syndie.defaultSelector");
     55        if (_defaultSelector == null) _defaultSelector = "";
    5356        reloadInfo();
    5457    }
     
    6467                    try {
    6568                        bi.load(new FileInputStream(meta));
    66                         info.add(bi);
     69                        if (bi.verify(_context)) {
     70                            info.add(bi);
     71                        } else {
     72                            System.err.println("Invalid blog (but we're storing it anyway): " + bi);
     73                            info.add(bi);
     74                        }
    6775                    } catch (IOException ioe) {
    6876                        ioe.printStackTrace();
     
    8088        }
    8189    }
     90   
     91    public String getDefaultSelector() { return _defaultSelector; }
    8292       
    8393    public BlogInfo getBlogInfo(BlogURI uri) {
     94        if (uri == null) return null;
    8495        synchronized (_blogInfo) {
    8596            return (BlogInfo)_blogInfo.get(uri.getKeyHash());
     
    91102        }
    92103    }
    93     public void storeBlogInfo(BlogInfo info) {
     104    public boolean storeBlogInfo(BlogInfo info) {
    94105        if (!info.verify(_context)) {
    95106            System.err.println("Not storing the invalid blog " + info);
    96             return;
    97         }
     107            return false;
     108        }
     109        boolean isNew = true;
    98110        synchronized (_blogInfo) {
    99             _blogInfo.put(info.getKey().calculateHash(), info);
    100         }
     111            BlogInfo old = (BlogInfo)_blogInfo.get(info.getKey().calculateHash());
     112            if ( (old == null) || (old.getEdition() < info.getEdition()) )
     113                _blogInfo.put(info.getKey().calculateHash(), info);
     114            else
     115                isNew = false;
     116        }
     117        if (!isNew) return true; // valid entry, but not stored, since its old
    101118        try {
    102119            File blogDir = new File(_rootDir, info.getKey().calculateHash().toBase64());
     
    107124            out.close();
    108125            System.out.println("Blog info written to " + blogFile.getPath());
     126            return true;
    109127        } catch (IOException ioe) {
    110128            ioe.printStackTrace();
     129            return false;
    111130        }
    112131    }
     
    263282   
    264283    public boolean storeEntry(EntryContainer container) {
     284        if (container == null) return false;
    265285        BlogURI uri = container.getURI();
     286        if (uri == null) return false;
     287
     288        File blogDir = new File(_rootDir, uri.getKeyHash().toBase64());
     289        blogDir.mkdirs();
     290        File entryFile = new File(blogDir, getEntryFilename(uri.getEntryId()));
     291        if (entryFile.exists()) return true;
     292
     293
    266294        BlogInfo info = getBlogInfo(uri);
    267295        if (info == null) {
     
    275303            //System.out.println("Signature is valid: " + container.getSignature() + " for info " + info);
    276304        }
    277         ByteArrayOutputStream baos = new ByteArrayOutputStream();
    278         try {
     305        try {
     306            ByteArrayOutputStream baos = new ByteArrayOutputStream();   
    279307            container.write(baos, true);
    280             File blogDir = new File(_rootDir, uri.getKeyHash().toBase64());
    281             blogDir.mkdirs();
    282308            byte data[] = baos.toByteArray();
    283             File entryFile = new File(blogDir, getEntryFilename(uri.getEntryId()));
    284309            FileOutputStream out = new FileOutputStream(entryFile);
    285310            out.write(data);
  • apps/syndie/java/src/net/i2p/syndie/BlogManager.java

    rc7b75df3 r1a6b49c  
    1919    private File _userDir;
    2020    private File _cacheDir;
     21    private File _tempDir;
    2122    private Archive _archive;
    2223   
     
    4344        _userDir = new File(root, "users");
    4445        _cacheDir = new File(root, "cache");
     46        _tempDir = new File(root, "temp");
    4547        _blogKeyDir.mkdirs();
    4648        _privKeyDir.mkdirs();
     
    4850        _cacheDir.mkdirs();
    4951        _userDir.mkdirs();
     52        _tempDir.mkdirs();
    5053        _archive = new Archive(ctx, _archiveDir.getAbsolutePath(), _cacheDir.getAbsolutePath());
    5154        _archive.regenerateIndex();
     
    9497   
    9598    public Archive getArchive() { return _archive; }
     99    public File getTempDir() { return _tempDir; }
    96100   
    97101    public List listMyBlogs() {
     
    176180        try {
    177181            out = new FileWriter(userFile);
    178             out.write("password=" + user.getHashedPassword() + "\n");
    179             out.write("blog=" + user.getBlog().toBase64() + "\n");
    180             out.write("lastid=" + user.getMostRecentEntry() + "\n");
    181             out.write("lastmetaedition=" + user.getLastMetaEntry() + "\n");
    182             out.write("lastlogin=" + user.getLastLogin() + "\n");
    183             out.write("addressbook=" + user.getAddressbookLocation() + "\n");
    184             out.write("showimages=" + user.getShowImages() + "\n");
    185             out.write("showexpanded=" + user.getShowExpanded() + "\n");
    186             StringBuffer buf = new StringBuffer();
    187             buf.append("groups=");
    188             Map groups = user.getBlogGroups();
    189             for (Iterator iter = groups.keySet().iterator(); iter.hasNext(); ) {
    190                 String name = (String)iter.next();
    191                 List selectors = (List)groups.get(name);
    192                 buf.append(name).append(':');
    193                 for (int i = 0; i < selectors.size(); i++) {
    194                     buf.append(selectors.get(i));
    195                     if (i + 1 < selectors.size())
    196                         buf.append(",");
    197                 }
    198                 if (iter.hasNext())
    199                     buf.append(' ');
    200             }
    201             buf.append('\n');
    202             out.write(buf.toString());
    203             // shitlist=hash,hash,hash
    204             List shitlistedBlogs = user.getShitlistedBlogs();
    205             if (shitlistedBlogs.size() > 0) {
    206                 buf.setLength(0);
    207                 buf.append("shitlistedblogs=");
    208                 for (int i = 0; i < shitlistedBlogs.size(); i++) {
    209                     Hash blog = (Hash)shitlistedBlogs.get(i);
    210                     buf.append(blog.toBase64());
    211                     if (i + 1 < shitlistedBlogs.size())
    212                         buf.append(',');
    213                 }
    214                 buf.append('\n');
    215                 out.write(buf.toString());
    216             }
     182            out.write(user.export());
    217183        } catch (IOException ioe) {
    218184            ioe.printStackTrace();
     
    348314    }
    349315   
     316    /**
     317     * read in the syndie blog metadata file from the stream, verifying it and adding it to
     318     * the archive if necessary
     319     *
     320     */
     321    public boolean importBlogMetadata(InputStream metadataStream) throws IOException {
     322        try {
     323            BlogInfo info = new BlogInfo();
     324            info.load(metadataStream);
     325            return _archive.storeBlogInfo(info);
     326        } catch (IOException ioe) {
     327            ioe.printStackTrace();
     328            return false;
     329        }
     330    }
     331   
     332    /**
     333     * read in the syndie entry file from the stream, verifying it and adding it to
     334     * the archive if necessary
     335     *
     336     */
     337    public boolean importBlogEntry(InputStream entryStream) throws IOException {
     338        try {
     339            EntryContainer c = new EntryContainer();
     340            c.load(entryStream);
     341            return _archive.storeEntry(c);
     342        } catch (IOException ioe) {
     343            ioe.printStackTrace();
     344            return false;
     345        }
     346    }
     347   
     348   
    350349    public String addAddress(User user, String name, String location, String schema) {
    351350        if (!user.getAuthenticated()) return "Not logged in";
  • apps/syndie/java/src/net/i2p/syndie/User.java

    rc7b75df3 r1a6b49c  
    2525    private boolean _showImagesByDefault;
    2626    private boolean _showExpandedByDefault;
     27    private String _defaultSelector;
    2728    private long _lastLogin;
    2829    private long _lastMetaEntry;
     30    private boolean _allowAccessRemote;
    2931    private boolean _authenticated;
     32    private String _eepProxyHost;
     33    private int _eepProxyPort;
     34    private String _webProxyHost;
     35    private int _webProxyPort;
     36    private String _torProxyHost;
     37    private int _torProxyPort;
    3038   
    3139    public User() {
     
    4149        _blogGroups = new HashMap();
    4250        _shitlistedBlogs = new ArrayList();
     51        _defaultSelector = null;
    4352        _addressbookLocation = "userhosts.txt";
    4453        _showImagesByDefault = false;
    4554        _showExpandedByDefault = false;
     55        _allowAccessRemote = false;
     56        _eepProxyHost = null;
     57        _webProxyHost = null;
     58        _torProxyHost = null;
     59        _eepProxyPort = -1;
     60        _webProxyPort = -1;
     61        _torProxyPort = -1;
    4662        _lastLogin = -1;
    4763        _lastMetaEntry = 0;
     
    6177    public String getHashedPassword() { return _hashedPassword; }
    6278    public long getLastMetaEntry() { return _lastMetaEntry; }
     79    public String getDefaultSelector() { return _defaultSelector; }
     80    public void setDefaultSelector(String sel) { _defaultSelector = sel; }
     81    public boolean getAllowAccessRemote() { return _allowAccessRemote; }
     82    public void setAllowAccessRemote(boolean allow) { _allowAccessRemote = true; }
    6383   
    6484    public void setMostRecentEntry(long id) { _mostRecentEntry = id; }
    6585    public void setLastMetaEntry(long id) { _lastMetaEntry = id; }
    6686
     87    public String getEepProxyHost() { return _eepProxyHost; }
     88    public int getEepProxyPort() { return _eepProxyPort; }
     89    public String getWebProxyHost() { return _webProxyHost; }
     90    public int getWebProxyPort() { return _webProxyPort; }
     91    public String getTorProxyHost() { return _torProxyHost; }
     92    public int getTorProxyPort() { return _torProxyPort; }
     93   
    6794    public void invalidate() {
    6895        BlogManager.instance().saveUser(this);
     
    136163        show = props.getProperty("showexpanded", "false");
    137164        _showExpandedByDefault = (show != null) && (show.equals("true"));
    138        
     165        _defaultSelector = props.getProperty("defaultselector");
     166        String allow = props.getProperty("allowaccessremote", "false");
     167        _allowAccessRemote = (allow != null) && (allow.equals("true"));
     168        _eepProxyPort = getInt(props.getProperty("eepproxyport"));
     169        _webProxyPort = getInt(props.getProperty("webproxyport"));
     170        _torProxyPort = getInt(props.getProperty("torproxyport"));
     171        _eepProxyHost = props.getProperty("eepproxyhost");
     172        _webProxyHost = props.getProperty("webproxyhost");
     173        _torProxyHost = props.getProperty("torproxyhost");
    139174        _lastLogin = _context.clock().now();
    140175        _authenticated = true;
     
    142177    }
    143178   
     179    private int getInt(String val) {
     180        if (val == null) return -1;
     181        try { return Integer.parseInt(val); } catch (NumberFormatException nfe) { return -1; }
     182    }
     183   
    144184    public static final String LOGIN_OK = "Logged in";
     185   
     186    public String export() {
     187        StringBuffer buf = new StringBuffer(512);
     188        buf.append("password=" + getHashedPassword() + "\n");
     189        buf.append("blog=" + getBlog().toBase64() + "\n");
     190        buf.append("lastid=" + getMostRecentEntry() + "\n");
     191        buf.append("lastmetaedition=" + getLastMetaEntry() + "\n");
     192        buf.append("lastlogin=" + getLastLogin() + "\n");
     193        buf.append("addressbook=" + getAddressbookLocation() + "\n");
     194        buf.append("showimages=" + getShowImages() + "\n");
     195        buf.append("showexpanded=" + getShowExpanded() + "\n");
     196        buf.append("defaultselector=" + getDefaultSelector() + "\n");
     197        buf.append("allowaccessremote=" + _allowAccessRemote + "\n");
     198        buf.append("eepproxyhost="+_eepProxyHost+"\n");
     199        buf.append("eepproxyport="+_eepProxyPort+"\n");
     200        buf.append("webproxyhost="+_webProxyHost+"\n");
     201        buf.append("webproxyport="+_webProxyPort+"\n");
     202        buf.append("torproxyhost="+_torProxyHost+"\n");
     203        buf.append("torproxyport="+_torProxyPort+"\n");
     204       
     205        buf.append("groups=");
     206        Map groups = getBlogGroups();
     207        for (Iterator iter = groups.keySet().iterator(); iter.hasNext(); ) {
     208            String name = (String)iter.next();
     209            List selectors = (List)groups.get(name);
     210            buf.append(name).append(':');
     211            for (int i = 0; i < selectors.size(); i++) {
     212                buf.append(selectors.get(i));
     213                if (i + 1 < selectors.size())
     214                    buf.append(",");
     215            }
     216            if (iter.hasNext())
     217                buf.append(' ');
     218        }
     219        buf.append('\n');
     220        // shitlist=hash,hash,hash
     221        List shitlistedBlogs = getShitlistedBlogs();
     222        if (shitlistedBlogs.size() > 0) {
     223            buf.setLength(0);
     224            buf.append("shitlistedblogs=");
     225            for (int i = 0; i < shitlistedBlogs.size(); i++) {
     226                Hash blog = (Hash)shitlistedBlogs.get(i);
     227                buf.append(blog.toBase64());
     228                if (i + 1 < shitlistedBlogs.size())
     229                    buf.append(',');
     230            }
     231            buf.append('\n');
     232        }
     233
     234        return buf.toString();
     235    }
    145236}
  • apps/syndie/java/src/net/i2p/syndie/data/ArchiveIndex.java

    rc7b75df3 r1a6b49c  
    7777    /** get the raw entry size (including attachments) from the given blog/tag pair */
    7878    public long getBlogEntrySizeKB(int index, int entryIndex) { return ((EntrySummary)((BlogSummary)_blogs.get(index)).entries.get(entryIndex)).size; }
     79   
     80    public boolean getEntryIsKnown(BlogURI uri) { return getEntry(uri) != null; }
     81    public long getBlogEntrySizeKB(BlogURI uri) {
     82        EntrySummary entry = getEntry(uri);
     83        if (entry == null) return -1;
     84        return entry.size;
     85    }
     86    private EntrySummary getEntry(BlogURI uri) {
     87        if ( (uri == null) || (uri.getKeyHash() == null) || (uri.getEntryId() < 0) ) return null;
     88        for (int i = 0; i < _blogs.size(); i++) {
     89            BlogSummary summary = (BlogSummary)_blogs.get(i);
     90            if (summary.blog.equals(uri.getKeyHash())) {
     91                for (int j = 0; j < summary.entries.size(); j++) {
     92                    EntrySummary entry = (EntrySummary)summary.entries.get(j);
     93                    if (entry.entry.equals(uri))
     94                        return entry;
     95                }
     96            }
     97        }
     98        return null;
     99    }
     100    public Set getBlogEntryTags(BlogURI uri) {
     101        Set tags = new HashSet();
     102        if ( (uri == null) || (uri.getKeyHash() == null) || (uri.getEntryId() < 0) ) return tags;
     103        for (int i = 0; i < _blogs.size(); i++) {
     104            BlogSummary summary = (BlogSummary)_blogs.get(i);
     105            if (summary.blog.equals(uri.getKeyHash())) {
     106                for (int j = 0; j < summary.entries.size(); j++) {
     107                    EntrySummary entry = (EntrySummary)summary.entries.get(j);
     108                    if (entry.entry.equals(uri)) {
     109                        tags.add(summary.tag);
     110                        break;
     111                    }
     112                }
     113            }
     114        }
     115        return tags;
     116    }
    79117   
    80118    /** how many 'new' blogs are listed */
  • apps/syndie/java/src/net/i2p/syndie/data/BlogInfo.java

    rc7b75df3 r1a6b49c  
    1414 *  Owner: base64 of their signing public key
    1515 *  Signature: base64 of the DSA signature of the rest of the ordered metadata
     16 *  Edition: base10 unique identifier for this metadata (higher clobbers lower)
    1617 *
    1718 * Optional keys:
     
    5455    public static final String NAME = "Name";
    5556    public static final String DESCRIPTION = "Description";
     57    public static final String EDITION = "Edition";
    5658   
    5759    public void load(InputStream in) throws IOException {
     
    6466            int len = line.length();
    6567            int split = line.indexOf(':');
    66             if ( (len <= 0) || (split <= 0) || (split >= len - 2) )
     68            if ( (len <= 0) || (split <= 0) ) {
    6769                continue;
     70            } else if (split >= len - 1) {
     71                names.add(line.substring(0, split).trim());
     72                vals.add("");
     73                continue;
     74            }
    6875           
    6976            String key = line.substring(0, split).trim();
     
    103110                buf.append(_optionNames[i]).append(':').append(_optionValues[i]).append('\n');
    104111        }
    105         out.write(buf.toString().getBytes());
     112        String s = buf.toString();
     113        out.write(s.getBytes());
    106114    }
    107115   
     
    132140        _optionNames = names;
    133141        _optionValues = values;
     142    }
     143   
     144    public int getEdition() {
     145        String e = getProperty(EDITION);
     146        if (e != null) {
     147            try {
     148                return Integer.parseInt(e);
     149            } catch (NumberFormatException nfe) {
     150                return 0;
     151            }
     152        }
     153        return 0;
    134154    }
    135155   
     
    152172            ByteArrayOutputStream out = new ByteArrayOutputStream(512);
    153173            write(out, false);
    154             return ctx.dsa().verifySignature(_signature, out.toByteArray(), _key);
     174            out.close();
     175            byte data[] = out.toByteArray();
     176            return ctx.dsa().verifySignature(_signature, data, _key);
    155177        } catch (IOException ioe) {
    156178            return false;
     
    193215        return buf.toString();
    194216    }
     217   
     218    public static void main(String args[]) {
     219        I2PAppContext ctx = I2PAppContext.getGlobalContext();
     220        /*
     221        try {
     222            Object keys[] = ctx.keyGenerator().generateSigningKeypair();
     223            SigningPublicKey pub = (SigningPublicKey)keys[0];
     224            SigningPrivateKey priv = (SigningPrivateKey)keys[1];
     225
     226            Properties opts = new Properties();
     227            opts.setProperty("Name", "n4m3");
     228            opts.setProperty("Description", "foo");
     229            opts.setProperty("Edition", "0");
     230            opts.setProperty("ContactURL", "u@h.org");
     231
     232            BlogInfo info = new BlogInfo(pub, null, opts);
     233            System.err.println("\n");
     234            System.err.println("\n");
     235            info.sign(ctx, priv);
     236            System.err.println("\n");
     237            boolean ok = info.verify(ctx);
     238            System.err.println("\n");
     239            System.err.println("sign&verify: " + ok);
     240            System.err.println("\n");
     241            System.err.println("\n");
     242           
     243            FileOutputStream o = new FileOutputStream("bloginfo-test.dat");
     244            info.write(o, true);
     245            o.close();
     246            FileInputStream i = new FileInputStream("bloginfo-test.dat");
     247            byte buf[] = new byte[4096];
     248            int sz = DataHelper.read(i, buf);
     249            BlogInfo read = new BlogInfo();
     250            read.load(new ByteArrayInputStream(buf, 0, sz));
     251            ok = read.verify(ctx);
     252            System.err.println("write to disk, verify read: " + ok);
     253            System.err.println("Data: " + Base64.encode(buf, 0, sz));
     254            System.err.println("Str : " + new String(buf, 0, sz));
     255        } catch (Exception e) { e.printStackTrace(); }
     256        */
     257        try {
     258            FileInputStream in = new FileInputStream(args[0]);
     259            BlogInfo info = new BlogInfo();
     260            info.load(in);
     261            boolean ok = info.verify(I2PAppContext.getGlobalContext());
     262            System.out.println("OK? " + ok + " :" + info);
     263        } catch (Exception e) { e.printStackTrace(); }
     264    }
    195265}
  • apps/syndie/java/src/net/i2p/syndie/data/EntryContainer.java

    rc7b75df3 r1a6b49c  
    7373   
    7474    public void load(InputStream source) throws IOException {
    75         String fmt = DataHelper.readLine(source).trim();
     75        String line = DataHelper.readLine(source);
     76        if (line == null) throw new IOException("No format line in the entry");
     77        String fmt = line.trim();
    7678        if (FORMAT_ZIP_UNENCRYPTED_STR.equals(fmt)) {
    7779            _format = FORMAT_ZIP_UNENCRYPTED;
     
    8284        }
    8385       
    84         String line = null;
    8586        while ( (line = DataHelper.readLine(source)) != null) {
    8687            line = line.trim();
     
    100101       
    101102        String sigStr = DataHelper.readLine(source);
     103        if ( (sigStr == null) || (sigStr.indexOf("Signature:") == -1) )
     104            throw new IOException("No signature line");
    102105        sigStr = sigStr.substring("Signature:".length()+1).trim();
    103106       
     
    105108        //System.out.println("Sig: " + _signature.toBase64());
    106109       
    107         line = DataHelper.readLine(source).trim();
     110        line = DataHelper.readLine(source);
     111        if (line == null)
     112            throw new IOException("No size line");
     113        line = line.trim();
    108114        int dataSize = -1;
    109115        try {
     
    111117            if (index == 0)
    112118                dataSize = Integer.parseInt(line.substring("Size:".length()+1).trim());
     119            else
     120                throw new IOException("Invalid size line");
    113121        } catch (NumberFormatException nfe) {
    114122            throw new IOException("Invalid entry size: " + line);
  • apps/syndie/java/src/net/i2p/syndie/sml/HTMLRenderer.java

    rc7b75df3 r1a6b49c  
    1313 */
    1414public class HTMLRenderer extends EventReceiverImpl {
    15     private SMLParser _parser;
    16     private Writer _out;
    17     private User _user;
    18     private Archive _archive;
    19     private EntryContainer _entry;
    20     private boolean _showImages;
    21     private boolean _cutBody;
    22     private boolean _cutReached;
    23     private int _cutSize;
    24     private int _lastNewlineAt;
    25     private Map _headers;
    26     private List _addresses;
    27     private List _links;
    28     private List _blogs;
    29     private StringBuffer _preBodyBuffer;
    30     private StringBuffer _bodyBuffer;
    31     private StringBuffer _postBodyBuffer;
     15    protected SMLParser _parser;
     16    protected Writer _out;
     17    protected User _user;
     18    protected Archive _archive;
     19    protected EntryContainer _entry;
     20    protected boolean _showImages;
     21    protected boolean _cutBody;
     22    protected boolean _cutReached;
     23    protected int _cutSize;
     24    protected int _lastNewlineAt;
     25    protected Map _headers;
     26    protected List _addresses;
     27    protected List _links;
     28    protected List _blogs;
     29    protected StringBuffer _preBodyBuffer;
     30    protected StringBuffer _bodyBuffer;
     31    protected StringBuffer _postBodyBuffer;
    3232   
    3333    public HTMLRenderer() {
     
    191191   
    192192    /** are we either before the cut or rendering without cutting? */
    193     private boolean continueBody() {
     193    protected boolean continueBody() {
    194194        boolean rv = ( (!_cutReached) && (_bodyBuffer.length() <= _cutSize) ) || (!_cutBody);
    195195        //if (!rv)
     
    228228    }
    229229   
    230     private static class Blog {
     230    protected static class Blog {
    231231        public String name;
    232232        public String hash;
     
    318318    }
    319319   
    320     private static class Link {
     320    protected static class Link {
    321321        public String schema;
    322322        public String location;
     
    341341    }
    342342
    343     private static class Address {
     343    protected static class Address {
    344344        public String name;
    345345        public String schema;
     
    382382    public void receiveEnd() {
    383383        _postBodyBuffer.append("</td></tr>\n");
    384         _postBodyBuffer.append("<tr>\n");
    385         _postBodyBuffer.append("<form action=\"").append(getAttachmentURLBase()).append("\">\n");
    386         _postBodyBuffer.append("<input type=\"hidden\" name=\"").append(ArchiveViewerBean.PARAM_BLOG);
    387         _postBodyBuffer.append("\" value=\"");
    388         if (_entry != null)
    389             _postBodyBuffer.append(Base64.encode(_entry.getURI().getKeyHash().getData()));
    390         else
    391             _postBodyBuffer.append("unknown");
    392         _postBodyBuffer.append("\" />\n");
    393         _postBodyBuffer.append("<input type=\"hidden\" name=\"").append(ArchiveViewerBean.PARAM_ENTRY);
    394         _postBodyBuffer.append("\" value=\"");
    395         if (_entry != null)
    396             _postBodyBuffer.append(_entry.getURI().getEntryId());
    397         else
    398             _postBodyBuffer.append("unknown");
    399         _postBodyBuffer.append("\" />\n");
    400         _postBodyBuffer.append("<td valign=\"top\" align=\"left\" style=\"entry.attachments.cell\" bgcolor=\"#77ff77\">\n");
    401        
    402         if ( (_entry != null) && (_entry.getAttachments() != null) && (_entry.getAttachments().length > 0) ) {
    403             _postBodyBuffer.append("<b>Attachments:</b> ");
    404             _postBodyBuffer.append("<select name=\"").append(ArchiveViewerBean.PARAM_ATTACHMENT).append("\">\n");
    405             for (int i = 0; i < _entry.getAttachments().length; i++) {
    406                 _postBodyBuffer.append("<option value=\"").append(i).append("\">");
    407                 Attachment a = _entry.getAttachments()[i];
    408                 _postBodyBuffer.append(sanitizeString(a.getName()));
    409                 if ( (a.getDescription() != null) && (a.getDescription().trim().length() > 0) ) {
    410                     _postBodyBuffer.append(": ");
    411                     _postBodyBuffer.append(sanitizeString(a.getDescription()));
     384        if (_cutBody) {
     385            _postBodyBuffer.append("<tr class=\"syndieEntryAttachmentsCell\">\n");
     386            _postBodyBuffer.append("<td colspan=\"2\" valign=\"top\" align=\"left\" class=\"syndieEntryAttachmentsCell\">");
     387            _postBodyBuffer.append("<a href=\"").append(getEntryURL()).append("\">View details...</a> ");
     388           
     389            if ( (_entry != null) && (_entry.getAttachments() != null) && (_entry.getAttachments().length > 0) ) {
     390                int num = _entry.getAttachments().length;
     391                if (num == 1)
     392                    _postBodyBuffer.append("1 attachment ");
     393                else
     394                    _postBodyBuffer.append(num + " attachments ");
     395            }
     396           
     397            int blogs = _blogs.size();
     398            if (blogs == 1)
     399                _postBodyBuffer.append("1 blog reference ");
     400            else if (blogs > 1)
     401                _postBodyBuffer.append(blogs).append(" blog references ");
     402           
     403            int links = _links.size();
     404            if (links == 1)
     405                _postBodyBuffer.append("1 external link ");
     406            else if (links > 1)
     407                _postBodyBuffer.append(links).append(" external links");
     408
     409            int addrs = _addresses.size();
     410            if (addrs == 1)
     411                _postBodyBuffer.append("1 address ");
     412            else if (addrs > 1)
     413                _postBodyBuffer.append(addrs).append(" addresses ");
     414           
     415            _postBodyBuffer.append("</td></tr>\n");
     416        } else {
     417            _postBodyBuffer.append("<tr class=\"syndieEntryAttachmentsCell\">\n");
     418            _postBodyBuffer.append("<form action=\"").append(getAttachmentURLBase()).append("\">\n");
     419            _postBodyBuffer.append("<input type=\"hidden\" name=\"").append(ArchiveViewerBean.PARAM_BLOG);
     420            _postBodyBuffer.append("\" value=\"");
     421            if (_entry != null)
     422                _postBodyBuffer.append(Base64.encode(_entry.getURI().getKeyHash().getData()));
     423            else
     424                _postBodyBuffer.append("unknown");
     425            _postBodyBuffer.append("\" />\n");
     426            _postBodyBuffer.append("<input type=\"hidden\" name=\"").append(ArchiveViewerBean.PARAM_ENTRY);
     427            _postBodyBuffer.append("\" value=\"");
     428            if (_entry != null)
     429                _postBodyBuffer.append(_entry.getURI().getEntryId());
     430            else
     431                _postBodyBuffer.append("unknown");
     432            _postBodyBuffer.append("\" />\n");
     433            _postBodyBuffer.append("<td colspan=\"2\" valign=\"top\" align=\"left\" class=\"syndieEntryAttachmentsCell\">\n");
     434
     435            if ( (_entry != null) && (_entry.getAttachments() != null) && (_entry.getAttachments().length > 0) ) {
     436                _postBodyBuffer.append("<b>Attachments:</b> ");
     437                _postBodyBuffer.append("<select name=\"").append(ArchiveViewerBean.PARAM_ATTACHMENT).append("\">\n");
     438                for (int i = 0; i < _entry.getAttachments().length; i++) {
     439                    _postBodyBuffer.append("<option value=\"").append(i).append("\">");
     440                    Attachment a = _entry.getAttachments()[i];
     441                    _postBodyBuffer.append(sanitizeString(a.getName()));
     442                    if ( (a.getDescription() != null) && (a.getDescription().trim().length() > 0) ) {
     443                        _postBodyBuffer.append(": ");
     444                        _postBodyBuffer.append(sanitizeString(a.getDescription()));
     445                    }
     446                    _postBodyBuffer.append(" (").append(a.getDataLength()/1024).append("KB");
     447                    _postBodyBuffer.append(", type ").append(sanitizeString(a.getMimeType())).append(")</option>\n");
    412448                }
    413                 _postBodyBuffer.append(" (").append(a.getDataLength()/1024).append("KB");
    414                 _postBodyBuffer.append(", type ").append(sanitizeString(a.getMimeType())).append(")</option>\n");
    415             }
    416             _postBodyBuffer.append("</select>\n");
    417             _postBodyBuffer.append("<input type=\"submit\" value=\"Download\" name=\"Download\" /><br />\n");
    418         }
    419        
    420         if (_blogs.size() > 0) {
    421             _postBodyBuffer.append("<b>Blog references:</b> ");
    422             for (int i = 0; i < _blogs.size(); i++) {
    423                 Blog b = (Blog)_blogs.get(i);
    424                 _postBodyBuffer.append("<a href=\"").append(getPageURL(new Hash(Base64.decode(b.hash)), b.tag, b.entryId, -1, -1, (_user != null ? _user.getShowExpanded() : false), (_user != null ? _user.getShowImages() : false)));
    425                 _postBodyBuffer.append("\">").append(sanitizeString(b.name)).append("</a> ");
    426             }
    427             _postBodyBuffer.append("<br />\n");
    428         }
    429        
    430         if (_links.size() > 0) {
    431             _postBodyBuffer.append("<b>External links:</b> ");
    432             for (int i = 0; i < _links.size(); i++) {
    433                 Link l = (Link)_links.get(i);
    434                 _postBodyBuffer.append("<a href=\"externallink.jsp?schema=");
    435                 _postBodyBuffer.append(sanitizeURL(l.schema)).append("&location=");
    436                 _postBodyBuffer.append(sanitizeURL(l.location));
    437                 _postBodyBuffer.append("\">").append(sanitizeString(l.location));
    438                 _postBodyBuffer.append(" (").append(sanitizeString(l.schema)).append(")</a> ");
    439             }
    440             _postBodyBuffer.append("<br />\n");
    441         }
    442        
    443         if (_addresses.size() > 0) {
    444             _postBodyBuffer.append("<b>Addresses:</b> ");
    445             for (int i = 0; i < _addresses.size(); i++) {
    446                 Address a = (Address)_addresses.get(i);
    447                 _postBodyBuffer.append("<a href=\"addaddress.jsp?schema=");
    448                 _postBodyBuffer.append(sanitizeURL(a.schema)).append("&location=");
    449                 _postBodyBuffer.append(sanitizeURL(a.location)).append("&name=");
    450                 _postBodyBuffer.append(sanitizeURL(a.name));
    451                 _postBodyBuffer.append("\">").append(sanitizeString(a.name));
    452             }
    453             _postBodyBuffer.append("<br />\n");
    454         }
    455        
    456         _postBodyBuffer.append("</td>\n</form>\n</tr>\n");
     449                _postBodyBuffer.append("</select>\n");
     450                _postBodyBuffer.append("<input type=\"submit\" value=\"Download\" name=\"Download\" /><br />\n");
     451            }
     452
     453            if (_blogs.size() > 0) {
     454                _postBodyBuffer.append("<b>Blog references:</b> ");
     455                for (int i = 0; i < _blogs.size(); i++) {
     456                    Blog b = (Blog)_blogs.get(i);
     457                    _postBodyBuffer.append("<a href=\"").append(getPageURL(new Hash(Base64.decode(b.hash)), b.tag, b.entryId, -1, -1, (_user != null ? _user.getShowExpanded() : false), (_user != null ? _user.getShowImages() : false)));
     458                    _postBodyBuffer.append("\">").append(sanitizeString(b.name)).append("</a> ");
     459                }
     460                _postBodyBuffer.append("<br />\n");
     461            }
     462
     463            if (_links.size() > 0) {
     464                _postBodyBuffer.append("<b>External links:</b> ");
     465                for (int i = 0; i < _links.size(); i++) {
     466                    Link l = (Link)_links.get(i);
     467                    _postBodyBuffer.append("<a href=\"externallink.jsp?schema=");
     468                    _postBodyBuffer.append(sanitizeURL(l.schema)).append("&location=");
     469                    _postBodyBuffer.append(sanitizeURL(l.location));
     470                    _postBodyBuffer.append("\">").append(sanitizeString(l.location));
     471                    _postBodyBuffer.append(" (").append(sanitizeString(l.schema)).append(")</a> ");
     472                }
     473                _postBodyBuffer.append("<br />\n");
     474            }
     475
     476            if (_addresses.size() > 0) {
     477                _postBodyBuffer.append("<b>Addresses:</b> ");
     478                for (int i = 0; i < _addresses.size(); i++) {
     479                    Address a = (Address)_addresses.get(i);
     480                    _postBodyBuffer.append("<a href=\"addaddress.jsp?schema=");
     481                    _postBodyBuffer.append(sanitizeURL(a.schema)).append("&location=");
     482                    _postBodyBuffer.append(sanitizeURL(a.location)).append("&name=");
     483                    _postBodyBuffer.append(sanitizeURL(a.name));
     484                    _postBodyBuffer.append("\">").append(sanitizeString(a.name));
     485                }
     486                _postBodyBuffer.append("<br />\n");
     487            }
     488
     489            _postBodyBuffer.append("</td>\n</form>\n</tr>\n");
     490        }
    457491        _postBodyBuffer.append("</table>\n");
    458492    }
     
    464498   
    465499    public void receiveHeaderEnd() {
     500        _preBodyBuffer.append("<table width=\"100%\" border=\"0\">\n");
     501        renderSubjectCell();
    466502        renderMetaCell();
    467         renderSubjectCell();
    468503        renderPreBodyCell();
    469504    }
     
    474509   
    475510    private void renderSubjectCell() {
    476         _preBodyBuffer.append("<td align=\"left\" valign=\"top\" style=\"entry.subject.cell\" bgcolor=\"#3355ff\">");
     511        _preBodyBuffer.append("<tr class=\"syndieEntrySubjectCell\"><td align=\"left\" valign=\"top\" class=\"syndieEntrySubjectCell\" width=\"400\"> ");
    477512        String subject = (String)_headers.get(HEADER_SUBJECT);
    478513        if (subject == null)
    479514            subject = "[no subject]";
    480515        _preBodyBuffer.append(sanitizeString(subject));
    481         _preBodyBuffer.append("</td></tr>\n");
     516        _preBodyBuffer.append("</td>\n");
    482517    }
    483518   
     
    485520        String bgcolor = (String)_headers.get(HEADER_BGCOLOR);
    486521        if (_cutBody)
    487             _preBodyBuffer.append("<tr><td align=\"left\" valign=\"top\" style=\"entry.summary.cell\" bgcolor=\"" + (bgcolor == null ? "#33ffff" : sanitizeTagParam(bgcolor)) + "\">");
     522            _preBodyBuffer.append("<tr class=\"syndieEntrySummaryCell\"><td colspan=\"2\" align=\"left\" valign=\"top\" class=\"syndieEntrySummaryCell\" " + (bgcolor != null ? "bgcolor=\"" + sanitizeTagParam(bgcolor) + "\"" : "") + "\">");
    488523        else
    489             _preBodyBuffer.append("<tr><td align=\"left\" valign=\"top\" style=\"entry.body.cell\" bgcolor=\"" + (bgcolor == null ? "#33ffff" : sanitizeTagParam(bgcolor)) + "\">");
     524            _preBodyBuffer.append("<tr class=\"syndieEntryBodyCell\"><td colspan=\"2\" align=\"left\" valign=\"top\" class=\"syndieEntryBodyCell\" " + (bgcolor != null ? "bgcolor=\"" + sanitizeTagParam(bgcolor) + "\"" : "") + "\">");
    490525    }
    491526   
    492527    private void renderMetaCell() {
    493         _preBodyBuffer.append("<table width=\"100%\" border=\"0\">\n");
    494         _preBodyBuffer.append("<tr><td align=\"left\" valign=\"top\" rowspan=\"3\" style=\"entry.meta.cell\" bgcolor=\"#33ccff\">\n");
     528        _preBodyBuffer.append("<td nowrap=\"true\" align=\"right\" valign=\"top\" class=\"syndieEntryMetaCell\">\n");
    495529        BlogInfo info = null;
    496530        if (_entry != null)
     
    507541            _preBodyBuffer.append("[unknown blog]");
    508542        }
    509         _preBodyBuffer.append("<br />\n");
    510543        String tags[] = (_entry != null ? _entry.getTags() : null);
    511         _preBodyBuffer.append("<i>");
    512         for (int i = 0; tags != null && i < tags.length; i++) {
    513             _preBodyBuffer.append("<a href=\"");
    514             _preBodyBuffer.append(getPageURL(_entry.getURI().getKeyHash(), tags[i], -1, -1, -1, (_user != null ? _user.getShowExpanded() : false), (_user != null ? _user.getShowImages() : false)));
    515             _preBodyBuffer.append("\">");
    516             _preBodyBuffer.append(sanitizeString(tags[i]));
    517             _preBodyBuffer.append("</a>");
    518             if (i + 1 < tags.length)
    519                 _preBodyBuffer.append(", ");
    520         }
    521         _preBodyBuffer.append("</i><br /><font size=\"-1\">\n");
     544        if ( (tags != null) && (tags.length > 0) ) {
     545            _preBodyBuffer.append(" Tags: ");
     546            _preBodyBuffer.append("<i>");
     547            for (int i = 0; tags != null && i < tags.length; i++) {
     548                _preBodyBuffer.append("<a href=\"");
     549                _preBodyBuffer.append(getPageURL(_entry.getURI().getKeyHash(), tags[i], -1, -1, -1, (_user != null ? _user.getShowExpanded() : false), (_user != null ? _user.getShowImages() : false)));
     550                _preBodyBuffer.append("\">");
     551                _preBodyBuffer.append(sanitizeString(tags[i]));
     552                _preBodyBuffer.append("</a>");
     553                if (i + 1 < tags.length)
     554                    _preBodyBuffer.append(", ");
     555            }
     556            _preBodyBuffer.append("</i>");
     557        }
     558        _preBodyBuffer.append(" ");
    522559        if (_entry != null)
    523560            _preBodyBuffer.append(getEntryDate(_entry.getURI().getEntryId()));
    524561        else
    525562            _preBodyBuffer.append(getEntryDate(new Date().getTime()));
    526         _preBodyBuffer.append("</font><br />");
    527563        String inReplyTo = (String)_headers.get(HEADER_IN_REPLY_TO);
    528         System.err.println("In reply to: [" + inReplyTo + "]");
    529564        if ( (inReplyTo != null) && (inReplyTo.trim().length() > 0) )
    530             _preBodyBuffer.append("<a href=\"").append(getPageURL(sanitizeTagParam(inReplyTo))).append("\">In reply to</a><br />\n");
     565            _preBodyBuffer.append(" <a href=\"").append(getPageURL(sanitizeTagParam(inReplyTo))).append("\">In reply to</a>\n");
    531566        if ( (_user != null) && (_user.getAuthenticated()) )
    532             _preBodyBuffer.append("<a href=\"").append(getPostURL(_user.getBlog(), true)).append("\">Reply</a><br />\n");
    533         _preBodyBuffer.append("\n</td>\n");
     567            _preBodyBuffer.append(" <a href=\"").append(getPostURL(_user.getBlog(), true)).append("\">Reply</a>\n");
     568        _preBodyBuffer.append("\n</td></tr>\n");
    534569    }
    535570   
     
    540575                String str = _dateFormat.format(new Date(when));
    541576                long dayBegin = _dateFormat.parse(str).getTime();
    542                 return str + "<br />" + (when - dayBegin);
     577                return str + "." + (when - dayBegin);
    543578            } catch (ParseException pe) {
    544579                pe.printStackTrace();
     
    549584    }
    550585   
    551     public static final String sanitizeString(String str) {
     586    public static final String sanitizeString(String str) { return sanitizeString(str, true); }
     587    public static final String sanitizeString(String str, boolean allowNL) {
    552588        if (str == null) return null;
    553         if ( (str.indexOf('<') < 0) && (str.indexOf('>') < 0) )
    554             return str;
     589        boolean unsafe = false;
     590        unsafe = unsafe || str.indexOf('<') >= 0;
     591        unsafe = unsafe || str.indexOf('>') >= 0;
     592        if (!allowNL) {
     593            unsafe = unsafe || str.indexOf('\n') >= 0;
     594            unsafe = unsafe || str.indexOf('\r') >= 0;
     595            unsafe = unsafe || str.indexOf('\f') >= 0;
     596        }
     597        if (!unsafe) return str;
     598       
    555599        str = str.replace('<', '_');
    556600        str = str.replace('>', '-');
     601        if (!allowNL) {
     602            str = str.replace('\n', ' ');
     603            str = str.replace('\r', ' ');
     604            str = str.replace('\f', ' ');
     605        }
    557606        return str;
    558607    }
     
    576625    }
    577626
    578     private String getAttachmentURLBase() { return "viewattachment.jsp"; }
    579     private String getAttachmentURL(int id) {
     627    protected String getAttachmentURLBase() { return "viewattachment.jsp"; }
     628    protected String getAttachmentURL(int id) {
    580629        if (_entry == null) return "unknown";
    581630        return getAttachmentURLBase() + "?" +
  • apps/syndie/java/src/net/i2p/syndie/web/ArchiveViewerBean.java

    rc7b75df3 r1a6b49c  
    8080    public static final String SEL_ENTRY = "entry://";
    8181    public static final String SEL_GROUP = "group://";
     82    /** submit field for the selector form */
     83    public static final String PARAM_SELECTOR_ACTION = "action";
     84    public static final String SEL_ACTION_SET_AS_DEFAULT = "Set as default";
    8285   
    8386    public static void renderBlogSelector(User user, Map parameters, Writer out) throws IOException {
     87        String sel = getString(parameters, PARAM_SELECTOR);
     88        String action = getString(parameters, PARAM_SELECTOR_ACTION);
     89        if ( (sel != null) && (action != null) && (SEL_ACTION_SET_AS_DEFAULT.equals(action)) ) {
     90            user.setDefaultSelector(HTMLRenderer.sanitizeString(sel, false));
     91            BlogManager.instance().saveUser(user);
     92        }
     93       
    8494        out.write("<select name=\"");
    8595        out.write(PARAM_SELECTOR);
     96        out.write("\">");
     97        out.write("<option value=\"");
     98        out.write(getDefaultSelector(user, parameters));
     99        out.write("\">Default blog filter</option>\n");
    86100        out.write("\">");
    87101        out.write("<option value=\"");
     
    158172    }
    159173   
     174    private static String getDefaultSelector(User user, Map parameters) {
     175        if ( (user == null) || (user.getDefaultSelector() == null) )
     176            return BlogManager.instance().getArchive().getDefaultSelector();
     177        else
     178            return user.getDefaultSelector();
     179    }
     180   
    160181    public static void renderBlogs(User user, Map parameters, Writer out) throws IOException {
    161182        String blogStr = getString(parameters, PARAM_BLOG);
     
    175196       
    176197        String sel = getString(parameters, PARAM_SELECTOR);
     198        if ( (sel == null) && (blog == null) && (group == null) && (tag == null) )
     199            sel = getDefaultSelector(user, parameters);
    177200        if (sel != null) {
    178201            Selector s = new Selector(sel);
     
    350373    }
    351374   
    352     private static final String getString(Map parameters, String param) {
     375    public static final String getString(Map parameters, String param) {
    353376        if ( (parameters == null) || (parameters.get(param) == null) )
    354377            return null;
     
    366389            else
    367390                return null;
     391        } else {
     392            return null;
     393        }
     394    }
     395    public static final String[] getStrings(Map parameters, String param) {
     396        if ( (parameters == null) || (parameters.get(param) == null) )
     397            return null;
     398        Object vals = parameters.get(param);
     399        if (vals.getClass().isArray()) {
     400            return (String[])vals;
     401        } else if (vals instanceof Collection) {
     402            Collection c = (Collection)vals;
     403            if (c.size() <= 0) return null;
     404            String rv[] = new String[c.size()];
     405            int i = 0;
     406            for (Iterator iter = c.iterator(); iter.hasNext(); i++)
     407                rv[i] = (String)iter.next();
     408            return rv;
    368409        } else {
    369410            return null;
  • apps/syndie/jsp/_bodyindex.jsp

    rc7b75df3 r1a6b49c  
    33<form action="index.jsp">
    44<b>Blogs:</b> <%ArchiveViewerBean.renderBlogSelector(user, request.getParameterMap(), out);%>
    5 <input type="submit" value="Refresh" /></form>
     5<input type="submit" value="Refresh" />
     6<input type="submit" name="action" value="<%=ArchiveViewerBean.SEL_ACTION_SET_AS_DEFAULT%>" /></form>
    67<hr />
    78
  • apps/syndie/jsp/_topnav.jsp

    rc7b75df3 r1a6b49c  
    1 <td valign="top" align="left" bgcolor="#cccc88" height="10"><a href="index.jsp">Blogs</a></td>
    2 <td valign="top" align="left" bgcolor="#cccc88" height="10">Remote archives</td>
    3 <td valign="top" align="left" bgcolor="#cccc88" height="10">Manage</td>
     1<td valign="top" align="left" class="syndieTopNavBlogsCell" height="10"><a href="index.jsp">Blogs</a></td>
     2<td valign="top" align="left" class="syndieTopNavRemoteCell" height="10"><a href="remote.jsp">Remote archives</a></td>
     3<td valign="top" align="left" class="syndieTopNavManageCell" height="10">Manage</td>
  • apps/syndie/jsp/addaddress.jsp

    rc7b75df3 r1a6b49c  
    44<head>
    55<title>SyndieMedia</title>
     6<link href="style.jsp" rel="stylesheet" type="text/css" />
    67</head>
    78<body>
  • apps/syndie/jsp/externallink.jsp

    rc7b75df3 r1a6b49c  
    33<head>
    44<title>SyndieMedia</title>
     5<link href="style.jsp" rel="stylesheet" type="text/css" />
    56</head>
    67<body>
  • apps/syndie/jsp/index.jsp

    rc7b75df3 r1a6b49c  
    33<head>
    44<title>SyndieMedia</title>
     5<link href="style.jsp" rel="stylesheet" type="text/css" />
    56</head>
    67<body>
  • apps/syndie/jsp/post.jsp

    rc7b75df3 r1a6b49c  
    11<%@page import="net.i2p.data.Base64, net.i2p.syndie.web.*, net.i2p.syndie.sml.*, net.i2p.syndie.data.*, net.i2p.syndie.*, org.mortbay.servlet.MultiPartRequest, java.util.*" %>
    22<jsp:useBean scope="session" class="net.i2p.syndie.User" id="user" />
     3<jsp:useBean scope="session" class="net.i2p.syndie.web.PostBean" id="post" />
    34<html>
    45<head>
    56<title>SyndieMedia</title>
     7<link href="style.jsp" rel="stylesheet" type="text/css" />
    68</head>
    79<body>
     
    1315<tr><td valign="top" align="left" colspan="3"><%
    1416
    15 String contentType = request.getContentType();
    16 if ((contentType != null) && (contentType.indexOf("boundary=") != -1) ) {
    17   if (!user.getAuthenticated()) { %>You must be logged in to post<%
     17if (!user.getAuthenticated()) {
     18  %>You must be logged in to post<%
     19} else {
     20  String confirm = request.getParameter("confirm");
     21  if ( (confirm != null) && (confirm.equalsIgnoreCase("true")) ) {
     22    BlogURI uri = post.postEntry();
     23    if (uri != null) {
     24      %>Blog entry <a href="<%=HTMLRenderer.getPageURL(user.getBlog(), null, uri.getEntryId(), -1, -1,
     25                                                        user.getShowExpanded(), user.getShowImages())%>">posted</a>!<%
     26    } else {
     27      %>There was an unknown error posting the entry...<%
     28    }
     29    post.reinitialize();
     30    post.setUser(user);
    1831  } else {
    19     MultiPartRequest req = new MultiPartRequest(request);
    20     String entrySubject = req.getString("entrysubject");
    21     String entryTags = req.getString("entrytags");
    22     String entryText = req.getString("entrytext");
    23     String entryHeaders = req.getString("entryheaders");
    24     String replyTo = req.getString(ArchiveViewerBean.PARAM_IN_REPLY_TO);
    25     if ( (replyTo != null) && (replyTo.trim().length() > 0) ) {
    26       byte r[] = Base64.decode(replyTo);
    27       if (r != null) {
    28         if (entryHeaders == null) entryHeaders = HTMLRenderer.HEADER_IN_REPLY_TO + ": " + new String(r);
    29         else entryHeaders = entryHeaders + '\n' + HTMLRenderer.HEADER_IN_REPLY_TO + ": " + new String(r);
    30       } else {
    31         replyTo = null;
    32       }
    33     }
    34    
    35     List fileStreams = new ArrayList();
    36     List fileNames = new ArrayList();
    37     List fileTypes = new ArrayList();
    38     for (int i = 0; i < 32; i++) {
    39       String filename = req.getFilename("entryfile" + i);
    40       if ( (filename != null) && (filename.trim().length() > 0) ) {
    41         fileNames.add(filename.trim());
    42         fileStreams.add(req.getInputStream("entryfile" + i));
    43         Hashtable params = req.getParams("entryfile" + i);
    44         String type = "application/octet-stream";
    45         for (Iterator iter = params.keySet().iterator(); iter.hasNext(); ) {
    46           String cur = (String)iter.next();
    47           if ("content-type".equalsIgnoreCase(cur)) {
    48             type = (String)params.get(cur);
    49             break;
     32    // logged in but not confirmed...
     33    String contentType = request.getContentType();
     34    if ((contentType != null) && (contentType.indexOf("boundary=") != -1) ) {
     35        // not confirmed but they posted stuff... gobble up what they give
     36        // and display it as a preview (then we show the confirm form)
     37        post.reinitialize();
     38        post.setUser(user);
     39       
     40        MultiPartRequest req = new MultiPartRequest(request);
     41        String entrySubject = req.getString("entrysubject");
     42        String entryTags = req.getString("entrytags");
     43        String entryText = req.getString("entrytext");
     44        String entryHeaders = req.getString("entryheaders");
     45        String replyTo = req.getString(ArchiveViewerBean.PARAM_IN_REPLY_TO);
     46        if ( (replyTo != null) && (replyTo.trim().length() > 0) ) {
     47          byte r[] = Base64.decode(replyTo);
     48          if (r != null) {
     49            if (entryHeaders == null) entryHeaders = HTMLRenderer.HEADER_IN_REPLY_TO + ": " + new String(r);
     50            else entryHeaders = entryHeaders + '\n' + HTMLRenderer.HEADER_IN_REPLY_TO + ": " + new String(r);
     51          } else {
     52            replyTo = null;
    5053          }
    5154        }
    52         fileTypes.add(type);
    53       }
    54     }
    55    
    56     BlogURI entry = BlogManager.instance().createBlogEntry(user, entrySubject, entryTags, entryHeaders, entryText, fileNames, fileStreams, fileTypes);
    57     if (entry != null) {
    58       // it has been rebuilt...
    59       request.setAttribute("index", BlogManager.instance().getArchive().getIndex());
    60 %>
    61 Blog entry <a href="<%=HTMLRenderer.getPageURL(user.getBlog(), null, entry.getEntryId(), -1, -1, user.getShowExpanded(), user.getShowImages())%>">posted</a>!
    62 <%   } else { %>
    63 There was an error posting... dunno what it was...
    64 <%   } 
    65   }
    66 } else { %><form action="post.jsp" method="POST" enctype="multipart/form-data">
    67 Post subject: <input type="text" size="80" name="entrysubject" /><br />
    68 Post tags: <input type="text" size="20" name="entrytags" /><br />
     55
     56        post.setSubject(entrySubject);
     57        post.setTags(entryTags);
     58        post.setText(entryText);
     59        post.setHeaders(entryHeaders);
     60
     61        for (int i = 0; i < 32; i++) {
     62          String filename = req.getFilename("entryfile" + i);
     63          if ( (filename != null) && (filename.trim().length() > 0) ) {
     64            Hashtable params = req.getParams("entryfile" + i);
     65            String type = "application/octet-stream";
     66            for (Iterator iter = params.keySet().iterator(); iter.hasNext(); ) {
     67              String cur = (String)iter.next();
     68              if ("content-type".equalsIgnoreCase(cur)) {
     69                type = (String)params.get(cur);
     70                break;
     71              }
     72            }
     73            post.addAttachment(filename.trim(), req.getInputStream("entryfile" + i), type);
     74          }
     75        }
     76
     77        post.renderPreview(out);
     78        %><hr />Please <a href="post.jsp?confirm=true">confirm</a> that this is ok.  Otherwise, just go back and make changes.<%
     79    } else {
     80      // logged in and not confirmed because they didn't send us anything! 
     81      // give 'em a new form
     82%><form action="post.jsp" method="POST" enctype="multipart/form-data">
     83Post subject: <input type="text" size="80" name="entrysubject" value="<%=post.getSubject()%>" /><br />
     84Post tags: <input type="text" size="20" name="entrytags" value="<%=post.getTags()%>" /><br />
    6985Post content (in raw SML, no headers):<br />
    70 <textarea rows="6" cols="80" name="entrytext"></textarea><br />
     86<textarea rows="6" cols="80" name="entrytext"><%=post.getText()%></textarea><br />
    7187<b>SML cheatsheet:</b><br /><textarea rows="6" cols="80" readonly="true">
    7288* newlines are newlines are newlines.
     
    89105</textarea><br />
    90106SML post headers:<br />
    91 <textarea rows="3" cols="80" name="entryheaders"></textarea><br /><%
     107<textarea rows="3" cols="80" name="entryheaders"><%=post.getHeaders()%></textarea><br /><%
    92108String s = request.getParameter(ArchiveViewerBean.PARAM_IN_REPLY_TO);
    93109if ( (s != null) && (s.trim().length() > 0) ) {%>
     
    106122Attachment 9: <input type="file" name="entryfile9" /><br />
    107123<hr />
    108 <input type="submit" name="Post" value="Post entry" /> <input type="reset" value="Cancel" />
    109 <% } %>
    110 </td></tr>
     124<input type="submit" name="Post" value="Preview..." /> <input type="reset" value="Cancel" />
     125<%
     126    } // end of the 'logged in, not confirmed, nothing posted' section
     127  } // end of the 'logged in, not confirmed' section
     128} // end of the 'logged in' section
     129%></td></tr>
    111130</table>
    112131</body>
  • apps/syndie/jsp/register.jsp

    rc7b75df3 r1a6b49c  
    44<head>
    55<title>SyndieMedia</title>
     6<link href="style.jsp" rel="stylesheet" type="text/css" />
    67</head>
    78<body>
  • apps/syndie/jsp/viewmetadata.jsp

    rc7b75df3 r1a6b49c  
    33<head>
    44<title>SyndieMedia</title>
     5<link href="style.jsp" rel="stylesheet" type="text/css" />
    56</head>
    67<body>
  • build.xml

    rc7b75df3 r1a6b49c  
    6060        <copy file="apps/addressbook/dist/addressbook.war" todir="build/" />
    6161        <copy file="apps/susimail/susimail.war" todir="build/" />
     62        <copy file="apps/syndie/syndie.war" todir="build/" />
    6263        <copy file="apps/syndie/java/build/syndie.jar" todir="build/" />
    6364        <copy file="apps/syndie/syndie.war" todir="build/" />
     
    189190        <copy file="build/addressbook.war" todir="pkg-temp/webapps/" />
    190191        <copy file="build/susimail.war" todir="pkg-temp/webapps/" />
     192        <copy file="build/syndie.war" todir="pkg-temp/webapps/" />
    191193        <copy file="installer/resources/clients.config" todir="pkg-temp/" />
    192194        <copy file="installer/resources/eepget" todir="pkg-temp/" />
     
    287289        <copy file="build/addressbook.war" todir="pkg-temp/webapps/" />
    288290        <copy file="build/susimail.war" todir="pkg-temp/webapps/" />
     291        <copy file="build/syndie.war" todir="pkg-temp/webapps/" />
    289292        <copy file="history.txt" todir="pkg-temp/" />
    290293        <mkdir dir="pkg-temp/docs/" />
  • core/java/src/net/i2p/data/Base64.java

    rc7b75df3 r1a6b49c  
    153153    private static void runApp(String args[]) {
    154154        try {
     155            if ("encodestring".equalsIgnoreCase(args[0])) {
     156                System.out.println(encode(args[1].getBytes()));
     157                return;
     158            }
    155159            InputStream in = System.in;
    156160            OutputStream out = System.out;
  • history.txt

    rc7b75df3 r1a6b49c  
    1 $Id: history.txt,v 1.227 2005/08/17 15:05:03 jrandom Exp $
     1$Id: history.txt,v 1.228 2005/08/21 13:39:06 jrandom Exp $
     2
     32005-08-23  jrandom
     4    * Removed the concept of "no bandwidth limit" - if none is specified, its
     5      16KBps in/out.
     6    * Include ack packets in the per-peer cwin throttle (they were part of the
     7      bandwidth limit though).
     8    * Tweak the SSU cwin operation to get more accurrate estimates under
     9      congestions.
     10    * SSU improvements to resend more efficiently.
     11    * Added a basic scheduler to eepget to fetch multiple files sequentially.
    212
    313* 2005-08-21  0.6.0.3 released
  • router/java/src/net/i2p/router/RouterVersion.java

    rc7b75df3 r1a6b49c  
    1616 */
    1717public class RouterVersion {
    18     public final static String ID = "$Revision: 1.216 $ $Date: 2005/08/17 15:05:03 $";
     18    public final static String ID = "$Revision: 1.217 $ $Date: 2005/08/21 13:39:05 $";
    1919    public final static String VERSION = "0.6.0.3";
    20     public final static long BUILD = 0;
     20    public final static long BUILD = 1;
    2121    public static void main(String args[]) {
    2222        System.out.println("I2P Router version: " + VERSION);
  • router/java/src/net/i2p/router/transport/FIFOBandwidthLimiter.java

    rc7b75df3 r1a6b49c  
    120120    final void refillBandwidthQueues(long bytesInbound, long bytesOutbound) {
    121121        if (_log.shouldLog(Log.DEBUG))
    122             _log.debug("Refilling the queues with " + bytesInbound + "/" + bytesOutbound);
     122            _log.debug("Refilling the queues with " + bytesInbound + "/" + bytesOutbound + ", available " +
     123                       _availableInboundBytes + '/' + _availableOutboundBytes + ", max " +
     124                       _maxInboundBytes + '/' + _maxOutboundBytes);
    123125        _availableInboundBytes += bytesInbound;
    124126        _availableOutboundBytes += bytesOutbound;
  • router/java/src/net/i2p/router/transport/FIFOBandwidthRefiller.java

    rc7b75df3 r1a6b49c  
    2626    public static final String PROP_OUTBOUND_BANDWIDTH_PEAK = "i2np.bandwidth.outboundBurstKBytes";
    2727    //public static final String PROP_REPLENISH_FREQUENCY = "i2np.bandwidth.replenishFrequencyMs";
    28  
     28
     29    // no longer allow unlimited bandwidth - the user must specify a value, and if they do not, it is 16KBps
     30    public static final int DEFAULT_INBOUND_BANDWIDTH = 16;
     31    public static final int DEFAULT_OUTBOUND_BANDWIDTH = 16;
     32
     33    public static final int DEFAULT_BURST_SECONDS = 60;
     34   
    2935    /** For now, until there is some tuning and safe throttling, we set the floor at 6KBps inbound */
    30     public static final int MIN_INBOUND_BANDWIDTH = 1;
     36    public static final int MIN_INBOUND_BANDWIDTH = 5;
    3137    /** For now, until there is some tuning and safe throttling, we set the floor at 6KBps outbound */
    32     public static final int MIN_OUTBOUND_BANDWIDTH = 1;
     38    public static final int MIN_OUTBOUND_BANDWIDTH = 5;
    3339    /** For now, until there is some tuning and safe throttling, we set the floor at a 10 second burst */
    34     public static final int MIN_INBOUND_BANDWIDTH_PEAK = 1;
     40    public static final int MIN_INBOUND_BANDWIDTH_PEAK = 10;
    3541    /** For now, until there is some tuning and safe throttling, we set the floor at a 10 second burst */
    36     public static final int MIN_OUTBOUND_BANDWIDTH_PEAK = 1;
     42    public static final int MIN_OUTBOUND_BANDWIDTH_PEAK = 10;
    3743    /** Updating the bandwidth more than once a second is silly.  once every 2 or 5 seconds is less so. */
    3844    public static final long MIN_REPLENISH_FREQUENCY = 100;
     
    147153                else
    148154                    _inboundKBytesPerSecond = MIN_INBOUND_BANDWIDTH;
     155                if (_log.shouldLog(Log.DEBUG))
     156                    _log.debug("Updating inbound rate to " + _inboundKBytesPerSecond);
    149157            } catch (NumberFormatException nfe) {
    150158                if (_log.shouldLog(Log.WARN))
     
    156164                _log.debug("Inbound bandwidth limits not specified in the config via " + PROP_INBOUND_BANDWIDTH);
    157165        }
     166       
     167        if (_inboundKBytesPerSecond <= 0)
     168            _inboundKBytesPerSecond = DEFAULT_INBOUND_BANDWIDTH;
    158169    }
    159170    private void updateOutboundRate() {
     
    170181                else
    171182                    _outboundKBytesPerSecond = MIN_OUTBOUND_BANDWIDTH;
     183                if (_log.shouldLog(Log.DEBUG))
     184                    _log.debug("Updating outbound rate to " + _outboundKBytesPerSecond);
    172185            } catch (NumberFormatException nfe) {
    173186                if (_log.shouldLog(Log.WARN))
     
    179192                _log.debug("Outbound bandwidth limits not specified in the config via " + PROP_OUTBOUND_BANDWIDTH);
    180193        }
     194       
     195        if (_outboundKBytesPerSecond <= 0)
     196            _outboundKBytesPerSecond = DEFAULT_OUTBOUND_BANDWIDTH;
    181197    }
    182198   
     
    204220                    _log.warn("Invalid inbound bandwidth burst limit [" + inBwStr
    205221                              + "]");
     222                _limiter.setMaxInboundBytes(DEFAULT_BURST_SECONDS * _inboundKBytesPerSecond * 1024);
    206223            }
    207224        } else {
     
    209226                _log.debug("Inbound bandwidth burst limits not specified in the config via "
    210227                           + PROP_INBOUND_BANDWIDTH_PEAK);
     228            _limiter.setMaxInboundBytes(DEFAULT_BURST_SECONDS * _inboundKBytesPerSecond * 1024);
    211229        }
    212230    }
     
    234252                    _log.warn("Invalid outbound bandwidth burst limit [" + outBwStr
    235253                              + "]");
     254                _limiter.setMaxOutboundBytes(DEFAULT_BURST_SECONDS * _outboundKBytesPerSecond * 1024);
    236255            }
    237256        } else {
     
    239258                _log.debug("Outbound bandwidth burst limits not specified in the config via "
    240259                           + PROP_OUTBOUND_BANDWIDTH_PEAK);
     260            _limiter.setMaxOutboundBytes(DEFAULT_BURST_SECONDS * _outboundKBytesPerSecond * 1024);
    241261        }
    242262    }
  • router/java/src/net/i2p/router/transport/udp/EstablishmentManager.java

    rc7b75df3 r1a6b49c  
    576576            if (outboundState.getLifetime() > MAX_ESTABLISH_TIME) {
    577577                if (outboundState.getState() != OutboundEstablishState.STATE_CONFIRMED_COMPLETELY) {
     578                    if (_log.shouldLog(Log.WARN))
     579                        _log.warn("Lifetime of expired outbound establish: " + outboundState.getLifetime());
    578580                    while (true) {
    579581                        OutNetMessage msg = outboundState.getNextQueuedMessage();
  • router/java/src/net/i2p/router/transport/udp/OutboundMessageFragments.java

    rc7b75df3 r1a6b49c  
    327327                state.push();
    328328           
    329                 int rto = peer.getRTO() * state.getPushCount();
     329                int rto = peer.getRTO();// * state.getPushCount();
    330330                state.setNextSendTime(now + rto);
    331331
     
    339339                              + " available=" + peer.getSendWindowBytesRemaining()
    340340                              + " for message " + state.getMessageId() + ": " + state);
    341                 state.setNextSendTime((now + 1024) & ~SECOND_MASK);
     341                state.setNextSendTime(now+(_context.random().nextInt(2*ACKSender.ACK_FREQUENCY))); //(now + 1024) & ~SECOND_MASK);
    342342                if (_log.shouldLog(Log.WARN))
    343343                    _log.warn("Retransmit after choke for next send time in " + (state.getNextSendTime()-now) + "ms");
     
    436436            if (peer != null) {
    437437                // this adjusts the rtt/rto/window/etc
    438                 peer.messageACKed(numFragments*state.getFragmentSize(), state.getLifetime(), state.getMaxSends());
     438                peer.messageACKed(numFragments*state.getFragmentSize(), state.getLifetime(), numSends);
    439439                if (peer.getSendWindowBytesRemaining() > 0)
    440440                    _throttle.unchoke(peer.getRemotePeer());
  • router/java/src/net/i2p/router/transport/udp/PeerState.java

    rc7b75df3 r1a6b49c  
    9494    private int _receiveBps;
    9595    private int _receiveBytes;
     96    private int _sendACKBps;
     97    private int _sendACKBytes;
     98    private int _receiveACKBps;
     99    private int _receiveACKBytes;
    96100    private long _receivePeriodBegin;
    97101    private volatile long _lastCongestionOccurred;
     
    142146    /** how many packets were retransmitted within the last RETRANSMISSION_PERIOD_WIDTH packets */
    143147    private long _packetsRetransmitted;
     148    /** how many packets were transmitted within the last RETRANSMISSION_PERIOD_WIDTH packets */
     149    private long _packetsPeriodTransmitted;
     150    private int _packetsPeriodRetransmitted;
    144151    private int _packetRetransmissionRate;
    145     /** what was the $packetsTransmitted when the current RETRANSMISSION_PERIOD_WIDTH began */
     152    /** at what time did we last break off the retransmission counter period */
    146153    private long _retransmissionPeriodStart;
    147154    /** how many dup packets were received within the last RETRANSMISSION_PERIOD_WIDTH packets */
     
    164171     */
    165172    private static final int DEFAULT_MTU = 608;//600; //1500;
    166     private static final int MIN_RTO = 1000 + ACKSender.ACK_FREQUENCY;
     173    private static final int MIN_RTO = 500 + ACKSender.ACK_FREQUENCY;
    167174    private static final int MAX_RTO = 3000; // 5000;
    168175   
     
    374381    }
    375382   
     383    /** how fast we are sending *ack* packets */
     384    public int getSendACKBps() { return _sendACKBps; }
     385    public int getReceiveACKBps() { return _receiveACKBps; }
     386   
    376387    /**
    377388     * have all of the packets received in the current second requested that
     
    385396     * not adjusted at all.
    386397     */
    387     public boolean allocateSendingBytes(int size) {
     398    public boolean allocateSendingBytes(int size) { return allocateSendingBytes(size, false); }
     399    public boolean allocateSendingBytes(int size, boolean isForACK) {
    388400        long now = _context.clock().now();
    389401        long duration = now - _lastSendRefill;
     
    392404            _sendBytes += size;
    393405            _sendBps = (int)(0.9f*(float)_sendBps + 0.1f*((float)_sendBytes * (1000f/(float)duration)));
     406            if (isForACK) {
     407                _sendACKBytes += size;
     408                _sendACKBps = (int)(0.9f*(float)_sendACKBps + 0.1f*((float)_sendACKBytes * (1000f/(float)duration)));
     409            }
    394410            _sendBytes = 0;
     411            _sendACKBytes = 0;
    395412            _lastSendRefill = now;
    396413        }
     
    400417            _sendBytes += size;
    401418            _lastSendTime = now;
     419            if (isForACK)
     420                _sendACKBytes += size;
    402421            return true;
    403422        } else {
     
    433452   
    434453    /** we received the message specified completely */
    435     public void messageFullyReceived(Long messageId, int bytes) {
    436         if (bytes > 0)
     454    public void messageFullyReceived(Long messageId, int bytes) { messageFullyReceived(messageId, bytes, false); }
     455    public void messageFullyReceived(Long messageId, int bytes, boolean isForACK) {
     456        if (bytes > 0) {
    437457            _receiveBytes += bytes;
    438         else {
    439             if (_retransmissionPeriodStart + RETRANSMISSION_PERIOD_WIDTH < _packetsReceived) {
     458            if (isForACK)
     459                _receiveACKBytes += bytes;
     460        } else {
     461            if (_retransmissionPeriodStart + 1000 < _context.clock().now()) {
    440462                _packetsReceivedDuplicate++;
    441463            } else {
    442                 _retransmissionPeriodStart = _packetsReceived;
     464                _retransmissionPeriodStart = _context.clock().now();
    443465                _packetsReceivedDuplicate = 1;
    444466            }
     
    449471        if (duration >= 1000) {
    450472            _receiveBps = (int)(0.9f*(float)_receiveBps + 0.1f*((float)_receiveBytes * (1000f/(float)duration)));
     473            if (isForACK)
     474                _receiveACKBps = (int)(0.9f*(float)_receiveACKBps + 0.1f*((float)_receiveACKBytes * (1000f/(float)duration)));
     475            _receiveACKBytes = 0;
    451476            _receiveBytes = 0;
    452477            _receivePeriodBegin = now;
     
    481506    private boolean congestionOccurred() {
    482507        long now = _context.clock().now();
    483         if (_lastCongestionOccurred + 10*1000 > now)
    484             return false; // only shrink once every 10 seconds
     508        if (_lastCongestionOccurred + 5*1000 > now)
     509            return false; // only shrink once every 5 seconds
    485510        _lastCongestionOccurred = now;
    486511       
    487512        _context.statManager().addRateData("udp.congestionOccurred", _sendWindowBytes, _sendBps);
    488513       
     514        int congestionAt = _sendWindowBytes;
    489515        //if (true)
    490516        //    _sendWindowBytes -= 10000;
    491517        //else
    492             _sendWindowBytes = (_sendWindowBytes*2) / 3;
     518            _sendWindowBytes = _sendWindowBytes/4; //(_sendWindowBytes*2) / 3;
    493519        if (_sendWindowBytes < MINIMUM_WINDOW_BYTES)
    494520            _sendWindowBytes = MINIMUM_WINDOW_BYTES;
    495         if (_sendWindowBytes < _slowStartThreshold)
    496             _slowStartThreshold = _sendWindowBytes;
     521        //if (congestionAt/2 < _slowStartThreshold)
     522            _slowStartThreshold = congestionAt/2;
    497523        return true;
    498524    }
     
    596622        _consecutiveFailedSends = 0;
    597623        _lastFailedSendPeriod = -1;
    598         if (_sendWindowBytes <= _slowStartThreshold) {
    599             _sendWindowBytes += bytesACKed;
    600         } else {
    601             double prob = ((double)bytesACKed) / ((double)_sendWindowBytes);
    602             if (_context.random().nextDouble() <= prob)
     624        if (numSends < 2) {
     625            if (_sendWindowBytes <= _slowStartThreshold) {
    603626                _sendWindowBytes += bytesACKed;
     627            } else {
     628                if (false) {
     629                    _sendWindowBytes += 16; // why 16?
     630                } else {
     631                    float prob = ((float)bytesACKed) / ((float)_sendWindowBytes);
     632                    float v = _context.random().nextFloat();
     633                    if (v < 0) v = 0-v;
     634                    if (v <= prob)
     635                        _sendWindowBytes += bytesACKed;
     636                }
     637            }
    604638        }
    605639        if (_sendWindowBytes > MAX_SEND_WINDOW_BYTES)
     
    607641        _lastReceiveTime = _context.clock().now();
    608642       
    609         if (_sendWindowBytesRemaining + bytesACKed <= _sendWindowBytes)
    610             _sendWindowBytesRemaining += bytesACKed;
    611         else
    612             _sendWindowBytesRemaining = _sendWindowBytes;
     643        if (false) {
     644            if (_sendWindowBytesRemaining + bytesACKed <= _sendWindowBytes)
     645                _sendWindowBytesRemaining += bytesACKed;
     646            else
     647                _sendWindowBytesRemaining = _sendWindowBytes;
     648        }
    613649       
    614650        _messagesSent++;
    615         if (numSends <= 2)
     651        if (numSends < 2)
    616652            recalculateTimeouts(lifetime);
    617653        else
     
    644680    /** we are resending a packet, so lets jack up the rto */
    645681    public void messageRetransmitted(int packets) {
    646         if (_retransmissionPeriodStart + RETRANSMISSION_PERIOD_WIDTH < _packetsTransmitted) {
     682        long now = _context.clock().now();
     683        if (_retransmissionPeriodStart + 1000 <= now) {
    647684            _packetsRetransmitted += packets;
    648685        } else {
    649686            _packetRetransmissionRate = (int)((float)(0.9f*_packetRetransmissionRate) + (float)(0.1f*_packetsRetransmitted));
    650             _retransmissionPeriodStart = _packetsTransmitted;
     687            //_packetsPeriodTransmitted = _packetsTransmitted - _retransmissionPeriodStart;
     688            _packetsPeriodRetransmitted = (int)_packetsRetransmitted;
     689            _retransmissionPeriodStart = now;
    651690            _packetsRetransmitted = packets;
    652691        }
     
    656695    }
    657696    public void packetsTransmitted(int packets) {
     697        long now = _context.clock().now();
    658698        _packetsTransmitted += packets;
    659         if (_retransmissionPeriodStart + RETRANSMISSION_PERIOD_WIDTH > _packetsTransmitted) {
     699        //_packetsPeriodTransmitted += packets;
     700        if (_retransmissionPeriodStart + 1000 <= now) {
    660701            _packetRetransmissionRate = (int)((float)(0.9f*_packetRetransmissionRate) + (float)(0.1f*_packetsRetransmitted));
    661             _retransmissionPeriodStart = _packetsTransmitted;
     702            _retransmissionPeriodStart = 0;
     703            _packetsPeriodRetransmitted = (int)_packetsRetransmitted;
    662704            _packetsRetransmitted = 0;
    663705        }
     
    674716    public long getPacketsTransmitted() { return _packetsTransmitted; }
    675717    public long getPacketsRetransmitted() { return _packetsRetransmitted; }
     718    public long getPacketsPeriodTransmitted() { return _packetsPeriodTransmitted; }
     719    public int getPacketsPeriodRetransmitted() { return _packetsPeriodRetransmitted; }
    676720    /** avg number of packets retransmitted for every 100 packets */
    677721    public long getPacketRetransmissionRate() { return _packetRetransmissionRate; }
  • router/java/src/net/i2p/router/transport/udp/PeerTestManager.java

    rc7b75df3 r1a6b49c  
    133133    private void receiveTestReply(RemoteHostId from, UDPPacketReader.PeerTestReader testInfo) {
    134134        PeerTestState test = _currentTest;
     135        if (test == null) return;
    135136        if ( (DataHelper.eq(from.getIP(), test.getBobIP().getAddress())) && (from.getPort() == test.getBobPort()) ) {
    136137            byte ip[] = new byte[testInfo.readIPSize()];
  • router/java/src/net/i2p/router/transport/udp/UDPReceiver.java

    rc7b75df3 r1a6b49c  
    4141        _context.statManager().createRateStat("udp.receivePacketSize", "How large packets received are", "udp", new long[] { 60*1000, 10*60*1000, 60*60*1000 });
    4242        _context.statManager().createRateStat("udp.droppedInbound", "How many packet are queued up but not yet received when we drop", "udp", new long[] { 60*1000, 10*60*1000, 60*60*1000 });
     43        _context.statManager().createRateStat("udp.droppedInboundProbabalistically", "How many packet we drop probabalistically (to simulate failures)", "udp", new long[] { 60*1000, 5*60*1000, 10*60*1000, 60*60*1000 });
     44        _context.statManager().createRateStat("udp.acceptedInboundProbabalistically", "How many packet we accept probabalistically (to simulate failures)", "udp", new long[] { 60*1000, 5*60*1000, 10*60*1000, 60*60*1000 });
    4345    }
    4446   
    4547    public void startup() {
     48        adjustDropProbability();
    4649        _keepRunning = true;
    4750        I2PThread t = new I2PThread(_runner, _name);
     
    5558            _inboundQueue.clear();
    5659            _inboundQueue.notifyAll();
     60        }
     61    }
     62   
     63    private void adjustDropProbability() {
     64        String p = _context.getProperty("i2np.udp.dropProbability");
     65        if (p != null) {
     66            try {
     67                ARTIFICIAL_DROP_PROBABILITY = Float.parseFloat(p);
     68            } catch (NumberFormatException nfe) {}
     69            if (ARTIFICIAL_DROP_PROBABILITY < 0) ARTIFICIAL_DROP_PROBABILITY = 0;
     70        } else {
     71            ARTIFICIAL_DROP_PROBABILITY = 0;
    5772        }
    5873    }
     
    7085    private static final long MAX_QUEUE_PERIOD = 1*1000;
    7186   
    72     private static final float ARTIFICIAL_DROP_PROBABILITY = 0.0f; // 0.02f; // 0.0f;
     87    private static float ARTIFICIAL_DROP_PROBABILITY = 0.0f; // 0.02f; // 0.0f;
    7388   
    7489    private static final int ARTIFICIAL_DELAY = 0; // 100;
     
    7691   
    7792    private int receive(UDPPacket packet) {
     93        //adjustDropProbability();
     94       
    7895        if (ARTIFICIAL_DROP_PROBABILITY > 0) {
    7996            // the first check is to let the compiler optimize away this
    8097            // random block on the live system when the probability is == 0
    81             if (_context.random().nextFloat() <= ARTIFICIAL_DROP_PROBABILITY)
     98            int v = _context.random().nextInt(1000);
     99            if (v < ARTIFICIAL_DROP_PROBABILITY*1000) {
     100                if (_log.shouldLog(Log.ERROR))
     101                    _log.error("Drop with v=" + v + " p=" + ARTIFICIAL_DROP_PROBABILITY + " packet size: " + packet.getPacket().getLength());
     102                _context.statManager().addRateData("udp.droppedInboundProbabalistically", 1, 0);
    82103                return -1;
     104            } else {
     105                _context.statManager().addRateData("udp.acceptedInboundProbabalistically", 1, 0);
     106            }
    83107        }
    84108       
Note: See TracChangeset for help on using the changeset viewer.