~ubuntu-branches/ubuntu/precise/kompozer/precise

« back to all changes in this revision

Viewing changes to mozilla/netwerk/streamconv/converters/nsDirIndexParser.cpp

  • Committer: Bazaar Package Importer
  • Author(s): Anthony Yarusso
  • Date: 2007-08-27 01:11:03 UTC
  • Revision ID: james.westby@ubuntu.com-20070827011103-2jgf4s6532gqu2ka
Tags: upstream-0.7.10
ImportĀ upstreamĀ versionĀ 0.7.10

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 
2
/* ----- BEGIN LICENSE BLOCK -----
 
3
 * Version: NPL 1.1/GPL 2.0/LGPL 2.1
 
4
 *
 
5
 * The contents of this file are subject to the Netscape Public License Version
 
6
 * 1.1 (the "License"); you may not use this file except in compliance with
 
7
 * the License. You may obtain a copy of the License at
 
8
 * http://www.mozilla.org/NPL/
 
9
 *
 
10
 * Software distributed under the License is distributed on an "AS IS" basis,
 
11
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 
12
 * for the specific language governing rights and limitations under the
 
13
 * License.
 
14
 *
 
15
 * The Original Code is the Mozilla Communicator client code.
 
16
 *
 
17
 * The Initial Developer of the Original Code is Netscape Communications
 
18
 * Corporation.
 
19
 * Portions created by Netscape Communications Corporation are
 
20
 * Copyright (C) 1998-2001 Netscape Communications Corporation.
 
21
 * All Rights Reserved.
 
22
 *
 
23
 * Contributor(s):
 
24
 *   Chris Waterson           <waterson@netscape.com>
 
25
 *   Robert John Churchill    <rjc@netscape.com>
 
26
 *   Pierre Phaneuf           <pp@ludusdesign.com>
 
27
 *   Bradley Baetz            <bbaetz@cs.mcgill.ca>
 
28
 *
 
29
 * Alternatively, the contents of this file may be used under the terms of
 
30
 * either of the GNU General Public License Version 2 or later (the "GPL"),
 
31
 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 
32
 * in which case the provisions of the GPL or the LGPL are applicable instead
 
33
 * of those above. If you wish to allow use of your version of this file only
 
34
 * under the terms of either the GPL or the LGPL, and not to allow others to
 
35
 * use your version of this file under the terms of the MPL, indicate your
 
36
 * decision by deleting the provisions above and replace them with the notice
 
37
 * and other provisions required by the LGPL or the GPL. If you do not delete
 
38
 * the provisions above, a recipient may use your version of this file under
 
39
 * the terms of any one of the MPL, the GPL or the LGPL.
 
40
 *
 
41
 * ----- END LICENSE BLOCK ----- */
 
42
 
 
43
/* This parsing code originally lived in xpfe/components/directory/ - bbaetz */
 
44
 
 
45
#include "prprf.h"
 
46
 
 
47
#include "nsDirIndexParser.h"
 
48
#include "nsReadableUtils.h"
 
49
#include "nsDirIndex.h"
 
50
#include "nsEscape.h"
 
51
#include "nsIServiceManager.h"
 
52
#include "nsIInputStream.h"
 
53
#include "nsIChannel.h"
 
54
#include "nsIURI.h"
 
55
#include "nsCRT.h"
 
56
#include "nsIPrefService.h"
 
57
#include "nsIPrefBranch.h"
 
58
#include "nsIPrefLocalizedString.h"
 
59
 
 
60
NS_IMPL_THREADSAFE_ISUPPORTS3(nsDirIndexParser,
 
61
                              nsIRequestObserver,
 
62
                              nsIStreamListener,
 
63
                              nsIDirIndexParser)
 
64
 
 
65
nsDirIndexParser::nsDirIndexParser() {
 
66
}
 
67
 
 
68
nsresult
 
69
nsDirIndexParser::Init() {
 
70
  mLineStart = 0;
 
71
  mHasDescription = PR_FALSE;
 
72
  mFormat = nsnull;
 
73
 
 
74
  // get default charset to be used for directory listings (fallback to
 
75
  // ISO-8859-1 if pref is unavailable).
 
76
  NS_NAMED_LITERAL_CSTRING(kFallbackEncoding, "ISO-8859-1");
 
77
  nsXPIDLString defCharset;
 
78
  nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID));
 
79
  if (prefs) {
 
80
    nsCOMPtr<nsIPrefLocalizedString> prefVal;
 
81
    prefs->GetComplexValue("intl.charset.default",
 
82
                           NS_GET_IID(nsIPrefLocalizedString),
 
83
                           getter_AddRefs(prefVal));
 
84
    if (prefVal)
 
85
      prefVal->ToString(getter_Copies(defCharset));
 
86
  }
 
87
  if (!defCharset.IsEmpty())
 
88
    LossyCopyUTF16toASCII(defCharset, mEncoding); // charset labels are always ASCII
 
89
  else
 
90
    mEncoding.Assign(kFallbackEncoding);
 
91
 
 
92
  nsresult rv;
 
93
  // XXX not threadsafe
 
94
  if (gRefCntParser++ == 0)
 
95
    rv = nsServiceManager::GetService(NS_ITEXTTOSUBURI_CONTRACTID,
 
96
                                      NS_GET_IID(nsITextToSubURI),
 
97
                                      NS_REINTERPRET_CAST(nsISupports**, &gTextToSubURI));
 
98
  else
 
99
    rv = NS_OK;
 
100
 
 
101
  return rv;
 
102
}
 
103
 
 
104
nsDirIndexParser::~nsDirIndexParser() {
 
105
  delete[] mFormat;
 
106
  // XXX not threadsafe
 
107
  if (--gRefCntParser == 0) {
 
108
    NS_IF_RELEASE(gTextToSubURI);
 
109
  }
 
110
}
 
111
 
 
112
NS_IMETHODIMP
 
113
nsDirIndexParser::SetListener(nsIDirIndexListener* aListener) {
 
114
  mListener = aListener;
 
115
  return NS_OK;
 
116
}
 
117
 
 
118
NS_IMETHODIMP
 
119
nsDirIndexParser::GetListener(nsIDirIndexListener** aListener) {
 
120
  NS_IF_ADDREF(*aListener = mListener.get());
 
121
  return NS_OK;
 
122
}
 
123
 
 
124
NS_IMETHODIMP
 
125
nsDirIndexParser::GetComment(char** aComment) {
 
126
  *aComment = ToNewCString(mComment);
 
127
 
 
128
  if (!*aComment)
 
129
    return NS_ERROR_OUT_OF_MEMORY;
 
130
  
 
131
  return NS_OK;
 
132
}
 
133
 
 
134
NS_IMETHODIMP
 
135
nsDirIndexParser::SetEncoding(const char* aEncoding) {
 
136
  mEncoding.Assign(aEncoding);
 
137
  return NS_OK;
 
138
}
 
139
 
 
140
NS_IMETHODIMP
 
141
nsDirIndexParser::GetEncoding(char** aEncoding) {
 
142
  *aEncoding = ToNewCString(mEncoding);
 
143
 
 
144
  if (!*aEncoding)
 
145
    return NS_ERROR_OUT_OF_MEMORY;
 
146
 
 
147
  return NS_OK;
 
148
}
 
149
 
 
150
NS_IMETHODIMP
 
151
nsDirIndexParser::OnStartRequest(nsIRequest* aRequest, nsISupports* aCtxt) {
 
152
  return NS_OK;
 
153
}
 
154
 
 
155
NS_IMETHODIMP
 
156
nsDirIndexParser::OnStopRequest(nsIRequest *aRequest, nsISupports *aCtxt,
 
157
                                nsresult aStatusCode) {
 
158
  // Finish up
 
159
  if (mBuf.Length() > (PRUint32) mLineStart) {
 
160
    ProcessData(aRequest, aCtxt);
 
161
  }
 
162
 
 
163
  return NS_OK;
 
164
}
 
165
 
 
166
nsDirIndexParser::Field
 
167
nsDirIndexParser::gFieldTable[] = {
 
168
  { "Filename", FIELD_FILENAME },
 
169
  { "Description", FIELD_DESCRIPTION },
 
170
  { "Content-Length", FIELD_CONTENTLENGTH },
 
171
  { "Last-Modified", FIELD_LASTMODIFIED },
 
172
  { "Content-Type", FIELD_CONTENTTYPE },
 
173
  { "File-Type", FIELD_FILETYPE },
 
174
  { nsnull, FIELD_UNKNOWN }
 
175
};
 
176
 
 
177
nsrefcnt nsDirIndexParser::gRefCntParser = 0;
 
178
nsITextToSubURI *nsDirIndexParser::gTextToSubURI;
 
179
 
 
180
nsresult
 
181
nsDirIndexParser::ParseFormat(const char* aFormatStr) {
 
182
  // Parse a "200" format line, and remember the fields and their
 
183
  // ordering in mFormat. Multiple 200 lines stomp on each other.
 
184
 
 
185
  delete[] mFormat;
 
186
 
 
187
  // Lets find out how many elements we have.
 
188
  // easier to do this then realloc
 
189
  const char* pos = aFormatStr;
 
190
  int num = 0;
 
191
  do {
 
192
    while (*pos && nsCRT::IsAsciiSpace(PRUnichar(*pos)))
 
193
      ++pos;
 
194
    
 
195
    ++num;
 
196
 
 
197
    if (! *pos)
 
198
      break;
 
199
 
 
200
    while (*pos && !nsCRT::IsAsciiSpace(PRUnichar(*pos)))
 
201
      ++pos;
 
202
 
 
203
  } while (*pos);
 
204
 
 
205
  mFormat = new int[num+1];
 
206
  mFormat[num] = -1;
 
207
  
 
208
  int formatNum=0;
 
209
  do {
 
210
    while (*aFormatStr && nsCRT::IsAsciiSpace(PRUnichar(*aFormatStr)))
 
211
      ++aFormatStr;
 
212
    
 
213
    if (! *aFormatStr)
 
214
      break;
 
215
 
 
216
    nsCAutoString name;
 
217
    PRInt32     len = 0;
 
218
    while (aFormatStr[len] && !nsCRT::IsAsciiSpace(PRUnichar(aFormatStr[len])))
 
219
      ++len;
 
220
    name.SetCapacity(len + 1);
 
221
    name.Append(aFormatStr, len);
 
222
    aFormatStr += len;
 
223
    
 
224
    // Okay, we're gonna monkey with the nsStr. Bold!
 
225
    name.SetLength(nsUnescapeCount(name.BeginWriting()));
 
226
 
 
227
    // All tokens are case-insensitive - http://www.area.com/~roeber/file_format.html
 
228
    if (name.EqualsIgnoreCase("description"))
 
229
      mHasDescription = PR_TRUE;
 
230
    
 
231
    for (Field* i = gFieldTable; i->mName; ++i) {
 
232
      if (name.EqualsIgnoreCase(i->mName)) {
 
233
        mFormat[formatNum] = i->mType;
 
234
        ++formatNum;
 
235
        break;
 
236
      }
 
237
    }
 
238
 
 
239
  } while (*aFormatStr);
 
240
  
 
241
  return NS_OK;
 
242
}
 
243
 
 
244
nsresult
 
245
nsDirIndexParser::ParseData(nsIDirIndex *aIdx, char* aDataStr) {
 
246
  // Parse a "201" data line, using the field ordering specified in
 
247
  // mFormat.
 
248
 
 
249
  if (!mFormat) {
 
250
    // Ignore if we haven't seen a format yet.
 
251
    return NS_OK;
 
252
  }
 
253
 
 
254
  nsresult rv = NS_OK;
 
255
 
 
256
  nsCAutoString filename;
 
257
 
 
258
  for (PRInt32 i = 0; mFormat[i] != -1; ++i) {
 
259
    // If we've exhausted the data before we run out of fields, just
 
260
    // bail.
 
261
    if (! *aDataStr)
 
262
      break;
 
263
 
 
264
    while (*aDataStr && nsCRT::IsAsciiSpace(*aDataStr))
 
265
      ++aDataStr;
 
266
 
 
267
    char    *value = aDataStr;
 
268
 
 
269
    if (*aDataStr == '"' || *aDataStr == '\'') {
 
270
      // it's a quoted string. snarf everything up to the next quote character
 
271
      const char quotechar = *(aDataStr++);
 
272
      ++value;
 
273
      while (*aDataStr && *aDataStr != quotechar)
 
274
        ++aDataStr;
 
275
      *aDataStr++ = '\0';
 
276
 
 
277
      if (! aDataStr) {
 
278
        NS_WARNING("quoted value not terminated");
 
279
      }
 
280
    } else {
 
281
      // it's unquoted. snarf until we see whitespace.
 
282
      value = aDataStr;
 
283
      while (*aDataStr && (!nsCRT::IsAsciiSpace(*aDataStr)))
 
284
        ++aDataStr;
 
285
      *aDataStr++ = '\0';
 
286
    }
 
287
 
 
288
    fieldType t = fieldType(mFormat[i]);
 
289
    switch (t) {
 
290
    case FIELD_FILENAME: {
 
291
      // don't unescape at this point, so that UnEscapeAndConvert() can
 
292
      filename = value;
 
293
      
 
294
      PRBool  success = PR_FALSE;
 
295
      
 
296
      nsAutoString entryuri;
 
297
      
 
298
      if (gTextToSubURI) {
 
299
        PRUnichar   *result = nsnull;
 
300
        if (NS_SUCCEEDED(rv = gTextToSubURI->UnEscapeAndConvert(mEncoding.get(), filename.get(),
 
301
                                                                &result)) && (result)) {
 
302
          if (*result) {
 
303
            aIdx->SetLocation(filename.get());
 
304
            if (!mHasDescription)
 
305
              aIdx->SetDescription(result);
 
306
            success = PR_TRUE;
 
307
          }
 
308
          Recycle(result);
 
309
        } else {
 
310
          NS_WARNING("UnEscapeAndConvert error");
 
311
        }
 
312
      }
 
313
      
 
314
      if (success == PR_FALSE) {
 
315
        // if unsuccessfully at charset conversion, then
 
316
        // just fallback to unescape'ing in-place
 
317
        // XXX - this shouldn't be using UTF8, should it?
 
318
        // when can we fail to get the service, anyway? - bbaetz
 
319
        aIdx->SetLocation(filename.get());
 
320
        if (!mHasDescription) {
 
321
          aIdx->SetDescription(NS_ConvertUTF8toUCS2(value).get());
 
322
        }
 
323
      }
 
324
    }
 
325
      break;
 
326
    case FIELD_DESCRIPTION:
 
327
      nsUnescape(value);
 
328
      aIdx->SetDescription(NS_ConvertUTF8toUCS2(value).get());
 
329
      break;
 
330
    case FIELD_CONTENTLENGTH:
 
331
      {
 
332
        PRInt64 len;
 
333
        PRInt32 status = PR_sscanf(value, "%lld", &len);
 
334
        if (status == 1)
 
335
          aIdx->SetSize(len);
 
336
        else
 
337
          aIdx->SetSize(LL_INIT(0, -1)); // -1 means unknown
 
338
      }
 
339
      break;
 
340
    case FIELD_LASTMODIFIED:
 
341
      {
 
342
        PRTime tm;
 
343
        nsUnescape(value);
 
344
        if (PR_ParseTimeString(value, PR_FALSE, &tm) == PR_SUCCESS) {
 
345
          aIdx->SetLastModified(tm);
 
346
        }
 
347
      }
 
348
      break;
 
349
    case FIELD_CONTENTTYPE:
 
350
      aIdx->SetContentType(value);
 
351
      break;
 
352
    case FIELD_FILETYPE:
 
353
      // unescape in-place
 
354
      nsUnescape(value);
 
355
      if (!nsCRT::strcasecmp(value, "directory")) {
 
356
        aIdx->SetType(nsIDirIndex::TYPE_DIRECTORY);
 
357
      } else if (!nsCRT::strcasecmp(value, "file")) {
 
358
        aIdx->SetType(nsIDirIndex::TYPE_FILE);
 
359
      } else if (!nsCRT::strcasecmp(value, "symbolic-link")) {
 
360
        aIdx->SetType(nsIDirIndex::TYPE_SYMLINK);
 
361
      } else {
 
362
        aIdx->SetType(nsIDirIndex::TYPE_UNKNOWN);
 
363
      }
 
364
      break;
 
365
    case FIELD_UNKNOWN:
 
366
      // ignore
 
367
      break;
 
368
    }
 
369
  }
 
370
 
 
371
  return NS_OK;
 
372
}
 
373
 
 
374
NS_IMETHODIMP
 
375
nsDirIndexParser::OnDataAvailable(nsIRequest *aRequest, nsISupports *aCtxt,
 
376
                                  nsIInputStream *aStream,
 
377
                                  PRUint32 aSourceOffset,
 
378
                                  PRUint32 aCount) {
 
379
  if (aCount < 1)
 
380
    return NS_OK;
 
381
  
 
382
  PRInt32 len = mBuf.Length();
 
383
  
 
384
  // Ensure that our mBuf has capacity to hold the data we're about to
 
385
  // read.
 
386
  mBuf.SetCapacity(len + aCount + 1);
 
387
  if (! mBuf.get())
 
388
    return NS_ERROR_OUT_OF_MEMORY;
 
389
 
 
390
  // Now read the data into our buffer.
 
391
  nsresult rv;
 
392
  PRUint32 count;
 
393
  rv = aStream->Read(mBuf.BeginWriting() + len, aCount, &count);
 
394
  if (NS_FAILED(rv)) return rv;
 
395
 
 
396
  // Set the string's length according to the amount of data we've read.
 
397
  // Note: we know this to work on nsCString. This isn't guaranteed to
 
398
  //       work on other strings.
 
399
  mBuf.SetLength(len + count);
 
400
 
 
401
  return ProcessData(aRequest, aCtxt);
 
402
}
 
403
 
 
404
nsresult
 
405
nsDirIndexParser::ProcessData(nsIRequest *aRequest, nsISupports *aCtxt) {
 
406
  if (!mListener)
 
407
    return NS_ERROR_FAILURE;
 
408
  
 
409
  PRInt32     numItems = 0;
 
410
  
 
411
  while(PR_TRUE) {
 
412
    ++numItems;
 
413
    
 
414
    PRInt32             eol = mBuf.FindCharInSet("\n\r", mLineStart);
 
415
    if (eol < 0)        break;
 
416
    mBuf.SetCharAt(PRUnichar('\0'), eol);
 
417
    
 
418
    const char  *line = mBuf.get() + mLineStart;
 
419
    
 
420
    PRInt32 lineLen = eol - mLineStart;
 
421
    mLineStart = eol + 1;
 
422
    
 
423
    if (lineLen >= 4) {
 
424
      nsresult  rv;
 
425
      const char        *buf = line;
 
426
      
 
427
      if (buf[0] == '1') {
 
428
        if (buf[1] == '0') {
 
429
          if (buf[2] == '0' && buf[3] == ':') {
 
430
            // 100. Human-readable comment line. Ignore
 
431
          } else if (buf[2] == '1' && buf[3] == ':') {
 
432
            // 101. Human-readable information line.
 
433
            mComment.Append(buf + 4);
 
434
          } else if (buf[2] == '2' && buf[3] == ':') {
 
435
            // 102. Human-readable information line, HTML.
 
436
            mComment.Append(buf + 4);
 
437
          }
 
438
        }
 
439
      } else if (buf[0] == '2') {
 
440
        if (buf[1] == '0') {
 
441
          if (buf[2] == '0' && buf[3] == ':') {
 
442
            // 200. Define field names
 
443
            rv = ParseFormat(buf + 4);
 
444
            if (NS_FAILED(rv)) {
 
445
              return rv;
 
446
            }
 
447
          } else if (buf[2] == '1' && buf[3] == ':') {
 
448
            // 201. Field data
 
449
            nsCOMPtr<nsIDirIndex> idx = do_CreateInstance("@mozilla.org/dirIndex;1",&rv);
 
450
            if (NS_FAILED(rv))
 
451
              return rv;
 
452
            
 
453
            rv = ParseData(idx, ((char *)buf) + 4);
 
454
            if (NS_FAILED(rv)) {
 
455
              return rv;
 
456
            }
 
457
 
 
458
            mListener->OnIndexAvailable(aRequest, aCtxt, idx);
 
459
          }
 
460
        }
 
461
      } else if (buf[0] == '3') {
 
462
        if (buf[1] == '0') {
 
463
          if (buf[2] == '0' && buf[3] == ':') {
 
464
            // 300. Self-referring URL
 
465
          } else if (buf[2] == '1' && buf[3] == ':') {
 
466
            // 301. OUR EXTENSION - encoding
 
467
            int i = 4;
 
468
            while (buf[i] && nsCRT::IsAsciiSpace(buf[i]))
 
469
              ++i;
 
470
            
 
471
            if (buf[i])
 
472
              SetEncoding(buf+i);
 
473
          }
 
474
        }
 
475
      }
 
476
    }
 
477
  }
 
478
  
 
479
  return NS_OK;
 
480
}