]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - docs/frontends/webapi.rst
docs/frontends/webapi.rst: change some more instances of 'delete' or 'remove' to...
[tahoe-lafs/tahoe-lafs.git] / docs / frontends / webapi.rst
1 ==========================
2 The Tahoe REST-ful Web API
3 ==========================
4
5 1.  `Enabling the web-API port`_
6 2.  `Basic Concepts: GET, PUT, DELETE, POST`_
7 3.  `URLs`_
8
9         1. `Child Lookup`_
10
11 4.  `Slow Operations, Progress, and Cancelling`_
12 5.  `Programmatic Operations`_
13
14     1. `Reading a file`_
15     2. `Writing/Uploading a File`_
16     3. `Creating a New Directory`_
17     4. `Getting Information About A File Or Directory (as JSON)`_
18     5. `Attaching an Existing File or Directory by its read- or write-cap`_
19     6. `Adding Multiple Files or Directories to a Parent Directory at Once`_
20     7. `Unlinking a File or Directory`_
21
22 6.  `Browser Operations: Human-Oriented Interfaces`_
23
24     1.  `Viewing A Directory (as HTML)`_
25     2.  `Viewing/Downloading a File`_
26     3.  `Getting Information About A File Or Directory (as HTML)`_
27     4.  `Creating a Directory`_
28     5.  `Uploading a File`_
29     6.  `Attaching An Existing File Or Directory (by URI)`_
30     7.  `Unlinking A Child`_
31     8.  `Renaming A Child`_
32     9.  `Other Utilities`_
33     10. `Debugging and Testing Features`_
34
35 7.  `Other Useful Pages`_
36 8.  `Static Files in /public_html`_
37 9.  `Safety and Security Issues -- Names vs. URIs`_
38 10. `Concurrency Issues`_
39
40
41 Enabling the web-API port
42 =========================
43
44 Every Tahoe node is capable of running a built-in HTTP server. To enable
45 this, just write a port number into the "[node]web.port" line of your node's
46 tahoe.cfg file. For example, writing "web.port = 3456" into the "[node]"
47 section of $NODEDIR/tahoe.cfg will cause the node to run a webserver on port
48 3456.
49
50 This string is actually a Twisted "strports" specification, meaning you can
51 get more control over the interface to which the server binds by supplying
52 additional arguments. For more details, see the documentation on
53 `twisted.application.strports
54 <http://twistedmatrix.com/documents/current/api/twisted.application.strports.html>`_.
55
56 Writing "tcp:3456:interface=127.0.0.1" into the web.port line does the same
57 but binds to the loopback interface, ensuring that only the programs on the
58 local host can connect. Using "ssl:3456:privateKey=mykey.pem:certKey=cert.pem"
59 runs an SSL server.
60
61 This webport can be set when the node is created by passing a --webport
62 option to the 'tahoe create-node' command. By default, the node listens on
63 port 3456, on the loopback (127.0.0.1) interface.
64
65
66 Basic Concepts: GET, PUT, DELETE, POST
67 ======================================
68
69 As described in `docs/architecture.rst <../architecture.rst>`_, each file
70 and directory in a Tahoe virtual filesystem is referenced by an identifier
71 that combines the designation of the object with the authority to do something
72 with it (such as read or modify the contents). This identifier is called a
73 "read-cap" or "write-cap", depending upon whether it enables read-only or
74 read-write access. These "caps" are also referred to as URIs (which may be
75 confusing because they are not currently `RFC3986
76 <http://tools.ietf.org/html/rfc3986>`_-compliant URIs).
77
78 The Tahoe web-based API is "REST-ful", meaning it implements the concepts of
79 "REpresentational State Transfer": the original scheme by which the World
80 Wide Web was intended to work. Each object (file or directory) is referenced
81 by a URL that includes the read- or write- cap. HTTP methods (GET, PUT, and
82 DELETE) are used to manipulate these objects. You can think of the URL as a
83 noun, and the method as a verb.
84
85 In REST, the GET method is used to retrieve information about an object, or
86 to retrieve some representation of the object itself. When the object is a
87 file, the basic GET method will simply return the contents of that file.
88 Other variations (generally implemented by adding query parameters to the
89 URL) will return information about the object, such as metadata. GET
90 operations are required to have no side-effects.
91
92 PUT is used to upload new objects into the filesystem, or to replace an
93 existing link or the contents of a mutable file. DELETE is used to unlink
94 objects from directories. Both PUT and DELETE are required to be idempotent:
95 performing the same operation multiple times must have the same side-effects
96 as only performing it once.
97
98 POST is used for more complicated actions that cannot be expressed as a GET,
99 PUT, or DELETE. POST operations can be thought of as a method call: sending
100 some message to the object referenced by the URL. In Tahoe, POST is also used
101 for operations that must be triggered by an HTML form (including upload and
102 unlinking), because otherwise a regular web browser has no way to accomplish
103 these tasks. In general, everything that can be done with a PUT or DELETE can
104 also be done with a POST.
105
106 Tahoe's web API is designed for two different kinds of consumer. The first is
107 a program that needs to manipulate the virtual file system. Such programs are
108 expected to use the RESTful interface described above. The second is a human
109 using a standard web browser to work with the filesystem. This user is given
110 a series of HTML pages with links to download files, and forms that use POST
111 actions to upload, rename, and unlink files.
112
113 When an error occurs, the HTTP response code will be set to an appropriate
114 400-series code (like 404 Not Found for an unknown childname, or 400 Bad Request
115 when the parameters to a web-API operation are invalid), and the HTTP response
116 body will usually contain a few lines of explanation as to the cause of the
117 error and possible responses. Unusual exceptions may result in a 500 Internal
118 Server Error as a catch-all, with a default response body containing
119 a Nevow-generated HTML-ized representation of the Python exception stack trace
120 that caused the problem. CLI programs which want to copy the response body to
121 stderr should provide an "Accept: text/plain" header to their requests to get
122 a plain text stack trace instead. If the Accept header contains ``*/*``, or
123 ``text/*``, or text/html (or if there is no Accept header), HTML tracebacks will
124 be generated.
125
126
127 URLs
128 ====
129
130 Tahoe uses a variety of read- and write- caps to identify files and
131 directories. The most common of these is the "immutable file read-cap", which
132 is used for most uploaded files. These read-caps look like the following::
133
134  URI:CHK:ime6pvkaxuetdfah2p2f35pe54:4btz54xk3tew6nd4y2ojpxj4m6wxjqqlwnztgre6gnjgtucd5r4a:3:10:202
135
136 The next most common is a "directory write-cap", which provides both read and
137 write access to a directory, and look like this::
138
139  URI:DIR2:djrdkfawoqihigoett4g6auz6a:jx5mplfpwexnoqff7y5e4zjus4lidm76dcuarpct7cckorh2dpgq
140
141 There are also "directory read-caps", which start with "URI:DIR2-RO:", and
142 give read-only access to a directory. Finally there are also mutable file
143 read- and write- caps, which start with "URI:SSK", and give access to mutable
144 files.
145
146 (Later versions of Tahoe will make these strings shorter, and will remove the
147 unfortunate colons, which must be escaped when these caps are embedded in
148 URLs.)
149
150 To refer to any Tahoe object through the web API, you simply need to combine
151 a prefix (which indicates the HTTP server to use) with the cap (which
152 indicates which object inside that server to access). Since the default Tahoe
153 webport is 3456, the most common prefix is one that will use a local node
154 listening on this port::
155
156  http://127.0.0.1:3456/uri/ + $CAP
157
158 So, to access the directory named above (which happens to be the
159 publically-writeable sample directory on the Tahoe test grid, described at
160 http://allmydata.org/trac/tahoe/wiki/TestGrid), the URL would be::
161
162  http://127.0.0.1:3456/uri/URI%3ADIR2%3Adjrdkfawoqihigoett4g6auz6a%3Ajx5mplfpwexnoqff7y5e4zjus4lidm76dcuarpct7cckorh2dpgq/
163
164 (note that the colons in the directory-cap are url-encoded into "%3A"
165 sequences).
166
167 Likewise, to access the file named above, use::
168
169  http://127.0.0.1:3456/uri/URI%3ACHK%3Aime6pvkaxuetdfah2p2f35pe54%3A4btz54xk3tew6nd4y2ojpxj4m6wxjqqlwnztgre6gnjgtucd5r4a%3A3%3A10%3A202
170
171 In the rest of this document, we'll use "$DIRCAP" as shorthand for a read-cap
172 or write-cap that refers to a directory, and "$FILECAP" to abbreviate a cap
173 that refers to a file (whether mutable or immutable). So those URLs above can
174 be abbreviated as::
175
176  http://127.0.0.1:3456/uri/$DIRCAP/
177  http://127.0.0.1:3456/uri/$FILECAP
178
179 The operation summaries below will abbreviate these further, by eliding the
180 server prefix. They will be displayed like this::
181
182  /uri/$DIRCAP/
183  /uri/$FILECAP
184
185
186 Child Lookup
187 ------------
188
189 Tahoe directories contain named child entries, just like directories in a regular
190 local filesystem. These child entries, called "dirnodes", consist of a name,
191 metadata, a write slot, and a read slot. The write and read slots normally contain
192 a write-cap and read-cap referring to the same object, which can be either a file
193 or a subdirectory. The write slot may be empty (actually, both may be empty,
194 but that is unusual).
195
196 If you have a Tahoe URL that refers to a directory, and want to reference a
197 named child inside it, just append the child name to the URL. For example, if
198 our sample directory contains a file named "welcome.txt", we can refer to
199 that file with::
200
201  http://127.0.0.1:3456/uri/$DIRCAP/welcome.txt
202
203 (or http://127.0.0.1:3456/uri/URI%3ADIR2%3Adjrdkfawoqihigoett4g6auz6a%3Ajx5mplfpwexnoqff7y5e4zjus4lidm76dcuarpct7cckorh2dpgq/welcome.txt)
204
205 Multiple levels of subdirectories can be handled this way::
206
207  http://127.0.0.1:3456/uri/$DIRCAP/tahoe-source/docs/architecture.rst
208
209 In this document, when we need to refer to a URL that references a file using
210 this child-of-some-directory format, we'll use the following string::
211
212  /uri/$DIRCAP/[SUBDIRS../]FILENAME
213
214 The "[SUBDIRS../]" part means that there are zero or more (optional)
215 subdirectory names in the middle of the URL. The "FILENAME" at the end means
216 that this whole URL refers to a file of some sort, rather than to a
217 directory.
218
219 When we need to refer specifically to a directory in this way, we'll write::
220
221  /uri/$DIRCAP/[SUBDIRS../]SUBDIR
222
223
224 Note that all components of pathnames in URLs are required to be UTF-8
225 encoded, so "resume.doc" (with an acute accent on both E's) would be accessed
226 with::
227
228  http://127.0.0.1:3456/uri/$DIRCAP/r%C3%A9sum%C3%A9.doc
229
230 Also note that the filenames inside upload POST forms are interpreted using
231 whatever character set was provided in the conventional '_charset' field, and
232 defaults to UTF-8 if not otherwise specified. The JSON representation of each
233 directory contains native Unicode strings. Tahoe directories are specified to
234 contain Unicode filenames, and cannot contain binary strings that are not
235 representable as such.
236
237 All Tahoe operations that refer to existing files or directories must include
238 a suitable read- or write- cap in the URL: the web-API server won't add one
239 for you. If you don't know the cap, you can't access the file. This allows
240 the security properties of Tahoe caps to be extended across the web-API
241 interface.
242
243
244 Slow Operations, Progress, and Cancelling
245 =========================================
246
247 Certain operations can be expected to take a long time. The "t=deep-check",
248 described below, will recursively visit every file and directory reachable
249 from a given starting point, which can take minutes or even hours for
250 extremely large directory structures. A single long-running HTTP request is a
251 fragile thing: proxies, NAT boxes, browsers, and users may all grow impatient
252 with waiting and give up on the connection.
253
254 For this reason, long-running operations have an "operation handle", which
255 can be used to poll for status/progress messages while the operation
256 proceeds. This handle can also be used to cancel the operation. These handles
257 are created by the client, and passed in as a an "ophandle=" query argument
258 to the POST or PUT request which starts the operation. The following
259 operations can then be used to retrieve status:
260
261 ``GET /operations/$HANDLE?output=HTML   (with or without t=status)``
262
263 ``GET /operations/$HANDLE?output=JSON   (same)``
264
265  These two retrieve the current status of the given operation. Each operation
266  presents a different sort of information, but in general the page retrieved
267  will indicate:
268
269  * whether the operation is complete, or if it is still running
270  * how much of the operation is complete, and how much is left, if possible
271
272  Note that the final status output can be quite large: a deep-manifest of a
273  directory structure with 300k directories and 200k unique files is about
274  275MB of JSON, and might take two minutes to generate. For this reason, the
275  full status is not provided until the operation has completed.
276
277  The HTML form will include a meta-refresh tag, which will cause a regular
278  web browser to reload the status page about 60 seconds later. This tag will
279  be removed once the operation has completed.
280
281  There may be more status information available under
282  /operations/$HANDLE/$ETC : i.e., the handle forms the root of a URL space.
283
284 ``POST /operations/$HANDLE?t=cancel``
285
286  This terminates the operation, and returns an HTML page explaining what was
287  cancelled. If the operation handle has already expired (see below), this
288  POST will return a 404, which indicates that the operation is no longer
289  running (either it was completed or terminated). The response body will be
290  the same as a GET /operations/$HANDLE on this operation handle, and the
291  handle will be expired immediately afterwards.
292
293 The operation handle will eventually expire, to avoid consuming an unbounded
294 amount of memory. The handle's time-to-live can be reset at any time, by
295 passing a retain-for= argument (with a count of seconds) to either the
296 initial POST that starts the operation, or the subsequent GET request which
297 asks about the operation. For example, if a 'GET
298 /operations/$HANDLE?output=JSON&retain-for=600' query is performed, the
299 handle will remain active for 600 seconds (10 minutes) after the GET was
300 received.
301
302 In addition, if the GET includes a release-after-complete=True argument, and
303 the operation has completed, the operation handle will be released
304 immediately.
305
306 If a retain-for= argument is not used, the default handle lifetimes are:
307
308  * handles will remain valid at least until their operation finishes
309  * uncollected handles for finished operations (i.e. handles for
310    operations that have finished but for which the GET page has not been
311    accessed since completion) will remain valid for four days, or for
312    the total time consumed by the operation, whichever is greater.
313  * collected handles (i.e. the GET page has been retrieved at least once
314    since the operation completed) will remain valid for one day.
315
316 Many "slow" operations can begin to use unacceptable amounts of memory when
317 operating on large directory structures. The memory usage increases when the
318 ophandle is polled, as the results must be copied into a JSON string, sent
319 over the wire, then parsed by a client. So, as an alternative, many "slow"
320 operations have streaming equivalents. These equivalents do not use operation
321 handles. Instead, they emit line-oriented status results immediately. Client
322 code can cancel the operation by simply closing the HTTP connection.
323
324
325 Programmatic Operations
326 =======================
327
328 Now that we know how to build URLs that refer to files and directories in a
329 Tahoe virtual filesystem, what sorts of operations can we do with those URLs?
330 This section contains a catalog of GET, PUT, DELETE, and POST operations that
331 can be performed on these URLs. This set of operations are aimed at programs
332 that use HTTP to communicate with a Tahoe node. A later section describes
333 operations that are intended for web browsers.
334
335
336 Reading A File
337 --------------
338
339 ``GET /uri/$FILECAP``
340
341 ``GET /uri/$DIRCAP/[SUBDIRS../]FILENAME``
342
343  This will retrieve the contents of the given file. The HTTP response body
344  will contain the sequence of bytes that make up the file.
345
346  To view files in a web browser, you may want more control over the
347  Content-Type and Content-Disposition headers. Please see the next section
348  "Browser Operations", for details on how to modify these URLs for that
349  purpose.
350
351
352 Writing/Uploading A File
353 ------------------------
354
355 ``PUT /uri/$FILECAP``
356
357 ``PUT /uri/$DIRCAP/[SUBDIRS../]FILENAME``
358
359  Upload a file, using the data from the HTTP request body, and add whatever
360  child links and subdirectories are necessary to make the file available at
361  the given location. Once this operation succeeds, a GET on the same URL will
362  retrieve the same contents that were just uploaded. This will create any
363  necessary intermediate subdirectories.
364
365  To use the /uri/$FILECAP form, $FILECAP must be a write-cap for a mutable file.
366
367  In the /uri/$DIRCAP/[SUBDIRS../]FILENAME form, if the target file is a
368  writeable mutable file, that file's contents will be overwritten in-place. If
369  it is a read-cap for a mutable file, an error will occur. If it is an
370  immutable file, the old file will be discarded, and a new one will be put in
371  its place.
372
373  When creating a new file, if "mutable=true" is in the query arguments, the
374  operation will create a mutable file instead of an immutable one.
375
376  This returns the file-cap of the resulting file. If a new file was created
377  by this method, the HTTP response code (as dictated by rfc2616) will be set
378  to 201 CREATED. If an existing file was replaced or modified, the response
379  code will be 200 OK.
380
381  Note that the 'curl -T localfile http://127.0.0.1:3456/uri/$DIRCAP/foo.txt'
382  command can be used to invoke this operation.
383
384 ``PUT /uri``
385
386  This uploads a file, and produces a file-cap for the contents, but does not
387  attach the file into the filesystem. No directories will be modified by
388  this operation. The file-cap is returned as the body of the HTTP response.
389
390  If "mutable=true" is in the query arguments, the operation will create a
391  mutable file, and return its write-cap in the HTTP respose. The default is
392  to create an immutable file, returning the read-cap as a response.
393
394
395 Creating A New Directory
396 ------------------------
397
398 ``POST /uri?t=mkdir``
399
400 ``PUT /uri?t=mkdir``
401
402  Create a new empty directory and return its write-cap as the HTTP response
403  body. This does not make the newly created directory visible from the
404  filesystem. The "PUT" operation is provided for backwards compatibility:
405  new code should use POST.
406
407 ``POST /uri?t=mkdir-with-children``
408
409  Create a new directory, populated with a set of child nodes, and return its
410  write-cap as the HTTP response body. The new directory is not attached to
411  any other directory: the returned write-cap is the only reference to it.
412
413  Initial children are provided as the body of the POST form (this is more
414  efficient than doing separate mkdir and set_children operations). If the
415  body is empty, the new directory will be empty. If not empty, the body will
416  be interpreted as a UTF-8 JSON-encoded dictionary of children with which the
417  new directory should be populated, using the same format as would be
418  returned in the 'children' value of the t=json GET request, described below.
419  Each dictionary key should be a child name, and each value should be a list
420  of [TYPE, PROPDICT], where PROPDICT contains "rw_uri", "ro_uri", and
421  "metadata" keys (all others are ignored). For example, the PUT request body
422  could be::
423
424   {
425     "Fran\u00e7ais": [ "filenode", {
426         "ro_uri": "URI:CHK:...",
427         "size": bytes,
428         "metadata": {
429           "ctime": 1202777696.7564139,
430           "mtime": 1202777696.7564139,
431           "tahoe": {
432             "linkcrtime": 1202777696.7564139,
433             "linkmotime": 1202777696.7564139
434             } } } ],
435     "subdir":  [ "dirnode", {
436         "rw_uri": "URI:DIR2:...",
437         "ro_uri": "URI:DIR2-RO:...",
438         "metadata": {
439           "ctime": 1202778102.7589991,
440           "mtime": 1202778111.2160511,
441           "tahoe": {
442             "linkcrtime": 1202777696.7564139,
443             "linkmotime": 1202777696.7564139
444           } } } ]
445   }
446
447  For forward-compatibility, a mutable directory can also contain caps in
448  a format that is unknown to the web-API server. When such caps are retrieved
449  from a mutable directory in a "ro_uri" field, they will be prefixed with
450  the string "ro.", indicating that they must not be decoded without
451  checking that they are read-only. The "ro." prefix must not be stripped
452  off without performing this check. (Future versions of the web-API server
453  will perform it where necessary.)
454
455  If both the "rw_uri" and "ro_uri" fields are present in a given PROPDICT,
456  and the web-API server recognizes the rw_uri as a write cap, then it will
457  reset the ro_uri to the corresponding read cap and discard the original
458  contents of ro_uri (in order to ensure that the two caps correspond to the
459  same object and that the ro_uri is in fact read-only). However this may not
460  happen for caps in a format unknown to the web-API server. Therefore, when
461  writing a directory the web-API client should ensure that the contents
462  of "rw_uri" and "ro_uri" for a given PROPDICT are a consistent
463  (write cap, read cap) pair if possible. If the web-API client only has
464  one cap and does not know whether it is a write cap or read cap, then
465  it is acceptable to set "rw_uri" to that cap and omit "ro_uri". The
466  client must not put a write cap into a "ro_uri" field.
467
468  The metadata may have a "no-write" field. If this is set to true in the
469  metadata of a link, it will not be possible to open that link for writing
470  via the SFTP frontend; see `<FTP-and-SFTP.rst>`_ for details.
471  Also, if the "no-write" field is set to true in the metadata of a link to
472  a mutable child, it will cause the link to be diminished to read-only.
473
474  Note that the web-API-using client application must not provide the
475  "Content-Type: multipart/form-data" header that usually accompanies HTML
476  form submissions, since the body is not formatted this way. Doing so will
477  cause a server error as the lower-level code misparses the request body.
478
479  Child file names should each be expressed as a Unicode string, then used as
480  keys of the dictionary. The dictionary should then be converted into JSON,
481  and the resulting string encoded into UTF-8. This UTF-8 bytestring should
482  then be used as the POST body.
483
484 ``POST /uri?t=mkdir-immutable``
485
486  Like t=mkdir-with-children above, but the new directory will be
487  deep-immutable. This means that the directory itself is immutable, and that
488  it can only contain objects that are treated as being deep-immutable, like
489  immutable files, literal files, and deep-immutable directories.
490
491  For forward-compatibility, a deep-immutable directory can also contain caps
492  in a format that is unknown to the web-API server. When such caps are retrieved
493  from a deep-immutable directory in a "ro_uri" field, they will be prefixed
494  with the string "imm.", indicating that they must not be decoded without
495  checking that they are immutable. The "imm." prefix must not be stripped
496  off without performing this check. (Future versions of the web-API server
497  will perform it where necessary.)
498  
499  The cap for each child may be given either in the "rw_uri" or "ro_uri"
500  field of the PROPDICT (not both). If a cap is given in the "rw_uri" field,
501  then the web-API server will check that it is an immutable read-cap of a
502  *known* format, and give an error if it is not. If a cap is given in the
503  "ro_uri" field, then the web-API server will still check whether known
504  caps are immutable, but for unknown caps it will simply assume that the
505  cap can be stored, as described above. Note that an attacker would be
506  able to store any cap in an immutable directory, so this check when
507  creating the directory is only to help non-malicious clients to avoid
508  accidentally giving away more authority than intended.
509
510  A non-empty request body is mandatory, since after the directory is created,
511  it will not be possible to add more children to it.
512
513 ``POST /uri/$DIRCAP/[SUBDIRS../]SUBDIR?t=mkdir``
514
515 ``PUT /uri/$DIRCAP/[SUBDIRS../]SUBDIR?t=mkdir``
516
517  Create new directories as necessary to make sure that the named target
518  ($DIRCAP/SUBDIRS../SUBDIR) is a directory. This will create additional
519  intermediate mutable directories as necessary. If the named target directory
520  already exists, this will make no changes to it.
521
522  If the final directory is created, it will be empty.
523
524  This operation will return an error if a blocking file is present at any of
525  the parent names, preventing the server from creating the necessary parent
526  directory; or if it would require changing an immutable directory.
527
528  The write-cap of the new directory will be returned as the HTTP response
529  body.
530
531 ``POST /uri/$DIRCAP/[SUBDIRS../]SUBDIR?t=mkdir-with-children``
532
533  Like /uri?t=mkdir-with-children, but the final directory is created as a
534  child of an existing mutable directory. This will create additional
535  intermediate mutable directories as necessary. If the final directory is
536  created, it will be populated with initial children from the POST request
537  body, as described above.
538  
539  This operation will return an error if a blocking file is present at any of
540  the parent names, preventing the server from creating the necessary parent
541  directory; or if it would require changing an immutable directory; or if
542  the immediate parent directory already has a a child named SUBDIR.
543
544 ``POST /uri/$DIRCAP/[SUBDIRS../]SUBDIR?t=mkdir-immutable``
545
546  Like /uri?t=mkdir-immutable, but the final directory is created as a child
547  of an existing mutable directory. The final directory will be deep-immutable,
548  and will be populated with the children specified as a JSON dictionary in
549  the POST request body.
550
551  In Tahoe 1.6 this operation creates intermediate mutable directories if
552  necessary, but that behaviour should not be relied on; see ticket #920.
553
554  This operation will return an error if the parent directory is immutable,
555  or already has a child named SUBDIR.
556
557 ``POST /uri/$DIRCAP/[SUBDIRS../]?t=mkdir&name=NAME``
558
559  Create a new empty mutable directory and attach it to the given existing
560  directory. This will create additional intermediate directories as necessary.
561
562  This operation will return an error if a blocking file is present at any of
563  the parent names, preventing the server from creating the necessary parent
564  directory, or if it would require changing any immutable directory.
565
566  The URL of this operation points to the parent of the bottommost new directory,
567  whereas the /uri/$DIRCAP/[SUBDIRS../]SUBDIR?t=mkdir operation above has a URL
568  that points directly to the bottommost new directory.
569
570 ``POST /uri/$DIRCAP/[SUBDIRS../]?t=mkdir-with-children&name=NAME``
571
572  Like /uri/$DIRCAP/[SUBDIRS../]?t=mkdir&name=NAME, but the new directory will
573  be populated with initial children via the POST request body. This command
574  will create additional intermediate mutable directories as necessary.
575  
576  This operation will return an error if a blocking file is present at any of
577  the parent names, preventing the server from creating the necessary parent
578  directory; or if it would require changing an immutable directory; or if
579  the immediate parent directory already has a a child named NAME.
580
581  Note that the name= argument must be passed as a queryarg, because the POST
582  request body is used for the initial children JSON. 
583
584 ``POST /uri/$DIRCAP/[SUBDIRS../]?t=mkdir-immutable&name=NAME``
585
586  Like /uri/$DIRCAP/[SUBDIRS../]?t=mkdir-with-children&name=NAME, but the
587  final directory will be deep-immutable. The children are specified as a
588  JSON dictionary in the POST request body. Again, the name= argument must be
589  passed as a queryarg.
590
591  In Tahoe 1.6 this operation creates intermediate mutable directories if
592  necessary, but that behaviour should not be relied on; see ticket #920.
593
594  This operation will return an error if the parent directory is immutable,
595  or already has a child named NAME.
596
597
598 Getting Information About A File Or Directory (as JSON)
599 -------------------------------------------------------
600
601 ``GET /uri/$FILECAP?t=json``
602
603 ``GET /uri/$DIRCAP?t=json``
604
605 ``GET /uri/$DIRCAP/[SUBDIRS../]SUBDIR?t=json``
606
607 ``GET /uri/$DIRCAP/[SUBDIRS../]FILENAME?t=json``
608
609  This returns a machine-parseable JSON-encoded description of the given
610  object. The JSON always contains a list, and the first element of the list is
611  always a flag that indicates whether the referenced object is a file or a
612  directory. If it is a capability to a file, then the information includes
613  file size and URI, like this::
614
615   GET /uri/$FILECAP?t=json :
616
617    [ "filenode", {
618          "ro_uri": file_uri,
619          "verify_uri": verify_uri,
620          "size": bytes,
621          "mutable": false
622          } ]
623
624  If it is a capability to a directory followed by a path from that directory
625  to a file, then the information also includes metadata from the link to the
626  file in the parent directory, like this::
627
628   GET /uri/$DIRCAP/[SUBDIRS../]FILENAME?t=json
629
630    [ "filenode", {
631          "ro_uri": file_uri,
632          "verify_uri": verify_uri,
633          "size": bytes,
634          "mutable": false,
635          "metadata": {
636            "ctime": 1202777696.7564139,
637            "mtime": 1202777696.7564139,
638            "tahoe": {
639                  "linkcrtime": 1202777696.7564139,
640                  "linkmotime": 1202777696.7564139
641                  } } } ]
642
643  If it is a directory, then it includes information about the children of
644  this directory, as a mapping from child name to a set of data about the
645  child (the same data that would appear in a corresponding GET?t=json of the
646  child itself). The child entries also include metadata about each child,
647  including link-creation- and link-change- timestamps. The output looks like
648  this::
649
650   GET /uri/$DIRCAP?t=json :
651   GET /uri/$DIRCAP/[SUBDIRS../]SUBDIR?t=json :
652
653    [ "dirnode", {
654          "rw_uri": read_write_uri,
655          "ro_uri": read_only_uri,
656          "verify_uri": verify_uri,
657          "mutable": true,
658          "children": {
659            "foo.txt": [ "filenode", {
660                    "ro_uri": uri,
661                    "size": bytes,
662                    "metadata": {
663                          "ctime": 1202777696.7564139,
664                          "mtime": 1202777696.7564139,
665                          "tahoe": {
666                            "linkcrtime": 1202777696.7564139,
667                            "linkmotime": 1202777696.7564139
668                            } } } ],
669            "subdir":  [ "dirnode", {
670                    "rw_uri": rwuri,
671                    "ro_uri": rouri,
672                    "metadata": {
673                          "ctime": 1202778102.7589991,
674                          "mtime": 1202778111.2160511,
675                          "tahoe": {
676                            "linkcrtime": 1202777696.7564139,
677                            "linkmotime": 1202777696.7564139
678                          } } } ]
679          } } ]
680
681  In the above example, note how 'children' is a dictionary in which the keys
682  are child names and the values depend upon whether the child is a file or a
683  directory. The value is mostly the same as the JSON representation of the
684  child object (except that directories do not recurse -- the "children"
685  entry of the child is omitted, and the directory view includes the metadata
686  that is stored on the directory edge).
687
688  The rw_uri field will be present in the information about a directory
689  if and only if you have read-write access to that directory. The verify_uri
690  field will be present if and only if the object has a verify-cap
691  (non-distributed LIT files do not have verify-caps).
692  
693  If the cap is of an unknown format, then the file size and verify_uri will
694  not be available::
695
696   GET /uri/$UNKNOWNCAP?t=json :
697
698    [ "unknown", {
699          "ro_uri": unknown_read_uri
700          } ]
701
702   GET /uri/$DIRCAP/[SUBDIRS../]UNKNOWNCHILDNAME?t=json :
703
704    [ "unknown", {
705          "rw_uri": unknown_write_uri,
706          "ro_uri": unknown_read_uri,
707          "mutable": true,
708          "metadata": {
709            "ctime": 1202777696.7564139,
710            "mtime": 1202777696.7564139,
711            "tahoe": {
712                  "linkcrtime": 1202777696.7564139,
713                  "linkmotime": 1202777696.7564139
714                  } } } ]
715
716  As in the case of file nodes, the metadata will only be present when the
717  capability is to a directory followed by a path. The "mutable" field is also
718  not always present; when it is absent, the mutability of the object is not
719  known.
720
721 About the metadata
722 ``````````````````
723
724 The value of the 'tahoe':'linkmotime' key is updated whenever a link to a
725 child is set. The value of the 'tahoe':'linkcrtime' key is updated whenever
726 a link to a child is created -- i.e. when there was not previously a link
727 under that name.
728
729 Note however, that if the edge in the Tahoe filesystem points to a mutable
730 file and the contents of that mutable file is changed, then the
731 'tahoe':'linkmotime' value on that edge will *not* be updated, since the
732 edge itself wasn't updated -- only the mutable file was.
733
734 The timestamps are represented as a number of seconds since the UNIX epoch
735 (1970-01-01 00:00:00 UTC), with leap seconds not being counted in the long
736 term.
737
738 In Tahoe earlier than v1.4.0, 'mtime' and 'ctime' keys were populated
739 instead of the 'tahoe':'linkmotime' and 'tahoe':'linkcrtime' keys. Starting
740 in Tahoe v1.4.0, the 'linkmotime'/'linkcrtime' keys in the 'tahoe' sub-dict
741 are populated. However, prior to Tahoe v1.7beta, a bug caused the 'tahoe'
742 sub-dict to be deleted by web-API requests in which new metadata is
743 specified, and not to be added to existing child links that lack it.
744
745 From Tahoe v1.7.0 onward, the 'mtime' and 'ctime' fields are no longer
746 populated or updated (see ticket #924), except by "tahoe backup" as
747 explained below. For backward compatibility, when an existing link is
748 updated and 'tahoe':'linkcrtime' is not present in the previous metadata
749 but 'ctime' is, the old value of 'ctime' is used as the new value of
750 'tahoe':'linkcrtime'.
751
752 The reason we added the new fields in Tahoe v1.4.0 is that there is a
753 "set_children" API (described below) which you can use to overwrite the
754 values of the 'mtime'/'ctime' pair, and this API is used by the
755 "tahoe backup" command (in Tahoe v1.3.0 and later) to set the 'mtime' and
756 'ctime' values when backing up files from a local filesystem into the
757 Tahoe filesystem. As of Tahoe v1.4.0, the set_children API cannot be used
758 to set anything under the 'tahoe' key of the metadata dict -- if you
759 include 'tahoe' keys in your 'metadata' arguments then it will silently
760 ignore those keys.
761
762 Therefore, if the 'tahoe' sub-dict is present, you can rely on the
763 'linkcrtime' and 'linkmotime' values therein to have the semantics described
764 above. (This is assuming that only official Tahoe clients have been used to
765 write those links, and that their system clocks were set to what you expected
766 -- there is nothing preventing someone from editing their Tahoe client or
767 writing their own Tahoe client which would overwrite those values however
768 they like, and there is nothing to constrain their system clock from taking
769 any value.)
770
771 When an edge is created or updated by "tahoe backup", the 'mtime' and
772 'ctime' keys on that edge are set as follows:
773
774 * 'mtime' is set to the timestamp read from the local filesystem for the
775   "mtime" of the local file in question, which means the last time the
776   contents of that file were changed.
777
778 * On Windows, 'ctime' is set to the creation timestamp for the file
779   read from the local filesystem. On other platforms, 'ctime' is set to
780   the UNIX "ctime" of the local file, which means the last time that
781   either the contents or the metadata of the local file was changed.
782
783 There are several ways that the 'ctime' field could be confusing: 
784
785 1. You might be confused about whether it reflects the time of the creation
786    of a link in the Tahoe filesystem (by a version of Tahoe < v1.7.0) or a
787    timestamp copied in by "tahoe backup" from a local filesystem.
788
789 2. You might be confused about whether it is a copy of the file creation
790    time (if "tahoe backup" was run on a Windows system) or of the last
791    contents-or-metadata change (if "tahoe backup" was run on a different
792    operating system).
793
794 3. You might be confused by the fact that changing the contents of a
795    mutable file in Tahoe doesn't have any effect on any links pointing at
796    that file in any directories, although "tahoe backup" sets the link
797    'ctime'/'mtime' to reflect timestamps about the local file corresponding
798    to the Tahoe file to which the link points.
799
800 4. Also, quite apart from Tahoe, you might be confused about the meaning
801    of the "ctime" in UNIX local filesystems, which people sometimes think
802    means file creation time, but which actually means, in UNIX local
803    filesystems, the most recent time that the file contents or the file
804    metadata (such as owner, permission bits, extended attributes, etc.)
805    has changed. Note that although "ctime" does not mean file creation time
806    in UNIX, links created by a version of Tahoe prior to v1.7.0, and never
807    written by "tahoe backup", will have 'ctime' set to the link creation
808    time.
809
810
811 Attaching an Existing File or Directory by its read- or write-cap
812 -----------------------------------------------------------------
813
814 ``PUT /uri/$DIRCAP/[SUBDIRS../]CHILDNAME?t=uri``
815
816  This attaches a child object (either a file or directory) to a specified
817  location in the virtual filesystem. The child object is referenced by its
818  read- or write- cap, as provided in the HTTP request body. This will create
819  intermediate directories as necessary.
820
821  This is similar to a UNIX hardlink: by referencing a previously-uploaded file
822  (or previously-created directory) instead of uploading/creating a new one,
823  you can create two references to the same object.
824
825  The read- or write- cap of the child is provided in the body of the HTTP
826  request, and this same cap is returned in the response body.
827
828  The default behavior is to overwrite any existing object at the same
829  location. To prevent this (and make the operation return an error instead
830  of overwriting), add a "replace=false" argument, as "?t=uri&replace=false".
831  With replace=false, this operation will return an HTTP 409 "Conflict" error
832  if there is already an object at the given location, rather than
833  overwriting the existing object. To allow the operation to overwrite a
834  file, but return an error when trying to overwrite a directory, use
835  "replace=only-files" (this behavior is closer to the traditional UNIX "mv"
836  command). Note that "true", "t", and "1" are all synonyms for "True", and
837  "false", "f", and "0" are synonyms for "False", and the parameter is
838  case-insensitive.
839  
840  Note that this operation does not take its child cap in the form of
841  separate "rw_uri" and "ro_uri" fields. Therefore, it cannot accept a
842  child cap in a format unknown to the web-API server, unless its URI
843  starts with "ro." or "imm.". This restriction is necessary because the
844  server is not able to attenuate an unknown write cap to a read cap.
845  Unknown URIs starting with "ro." or "imm.", on the other hand, are
846  assumed to represent read caps. The client should not prefix a write
847  cap with "ro." or "imm." and pass it to this operation, since that
848  would result in granting the cap's write authority to holders of the
849  directory read cap.
850
851
852 Adding Multiple Files or Directories to a Parent Directory at Once
853 ------------------------------------------------------------------
854
855 ``POST /uri/$DIRCAP/[SUBDIRS..]?t=set_children``
856
857 ``POST /uri/$DIRCAP/[SUBDIRS..]?t=set-children``    (Tahoe >= v1.6)
858
859  This command adds multiple children to a directory in a single operation.
860  It reads the request body and interprets it as a JSON-encoded description
861  of the child names and read/write-caps that should be added.
862
863  The body should be a JSON-encoded dictionary, in the same format as the
864  "children" value returned by the "GET /uri/$DIRCAP?t=json" operation
865  described above. In this format, each key is a child names, and the
866  corresponding value is a tuple of (type, childinfo). "type" is ignored, and
867  "childinfo" is a dictionary that contains "rw_uri", "ro_uri", and
868  "metadata" keys. You can take the output of "GET /uri/$DIRCAP1?t=json" and
869  use it as the input to "POST /uri/$DIRCAP2?t=set_children" to make DIR2
870  look very much like DIR1 (except for any existing children of DIR2 that
871  were not overwritten, and any existing "tahoe" metadata keys as described
872  below).
873
874  When the set_children request contains a child name that already exists in
875  the target directory, this command defaults to overwriting that child with
876  the new value (both child cap and metadata, but if the JSON data does not
877  contain a "metadata" key, the old child's metadata is preserved). The
878  command takes a boolean "overwrite=" query argument to control this
879  behavior. If you use "?t=set_children&overwrite=false", then an attempt to
880  replace an existing child will instead cause an error.
881
882  Any "tahoe" key in the new child's "metadata" value is ignored. Any
883  existing "tahoe" metadata is preserved. The metadata["tahoe"] value is
884  reserved for metadata generated by the tahoe node itself. The only two keys
885  currently placed here are "linkcrtime" and "linkmotime". For details, see
886  the section above entitled "Get Information About A File Or Directory (as
887  JSON)", in the "About the metadata" subsection.
888  
889  Note that this command was introduced with the name "set_children", which
890  uses an underscore rather than a hyphen as other multi-word command names
891  do. The variant with a hyphen is now accepted, but clients that desire
892  backward compatibility should continue to use "set_children".
893
894
895 Unlinking a File or Directory
896 -----------------------------
897
898 ``DELETE /uri/$DIRCAP/[SUBDIRS../]CHILDNAME``
899
900  This removes the given name from its parent directory. CHILDNAME is the
901  name to be removed, and $DIRCAP/SUBDIRS.. indicates the directory that will
902  be modified.
903
904  Note that this does not actually delete the file or directory that the name
905  points to from the tahoe grid -- it only unlinks the named reference from
906  this directory. If there are other names in this directory or in other
907  directories that point to the resource, then it will remain accessible
908  through those paths. Even if all names pointing to this object are removed
909  from their parent directories, then someone with possession of its read-cap
910  can continue to access the object through that cap.
911
912  The object will only become completely unreachable once 1: there are no
913  reachable directories that reference it, and 2: nobody is holding a read-
914  or write- cap to the object. (This behavior is very similar to the way
915  hardlinks and anonymous files work in traditional UNIX filesystems).
916
917  This operation will not modify more than a single directory. Intermediate
918  directories which were implicitly created by PUT or POST methods will *not*
919  be automatically removed by DELETE.
920
921  This method returns the file- or directory- cap of the object that was just
922  removed.
923
924
925 Browser Operations: Human-oriented interfaces
926 =============================================
927
928 This section describes the HTTP operations that provide support for humans
929 running a web browser. Most of these operations use HTML forms that use POST
930 to drive the Tahoe node. This section is intended for HTML authors who want
931 to write web pages that contain forms and buttons which manipulate the Tahoe
932 filesystem.
933
934 Note that for all POST operations, the arguments listed can be provided
935 either as URL query arguments or as form body fields. URL query arguments are
936 separated from the main URL by "?", and from each other by "&". For example,
937 "POST /uri/$DIRCAP?t=upload&mutable=true". Form body fields are usually
938 specified by using <input type="hidden"> elements. For clarity, the
939 descriptions below display the most significant arguments as URL query args.
940
941
942 Viewing A Directory (as HTML)
943 -----------------------------
944
945 ``GET /uri/$DIRCAP/[SUBDIRS../]``
946
947  This returns an HTML page, intended to be displayed to a human by a web
948  browser, which contains HREF links to all files and directories reachable
949  from this directory. These HREF links do not have a t= argument, meaning
950  that a human who follows them will get pages also meant for a human. It also
951  contains forms to upload new files, and to unlink files and directories
952  from their parent directory. Those forms use POST methods to do their job.
953
954
955 Viewing/Downloading a File
956 --------------------------
957
958 ``GET /uri/$FILECAP``
959
960 ``GET /uri/$DIRCAP/[SUBDIRS../]FILENAME``
961
962  This will retrieve the contents of the given file. The HTTP response body
963  will contain the sequence of bytes that make up the file.
964
965  If you want the HTTP response to include a useful Content-Type header,
966  either use the second form (which starts with a $DIRCAP), or add a
967  "filename=foo" query argument, like "GET /uri/$FILECAP?filename=foo.jpg".
968  The bare "GET /uri/$FILECAP" does not give the Tahoe node enough information
969  to determine a Content-Type (since Tahoe immutable files are merely
970  sequences of bytes, not typed+named file objects).
971
972  If the URL has both filename= and "save=true" in the query arguments, then
973  the server to add a "Content-Disposition: attachment" header, along with a
974  filename= parameter. When a user clicks on such a link, most browsers will
975  offer to let the user save the file instead of displaying it inline (indeed,
976  most browsers will refuse to display it inline). "true", "t", "1", and other
977  case-insensitive equivalents are all treated the same.
978
979  Character-set handling in URLs and HTTP headers is a dubious art [1]_. For
980  maximum compatibility, Tahoe simply copies the bytes from the filename=
981  argument into the Content-Disposition header's filename= parameter, without
982  trying to interpret them in any particular way.
983
984
985 ``GET /named/$FILECAP/FILENAME``
986
987  This is an alternate download form which makes it easier to get the correct
988  filename. The Tahoe server will provide the contents of the given file, with
989  a Content-Type header derived from the given filename. This form is used to
990  get browsers to use the "Save Link As" feature correctly, and also helps
991  command-line tools like "wget" and "curl" use the right filename. Note that
992  this form can *only* be used with file caps; it is an error to use a
993  directory cap after the /named/ prefix.
994
995
996 Getting Information About A File Or Directory (as HTML)
997 -------------------------------------------------------
998
999 ``GET /uri/$FILECAP?t=info``
1000
1001 ``GET /uri/$DIRCAP/?t=info``
1002
1003 ``GET /uri/$DIRCAP/[SUBDIRS../]SUBDIR/?t=info``
1004
1005 ``GET /uri/$DIRCAP/[SUBDIRS../]FILENAME?t=info``
1006
1007  This returns a human-oriented HTML page with more detail about the selected
1008  file or directory object. This page contains the following items:
1009
1010  * object size
1011  * storage index
1012  * JSON representation
1013  * raw contents (text/plain)
1014  * access caps (URIs): verify-cap, read-cap, write-cap (for mutable objects)
1015  * check/verify/repair form
1016  * deep-check/deep-size/deep-stats/manifest (for directories)
1017  * replace-conents form (for mutable files)
1018
1019
1020 Creating a Directory
1021 --------------------
1022
1023 ``POST /uri?t=mkdir``
1024
1025  This creates a new empty directory, but does not attach it to the virtual
1026  filesystem.
1027
1028  If a "redirect_to_result=true" argument is provided, then the HTTP response
1029  will cause the web browser to be redirected to a /uri/$DIRCAP page that
1030  gives access to the newly-created directory. If you bookmark this page,
1031  you'll be able to get back to the directory again in the future. This is the
1032  recommended way to start working with a Tahoe server: create a new unlinked
1033  directory (using redirect_to_result=true), then bookmark the resulting
1034  /uri/$DIRCAP page. There is a "create directory" button on the Welcome page
1035  to invoke this action.
1036
1037  If "redirect_to_result=true" is not provided (or is given a value of
1038  "false"), then the HTTP response body will simply be the write-cap of the
1039  new directory.
1040
1041 ``POST /uri/$DIRCAP/[SUBDIRS../]?t=mkdir&name=CHILDNAME``
1042
1043  This creates a new empty directory as a child of the designated SUBDIR. This
1044  will create additional intermediate directories as necessary.
1045
1046  If a "when_done=URL" argument is provided, the HTTP response will cause the
1047  web browser to redirect to the given URL. This provides a convenient way to
1048  return the browser to the directory that was just modified. Without a
1049  when_done= argument, the HTTP response will simply contain the write-cap of
1050  the directory that was just created.
1051
1052
1053 Uploading a File
1054 ----------------
1055
1056 ``POST /uri?t=upload``
1057
1058  This uploads a file, and produces a file-cap for the contents, but does not
1059  attach the file into the filesystem. No directories will be modified by
1060  this operation.
1061
1062  The file must be provided as the "file" field of an HTML encoded form body,
1063  produced in response to an HTML form like this::
1064  
1065   <form action="/uri" method="POST" enctype="multipart/form-data">
1066    <input type="hidden" name="t" value="upload" />
1067    <input type="file" name="file" />
1068    <input type="submit" value="Upload Unlinked" />
1069   </form>
1070
1071  If a "when_done=URL" argument is provided, the response body will cause the
1072  browser to redirect to the given URL. If the when_done= URL has the string
1073  "%(uri)s" in it, that string will be replaced by a URL-escaped form of the
1074  newly created file-cap. (Note that without this substitution, there is no
1075  way to access the file that was just uploaded).
1076
1077  The default (in the absence of when_done=) is to return an HTML page that
1078  describes the results of the upload. This page will contain information
1079  about which storage servers were used for the upload, how long each
1080  operation took, etc.
1081
1082  If a "mutable=true" argument is provided, the operation will create a
1083  mutable file, and the response body will contain the write-cap instead of
1084  the upload results page. The default is to create an immutable file,
1085  returning the upload results page as a response.
1086
1087
1088 ``POST /uri/$DIRCAP/[SUBDIRS../]?t=upload``
1089
1090  This uploads a file, and attaches it as a new child of the given directory,
1091  which must be mutable. The file must be provided as the "file" field of an
1092  HTML-encoded form body, produced in response to an HTML form like this::
1093  
1094   <form action="." method="POST" enctype="multipart/form-data">
1095    <input type="hidden" name="t" value="upload" />
1096    <input type="file" name="file" />
1097    <input type="submit" value="Upload" />
1098   </form>
1099
1100  A "name=" argument can be provided to specify the new child's name,
1101  otherwise it will be taken from the "filename" field of the upload form
1102  (most web browsers will copy the last component of the original file's
1103  pathname into this field). To avoid confusion, name= is not allowed to
1104  contain a slash.
1105
1106  If there is already a child with that name, and it is a mutable file, then
1107  its contents are replaced with the data being uploaded. If it is not a
1108  mutable file, the default behavior is to remove the existing child before
1109  creating a new one. To prevent this (and make the operation return an error
1110  instead of overwriting the old child), add a "replace=false" argument, as
1111  "?t=upload&replace=false". With replace=false, this operation will return an
1112  HTTP 409 "Conflict" error if there is already an object at the given
1113  location, rather than overwriting the existing object. Note that "true",
1114  "t", and "1" are all synonyms for "True", and "false", "f", and "0" are
1115  synonyms for "False". the parameter is case-insensitive.
1116
1117  This will create additional intermediate directories as necessary, although
1118  since it is expected to be triggered by a form that was retrieved by "GET
1119  /uri/$DIRCAP/[SUBDIRS../]", it is likely that the parent directory will
1120  already exist.
1121
1122  If a "mutable=true" argument is provided, any new file that is created will
1123  be a mutable file instead of an immutable one. <input type="checkbox"
1124  name="mutable" /> will give the user a way to set this option.
1125
1126  If a "when_done=URL" argument is provided, the HTTP response will cause the
1127  web browser to redirect to the given URL. This provides a convenient way to
1128  return the browser to the directory that was just modified. Without a
1129  when_done= argument, the HTTP response will simply contain the file-cap of
1130  the file that was just uploaded (a write-cap for mutable files, or a
1131  read-cap for immutable files).
1132
1133 ``POST /uri/$DIRCAP/[SUBDIRS../]FILENAME?t=upload``
1134
1135  This also uploads a file and attaches it as a new child of the given
1136  directory, which must be mutable. It is a slight variant of the previous
1137  operation, as the URL refers to the target file rather than the parent
1138  directory. It is otherwise identical: this accepts mutable= and when_done=
1139  arguments too.
1140
1141 ``POST /uri/$FILECAP?t=upload``
1142
1143  This modifies the contents of an existing mutable file in-place. An error is
1144  signalled if $FILECAP does not refer to a mutable file. It behaves just like
1145  the "PUT /uri/$FILECAP" form, but uses a POST for the benefit of HTML forms
1146  in a web browser.
1147
1148
1149 Attaching An Existing File Or Directory (by URI)
1150 ------------------------------------------------
1151
1152 ``POST /uri/$DIRCAP/[SUBDIRS../]?t=uri&name=CHILDNAME&uri=CHILDCAP``
1153
1154  This attaches a given read- or write- cap "CHILDCAP" to the designated
1155  directory, with a specified child name. This behaves much like the PUT t=uri
1156  operation, and is a lot like a UNIX hardlink. It is subject to the same
1157  restrictions as that operation on the use of cap formats unknown to the
1158  web-API server.
1159
1160  This will create additional intermediate directories as necessary, although
1161  since it is expected to be triggered by a form that was retrieved by "GET
1162  /uri/$DIRCAP/[SUBDIRS../]", it is likely that the parent directory will
1163  already exist.
1164
1165  This accepts the same replace= argument as POST t=upload.
1166
1167
1168 Unlinking A Child
1169 -----------------
1170
1171 ``POST /uri/$DIRCAP/[SUBDIRS../]?t=delete&name=CHILDNAME``
1172
1173 ``POST /uri/$DIRCAP/[SUBDIRS../]?t=unlink&name=CHILDNAME``
1174
1175  This instructs the node to remove a child object (file or subdirectory) from
1176  the given directory, which must be mutable. Note that the entire subtree is
1177  unlinked from the parent. Unlike deleting a subdirectory in a UNIX local
1178  filesystem, the subtree need not be empty; if it isn't, then other references
1179  into the subtree will see that the child subdirectories are not modified by
1180  this operation. Only the link from the given directory to its child is severed.
1181
1182  In Tahoe-LAFS v1.9.0 and later, t=unlink can be used as a synonym for t=delete.
1183  If interoperability with older web-API servers is required, t=delete should
1184  be used.
1185
1186
1187 Renaming A Child
1188 ----------------
1189
1190 ``POST /uri/$DIRCAP/[SUBDIRS../]?t=rename&from_name=OLD&to_name=NEW``
1191
1192  This instructs the node to rename a child of the given directory, which must
1193  be mutable. This has a similar effect to removing the child, then adding the
1194  same child-cap under the new name, except that it preserves metadata. This
1195  operation cannot move the child to a different directory.
1196
1197  This operation will replace any existing child of the new name, making it
1198  behave like the UNIX "``mv -f``" command.
1199
1200 Other Utilities
1201 ---------------
1202
1203 ``GET /uri?uri=$CAP``
1204
1205   This causes a redirect to /uri/$CAP, and retains any additional query
1206   arguments (like filename= or save=). This is for the convenience of web
1207   forms which allow the user to paste in a read- or write- cap (obtained
1208   through some out-of-band channel, like IM or email).
1209
1210   Note that this form merely redirects to the specific file or directory
1211   indicated by the $CAP: unlike the GET /uri/$DIRCAP form, you cannot
1212   traverse to children by appending additional path segments to the URL.
1213
1214 ``GET /uri/$DIRCAP/[SUBDIRS../]?t=rename-form&name=$CHILDNAME``
1215
1216   This provides a useful facility to browser-based user interfaces. It
1217   returns a page containing a form targetting the "POST $DIRCAP t=rename"
1218   functionality described above, with the provided $CHILDNAME present in the
1219   'from_name' field of that form. I.e. this presents a form offering to
1220   rename $CHILDNAME, requesting the new name, and submitting POST rename.
1221
1222 ``GET /uri/$DIRCAP/[SUBDIRS../]CHILDNAME?t=uri``
1223
1224  This returns the file- or directory- cap for the specified object.
1225
1226 ``GET /uri/$DIRCAP/[SUBDIRS../]CHILDNAME?t=readonly-uri``
1227
1228  This returns a read-only file- or directory- cap for the specified object.
1229  If the object is an immutable file, this will return the same value as
1230  t=uri.
1231
1232
1233 Debugging and Testing Features
1234 ------------------------------
1235
1236 These URLs are less-likely to be helpful to the casual Tahoe user, and are
1237 mainly intended for developers.
1238
1239 ``POST $URL?t=check``
1240
1241  This triggers the FileChecker to determine the current "health" of the
1242  given file or directory, by counting how many shares are available. The
1243  page that is returned will display the results. This can be used as a "show
1244  me detailed information about this file" page.
1245
1246  If a verify=true argument is provided, the node will perform a more
1247  intensive check, downloading and verifying every single bit of every share.
1248
1249  If an add-lease=true argument is provided, the node will also add (or
1250  renew) a lease to every share it encounters. Each lease will keep the share
1251  alive for a certain period of time (one month by default). Once the last
1252  lease expires or is explicitly cancelled, the storage server is allowed to
1253  delete the share.
1254
1255  If an output=JSON argument is provided, the response will be
1256  machine-readable JSON instead of human-oriented HTML. The data is a
1257  dictionary with the following keys::
1258
1259   storage-index: a base32-encoded string with the objects's storage index,
1260                                  or an empty string for LIT files
1261   summary: a string, with a one-line summary of the stats of the file
1262   results: a dictionary that describes the state of the file. For LIT files,
1263                    this dictionary has only the 'healthy' key, which will always be
1264                    True. For distributed files, this dictionary has the following
1265                    keys:
1266         count-shares-good: the number of good shares that were found
1267         count-shares-needed: 'k', the number of shares required for recovery
1268         count-shares-expected: 'N', the number of total shares generated
1269         count-good-share-hosts: this was intended to be the number of distinct
1270                                                         storage servers with good shares. It is currently
1271                                                         (as of Tahoe-LAFS v1.8.0) computed incorrectly;
1272                                                         see ticket #1115.
1273         count-wrong-shares: for mutable files, the number of shares for
1274                                                 versions other than the 'best' one (highest
1275                                                 sequence number, highest roothash). These are
1276                                                 either old ...
1277         count-recoverable-versions: for mutable files, the number of
1278                                                                 recoverable versions of the file. For
1279                                                                 a healthy file, this will equal 1.
1280         count-unrecoverable-versions: for mutable files, the number of
1281                                                                   unrecoverable versions of the file.
1282                                                                   For a healthy file, this will be 0.
1283         count-corrupt-shares: the number of shares with integrity failures
1284         list-corrupt-shares: a list of "share locators", one for each share
1285                                                  that was found to be corrupt. Each share locator
1286                                                  is a list of (serverid, storage_index, sharenum).
1287         needs-rebalancing: (bool) True if there are multiple shares on a single
1288                                            storage server, indicating a reduction in reliability
1289                                            that could be resolved by moving shares to new
1290                                            servers.
1291         servers-responding: list of base32-encoded storage server identifiers,
1292                                                 one for each server which responded to the share
1293                                                 query.
1294         healthy: (bool) True if the file is completely healthy, False otherwise.
1295                          Healthy files have at least N good shares. Overlapping shares
1296                          do not currently cause a file to be marked unhealthy. If there
1297                          are at least N good shares, then corrupt shares do not cause the
1298                          file to be marked unhealthy, although the corrupt shares will be
1299                          listed in the results (list-corrupt-shares) and should be manually
1300                          removed to wasting time in subsequent downloads (as the
1301                          downloader rediscovers the corruption and uses alternate shares).
1302                          Future compatibility: the meaning of this field may change to
1303                          reflect whether the servers-of-happiness criterion is met
1304                          (see ticket #614).
1305         sharemap: dict mapping share identifier to list of serverids
1306                           (base32-encoded strings). This indicates which servers are
1307                           holding which shares. For immutable files, the shareid is
1308                           an integer (the share number, from 0 to N-1). For
1309                           immutable files, it is a string of the form
1310                           'seq%d-%s-sh%d', containing the sequence number, the
1311                           roothash, and the share number.
1312
1313 ``POST $URL?t=start-deep-check``    (must add &ophandle=XYZ)
1314
1315  This initiates a recursive walk of all files and directories reachable from
1316  the target, performing a check on each one just like t=check. The result
1317  page will contain a summary of the results, including details on any
1318  file/directory that was not fully healthy.
1319
1320  t=start-deep-check can only be invoked on a directory. An error (400
1321  BAD_REQUEST) will be signalled if it is invoked on a file. The recursive
1322  walker will deal with loops safely.
1323
1324  This accepts the same verify= and add-lease= arguments as t=check.
1325
1326  Since this operation can take a long time (perhaps a second per object),
1327  the ophandle= argument is required (see "Slow Operations, Progress, and
1328  Cancelling" above). The response to this POST will be a redirect to the
1329  corresponding /operations/$HANDLE page (with output=HTML or output=JSON to
1330  match the output= argument given to the POST). The deep-check operation
1331  will continue to run in the background, and the /operations page should be
1332  used to find out when the operation is done.
1333
1334  Detailed check results for non-healthy files and directories will be
1335  available under /operations/$HANDLE/$STORAGEINDEX, and the HTML status will
1336  contain links to these detailed results.
1337
1338  The HTML /operations/$HANDLE page for incomplete operations will contain a
1339  meta-refresh tag, set to 60 seconds, so that a browser which uses
1340  deep-check will automatically poll until the operation has completed.
1341
1342  The JSON page (/options/$HANDLE?output=JSON) will contain a
1343  machine-readable JSON dictionary with the following keys::
1344
1345   finished: a boolean, True if the operation is complete, else False. Some
1346                         of the remaining keys may not be present until the operation
1347                         is complete.
1348   root-storage-index: a base32-encoded string with the storage index of the
1349                                           starting point of the deep-check operation
1350   count-objects-checked: count of how many objects were checked. Note that
1351                                                  non-distributed objects (i.e. small immutable LIT
1352                                                  files) are not checked, since for these objects,
1353                                                  the data is contained entirely in the URI.
1354   count-objects-healthy: how many of those objects were completely healthy
1355   count-objects-unhealthy: how many were damaged in some way
1356   count-corrupt-shares: how many shares were found to have corruption,
1357                                                 summed over all objects examined
1358   list-corrupt-shares: a list of "share identifiers", one for each share
1359                                            that was found to be corrupt. Each share identifier
1360                                            is a list of (serverid, storage_index, sharenum).
1361   list-unhealthy-files: a list of (pathname, check-results) tuples, for
1362                                                 each file that was not fully healthy. 'pathname' is
1363                                                 a list of strings (which can be joined by "/"
1364                                                 characters to turn it into a single string),
1365                                                 relative to the directory on which deep-check was
1366                                                 invoked. The 'check-results' field is the same as
1367                                                 that returned by t=check&output=JSON, described
1368                                                 above.
1369   stats: a dictionary with the same keys as the t=start-deep-stats command
1370                  (described below)
1371
1372 ``POST $URL?t=stream-deep-check``
1373
1374  This initiates a recursive walk of all files and directories reachable from
1375  the target, performing a check on each one just like t=check. For each
1376  unique object (duplicates are skipped), a single line of JSON is emitted to
1377  the HTTP response channel (or an error indication, see below). When the walk
1378  is complete, a final line of JSON is emitted which contains the accumulated
1379  file-size/count "deep-stats" data.
1380
1381  This command takes the same arguments as t=start-deep-check.
1382
1383  A CLI tool can split the response stream on newlines into "response units",
1384  and parse each response unit as JSON. Each such parsed unit will be a
1385  dictionary, and will contain at least the "type" key: a string, one of
1386  "file", "directory", or "stats".
1387
1388  For all units that have a type of "file" or "directory", the dictionary will
1389  contain the following keys::
1390
1391   "path": a list of strings, with the path that is traversed to reach the
1392           object
1393   "cap": a write-cap URI for the file or directory, if available, else a
1394          read-cap URI
1395   "verifycap": a verify-cap URI for the file or directory
1396   "repaircap": an URI for the weakest cap that can still be used to repair
1397                the object
1398   "storage-index": a base32 storage index for the object
1399   "check-results": a copy of the dictionary which would be returned by
1400                    t=check&output=json, with three top-level keys:
1401                    "storage-index", "summary", and "results", and a variety
1402                    of counts and sharemaps in the "results" value.
1403
1404  Note that non-distributed files (i.e. LIT files) will have values of None
1405  for verifycap, repaircap, and storage-index, since these files can neither
1406  be verified nor repaired, and are not stored on the storage servers.
1407  Likewise the check-results dictionary will be limited: an empty string for
1408  storage-index, and a results dictionary with only the "healthy" key.
1409
1410  The last unit in the stream will have a type of "stats", and will contain
1411  the keys described in the "start-deep-stats" operation, below.
1412
1413  If any errors occur during the traversal (specifically if a directory is
1414  unrecoverable, such that further traversal is not possible), an error
1415  indication is written to the response body, instead of the usual line of
1416  JSON. This error indication line will begin with the string "ERROR:" (in all
1417  caps), and contain a summary of the error on the rest of the line. The
1418  remaining lines of the response body will be a python exception. The client
1419  application should look for the ERROR: and stop processing JSON as soon as
1420  it is seen. Note that neither a file being unrecoverable nor a directory
1421  merely being unhealthy will cause traversal to stop. The line just before
1422  the ERROR: will describe the directory that was untraversable, since the
1423  unit is emitted to the HTTP response body before the child is traversed.
1424
1425
1426 ``POST $URL?t=check&repair=true``
1427
1428  This performs a health check of the given file or directory, and if the
1429  checker determines that the object is not healthy (some shares are missing
1430  or corrupted), it will perform a "repair". During repair, any missing
1431  shares will be regenerated and uploaded to new servers.
1432
1433  This accepts the same verify=true and add-lease= arguments as t=check. When
1434  an output=JSON argument is provided, the machine-readable JSON response
1435  will contain the following keys::
1436
1437   storage-index: a base32-encoded string with the objects's storage index,
1438                                  or an empty string for LIT files
1439   repair-attempted: (bool) True if repair was attempted
1440   repair-successful: (bool) True if repair was attempted and the file was
1441                                          fully healthy afterwards. False if no repair was
1442                                          attempted, or if a repair attempt failed.
1443   pre-repair-results: a dictionary that describes the state of the file
1444                                           before any repair was performed. This contains exactly
1445                                           the same keys as the 'results' value of the t=check
1446                                           response, described above.
1447   post-repair-results: a dictionary that describes the state of the file
1448                                            after any repair was performed. If no repair was
1449                                            performed, post-repair-results and pre-repair-results
1450                                            will be the same. This contains exactly the same keys
1451                                            as the 'results' value of the t=check response,
1452                                            described above.
1453
1454 ``POST $URL?t=start-deep-check&repair=true``    (must add &ophandle=XYZ)
1455
1456  This triggers a recursive walk of all files and directories, performing a
1457  t=check&repair=true on each one.
1458
1459  Like t=start-deep-check without the repair= argument, this can only be
1460  invoked on a directory. An error (400 BAD_REQUEST) will be signalled if it
1461  is invoked on a file. The recursive walker will deal with loops safely.
1462
1463  This accepts the same verify= and add-lease= arguments as
1464  t=start-deep-check. It uses the same ophandle= mechanism as
1465  start-deep-check. When an output=JSON argument is provided, the response
1466  will contain the following keys::
1467
1468   finished: (bool) True if the operation has completed, else False
1469   root-storage-index: a base32-encoded string with the storage index of the
1470                                           starting point of the deep-check operation
1471   count-objects-checked: count of how many objects were checked
1472
1473   count-objects-healthy-pre-repair: how many of those objects were completely
1474                                                                         healthy, before any repair
1475   count-objects-unhealthy-pre-repair: how many were damaged in some way
1476   count-objects-healthy-post-repair: how many of those objects were completely
1477                                                                           healthy, after any repair
1478   count-objects-unhealthy-post-repair: how many were damaged in some way
1479
1480   count-repairs-attempted: repairs were attempted on this many objects.
1481   count-repairs-successful: how many repairs resulted in healthy objects
1482   count-repairs-unsuccessful: how many repairs resulted did not results in
1483                                                           completely healthy objects
1484   count-corrupt-shares-pre-repair: how many shares were found to have
1485                                                                    corruption, summed over all objects
1486                                                                    examined, before any repair
1487   count-corrupt-shares-post-repair: how many shares were found to have
1488                                                                         corruption, summed over all objects
1489                                                                         examined, after any repair
1490   list-corrupt-shares: a list of "share identifiers", one for each share
1491                                            that was found to be corrupt (before any repair).
1492                                            Each share identifier is a list of (serverid,
1493                                            storage_index, sharenum).
1494   list-remaining-corrupt-shares: like list-corrupt-shares, but mutable shares
1495                                                                  that were successfully repaired are not
1496                                                                  included. These are shares that need
1497                                                                  manual processing. Since immutable shares
1498                                                                  cannot be modified by clients, all corruption
1499                                                                  in immutable shares will be listed here.
1500   list-unhealthy-files: a list of (pathname, check-results) tuples, for
1501                                                 each file that was not fully healthy. 'pathname' is
1502                                                 relative to the directory on which deep-check was
1503                                                 invoked. The 'check-results' field is the same as
1504                                                 that returned by t=check&repair=true&output=JSON,
1505                                                 described above.
1506   stats: a dictionary with the same keys as the t=start-deep-stats command
1507                  (described below)
1508
1509 ``POST $URL?t=stream-deep-check&repair=true``
1510
1511  This triggers a recursive walk of all files and directories, performing a
1512  t=check&repair=true on each one. For each unique object (duplicates are
1513  skipped), a single line of JSON is emitted to the HTTP response channel (or
1514  an error indication). When the walk is complete, a final line of JSON is
1515  emitted which contains the accumulated file-size/count "deep-stats" data.
1516
1517  This emits the same data as t=stream-deep-check (without the repair=true),
1518  except that the "check-results" field is replaced with a
1519  "check-and-repair-results" field, which contains the keys returned by
1520  t=check&repair=true&output=json (i.e. repair-attempted, repair-successful,
1521  pre-repair-results, and post-repair-results). The output does not contain
1522  the summary dictionary that is provied by t=start-deep-check&repair=true
1523  (the one with count-objects-checked and list-unhealthy-files), since the
1524  receiving client is expected to calculate those values itself from the
1525  stream of per-object check-and-repair-results.
1526
1527  Note that the "ERROR:" indication will only be emitted if traversal stops,
1528  which will only occur if an unrecoverable directory is encountered. If a
1529  file or directory repair fails, the traversal will continue, and the repair
1530  failure will be indicated in the JSON data (in the "repair-successful" key).
1531
1532 ``POST $DIRURL?t=start-manifest``    (must add &ophandle=XYZ)
1533
1534  This operation generates a "manfest" of the given directory tree, mostly
1535  for debugging. This is a table of (path, filecap/dircap), for every object
1536  reachable from the starting directory. The path will be slash-joined, and
1537  the filecap/dircap will contain a link to the object in question. This page
1538  gives immediate access to every object in the virtual filesystem subtree.
1539
1540  This operation uses the same ophandle= mechanism as deep-check. The
1541  corresponding /operations/$HANDLE page has three different forms. The
1542  default is output=HTML.
1543
1544  If output=text is added to the query args, the results will be a text/plain
1545  list. The first line is special: it is either "finished: yes" or "finished:
1546  no"; if the operation is not finished, you must periodically reload the
1547  page until it completes. The rest of the results are a plaintext list, with
1548  one file/dir per line, slash-separated, with the filecap/dircap separated
1549  by a space.
1550
1551  If output=JSON is added to the queryargs, then the results will be a
1552  JSON-formatted dictionary with six keys. Note that because large directory
1553  structures can result in very large JSON results, the full results will not
1554  be available until the operation is complete (i.e. until output["finished"]
1555  is True)::
1556
1557   finished (bool): if False then you must reload the page until True
1558   origin_si (base32 str): the storage index of the starting point
1559   manifest: list of (path, cap) tuples, where path is a list of strings.
1560   verifycaps: list of (printable) verify cap strings
1561   storage-index: list of (base32) storage index strings
1562   stats: a dictionary with the same keys as the t=start-deep-stats command
1563                  (described below)
1564
1565 ``POST $DIRURL?t=start-deep-size``   (must add &ophandle=XYZ)
1566
1567  This operation generates a number (in bytes) containing the sum of the
1568  filesize of all directories and immutable files reachable from the given
1569  directory. This is a rough lower bound of the total space consumed by this
1570  subtree. It does not include space consumed by mutable files, nor does it
1571  take expansion or encoding overhead into account. Later versions of the
1572  code may improve this estimate upwards.
1573
1574  The /operations/$HANDLE status output consists of two lines of text::
1575
1576   finished: yes
1577   size: 1234
1578
1579 ``POST $DIRURL?t=start-deep-stats``    (must add &ophandle=XYZ)
1580
1581  This operation performs a recursive walk of all files and directories
1582  reachable from the given directory, and generates a collection of
1583  statistics about those objects.
1584
1585  The result (obtained from the /operations/$OPHANDLE page) is a
1586  JSON-serialized dictionary with the following keys (note that some of these
1587  keys may be missing until 'finished' is True)::
1588
1589   finished: (bool) True if the operation has finished, else False
1590   count-immutable-files: count of how many CHK files are in the set
1591   count-mutable-files: same, for mutable files (does not include directories)
1592   count-literal-files: same, for LIT files (data contained inside the URI)
1593   count-files: sum of the above three
1594   count-directories: count of directories
1595   count-unknown: count of unrecognized objects (perhaps from the future)
1596   size-immutable-files: total bytes for all CHK files in the set, =deep-size
1597   size-mutable-files (TODO): same, for current version of all mutable files
1598   size-literal-files: same, for LIT files
1599   size-directories: size of directories (includes size-literal-files)
1600   size-files-histogram: list of (minsize, maxsize, count) buckets,
1601                                                 with a histogram of filesizes, 5dB/bucket,
1602                                                 for both literal and immutable files
1603   largest-directory: number of children in the largest directory
1604   largest-immutable-file: number of bytes in the largest CHK file
1605
1606  size-mutable-files is not implemented, because it would require extra
1607  queries to each mutable file to get their size. This may be implemented in
1608  the future.
1609
1610  Assuming no sharing, the basic space consumed by a single root directory is
1611  the sum of size-immutable-files, size-mutable-files, and size-directories.
1612  The actual disk space used by the shares is larger, because of the
1613  following sources of overhead::
1614
1615   integrity data
1616   expansion due to erasure coding
1617   share management data (leases)
1618   backend (ext3) minimum block size
1619
1620 ``POST $URL?t=stream-manifest``
1621
1622  This operation performs a recursive walk of all files and directories
1623  reachable from the given starting point. For each such unique object
1624  (duplicates are skipped), a single line of JSON is emitted to the HTTP
1625  response channel (or an error indication, see below). When the walk is
1626  complete, a final line of JSON is emitted which contains the accumulated
1627  file-size/count "deep-stats" data.
1628
1629  A CLI tool can split the response stream on newlines into "response units",
1630  and parse each response unit as JSON. Each such parsed unit will be a
1631  dictionary, and will contain at least the "type" key: a string, one of
1632  "file", "directory", or "stats".
1633
1634  For all units that have a type of "file" or "directory", the dictionary will
1635  contain the following keys::
1636
1637   "path": a list of strings, with the path that is traversed to reach the
1638           object
1639   "cap": a write-cap URI for the file or directory, if available, else a
1640          read-cap URI
1641   "verifycap": a verify-cap URI for the file or directory
1642   "repaircap": an URI for the weakest cap that can still be used to repair
1643                the object
1644   "storage-index": a base32 storage index for the object
1645
1646  Note that non-distributed files (i.e. LIT files) will have values of None
1647  for verifycap, repaircap, and storage-index, since these files can neither
1648  be verified nor repaired, and are not stored on the storage servers.
1649
1650  The last unit in the stream will have a type of "stats", and will contain
1651  the keys described in the "start-deep-stats" operation, below.
1652
1653  If any errors occur during the traversal (specifically if a directory is
1654  unrecoverable, such that further traversal is not possible), an error
1655  indication is written to the response body, instead of the usual line of
1656  JSON. This error indication line will begin with the string "ERROR:" (in all
1657  caps), and contain a summary of the error on the rest of the line. The
1658  remaining lines of the response body will be a python exception. The client
1659  application should look for the ERROR: and stop processing JSON as soon as
1660  it is seen. The line just before the ERROR: will describe the directory that
1661  was untraversable, since the manifest entry is emitted to the HTTP response
1662  body before the child is traversed.
1663
1664
1665 Other Useful Pages
1666 ==================
1667
1668 The portion of the web namespace that begins with "/uri" (and "/named") is
1669 dedicated to giving users (both humans and programs) access to the Tahoe
1670 virtual filesystem. The rest of the namespace provides status information
1671 about the state of the Tahoe node.
1672
1673 ``GET /``   (the root page)
1674
1675 This is the "Welcome Page", and contains a few distinct sections::
1676
1677  Node information: library versions, local nodeid, services being provided.
1678
1679  Filesystem Access Forms: create a new directory, view a file/directory by
1680                           URI, upload a file (unlinked), download a file by
1681                           URI.
1682
1683  Grid Status: introducer information, helper information, connected storage
1684               servers.
1685
1686 ``GET /status/``
1687
1688  This page lists all active uploads and downloads, and contains a short list
1689  of recent upload/download operations. Each operation has a link to a page
1690  that describes file sizes, servers that were involved, and the time consumed
1691  in each phase of the operation.
1692
1693  A GET of /status/?t=json will contain a machine-readable subset of the same
1694  data. It returns a JSON-encoded dictionary. The only key defined at this
1695  time is "active", with a value that is a list of operation dictionaries, one
1696  for each active operation. Once an operation is completed, it will no longer
1697  appear in data["active"] .
1698
1699  Each op-dict contains a "type" key, one of "upload", "download",
1700  "mapupdate", "publish", or "retrieve" (the first two are for immutable
1701  files, while the latter three are for mutable files and directories).
1702
1703  The "upload" op-dict will contain the following keys::
1704
1705   type (string): "upload"
1706   storage-index-string (string): a base32-encoded storage index
1707   total-size (int): total size of the file
1708   status (string): current status of the operation
1709   progress-hash (float): 1.0 when the file has been hashed
1710   progress-ciphertext (float): 1.0 when the file has been encrypted.
1711   progress-encode-push (float): 1.0 when the file has been encoded and
1712                                                                 pushed to the storage servers. For helper
1713                                                                 uploads, the ciphertext value climbs to 1.0
1714                                                                 first, then encoding starts. For unassisted
1715                                                                 uploads, ciphertext and encode-push progress
1716                                                                 will climb at the same pace.
1717
1718  The "download" op-dict will contain the following keys::
1719
1720   type (string): "download"
1721   storage-index-string (string): a base32-encoded storage index
1722   total-size (int): total size of the file
1723   status (string): current status of the operation
1724   progress (float): 1.0 when the file has been fully downloaded
1725
1726  Front-ends which want to report progress information are advised to simply
1727  average together all the progress-* indicators. A slightly more accurate
1728  value can be found by ignoring the progress-hash value (since the current
1729  implementation hashes synchronously, so clients will probably never see
1730  progress-hash!=1.0).
1731
1732 ``GET /provisioning/``
1733
1734  This page provides a basic tool to predict the likely storage and bandwidth
1735  requirements of a large Tahoe grid. It provides forms to input things like
1736  total number of users, number of files per user, average file size, number
1737  of servers, expansion ratio, hard drive failure rate, etc. It then provides
1738  numbers like how many disks per server will be needed, how many read
1739  operations per second should be expected, and the likely MTBF for files in
1740  the grid. This information is very preliminary, and the model upon which it
1741  is based still needs a lot of work.
1742
1743 ``GET /helper_status/``
1744
1745  If the node is running a helper (i.e. if [helper]enabled is set to True in
1746  tahoe.cfg), then this page will provide a list of all the helper operations
1747  currently in progress. If "?t=json" is added to the URL, it will return a
1748  JSON-formatted list of helper statistics, which can then be used to produce
1749  graphs to indicate how busy the helper is.
1750
1751 ``GET /statistics/``
1752
1753  This page provides "node statistics", which are collected from a variety of
1754  sources::
1755
1756    load_monitor: every second, the node schedules a timer for one second in
1757                  the future, then measures how late the subsequent callback
1758                  is. The "load_average" is this tardiness, measured in
1759                  seconds, averaged over the last minute. It is an indication
1760                  of a busy node, one which is doing more work than can be
1761                  completed in a timely fashion. The "max_load" value is the
1762                  highest value that has been seen in the last 60 seconds.
1763
1764    cpu_monitor: every minute, the node uses time.clock() to measure how much
1765                 CPU time it has used, and it uses this value to produce
1766                 1min/5min/15min moving averages. These values range from 0%
1767                 (0.0) to 100% (1.0), and indicate what fraction of the CPU
1768                 has been used by the Tahoe node. Not all operating systems
1769                 provide meaningful data to time.clock(): they may report 100%
1770                 CPU usage at all times.
1771
1772    uploader: this counts how many immutable files (and bytes) have been
1773              uploaded since the node was started
1774
1775    downloader: this counts how many immutable files have been downloaded
1776                since the node was started
1777
1778    publishes: this counts how many mutable files (including directories) have
1779               been modified since the node was started
1780
1781    retrieves: this counts how many mutable files (including directories) have
1782               been read since the node was started
1783
1784  There are other statistics that are tracked by the node. The "raw stats"
1785  section shows a formatted dump of all of them.
1786
1787  By adding "?t=json" to the URL, the node will return a JSON-formatted
1788  dictionary of stats values, which can be used by other tools to produce
1789  graphs of node behavior. The misc/munin/ directory in the source
1790  distribution provides some tools to produce these graphs.
1791
1792 ``GET /``   (introducer status)
1793
1794  For Introducer nodes, the welcome page displays information about both
1795  clients and servers which are connected to the introducer. Servers make
1796  "service announcements", and these are listed in a table. Clients will
1797  subscribe to hear about service announcements, and these subscriptions are
1798  listed in a separate table. Both tables contain information about what
1799  version of Tahoe is being run by the remote node, their advertised and
1800  outbound IP addresses, their nodeid and nickname, and how long they have
1801  been available.
1802
1803  By adding "?t=json" to the URL, the node will return a JSON-formatted
1804  dictionary of stats values, which can be used to produce graphs of connected
1805  clients over time. This dictionary has the following keys::
1806
1807   ["subscription_summary"] : a dictionary mapping service name (like
1808                              "storage") to an integer with the number of
1809                              clients that have subscribed to hear about that
1810                              service
1811   ["announcement_summary"] : a dictionary mapping service name to an integer
1812                              with the number of servers which are announcing
1813                              that service
1814   ["announcement_distinct_hosts"] : a dictionary mapping service name to an
1815                                     integer which represents the number of
1816                                     distinct hosts that are providing that
1817                                     service. If two servers have announced
1818                                     FURLs which use the same hostnames (but
1819                                     different ports and tubids), they are
1820                                     considered to be on the same host.
1821
1822
1823 Static Files in /public_html
1824 ============================
1825
1826 The web-API server will take any request for a URL that starts with /static
1827 and serve it from a configurable directory which defaults to
1828 $BASEDIR/public_html . This is configured by setting the "[node]web.static"
1829 value in $BASEDIR/tahoe.cfg . If this is left at the default value of
1830 "public_html", then http://localhost:3456/static/subdir/foo.html will be
1831 served with the contents of the file $BASEDIR/public_html/subdir/foo.html .
1832
1833 This can be useful to serve a javascript application which provides a
1834 prettier front-end to the rest of the Tahoe web-API.
1835
1836
1837 Safety and Security Issues -- Names vs. URIs
1838 ============================================
1839
1840 Summary: use explicit file- and dir- caps whenever possible, to reduce the
1841 potential for surprises when the filesystem structure is changed.
1842
1843 Tahoe provides a mutable filesystem, but the ways that the filesystem can
1844 change are limited. The only thing that can change is that the mapping from
1845 child names to child objects that each directory contains can be changed by
1846 adding a new child name pointing to an object, removing an existing child name,
1847 or changing an existing child name to point to a different object.
1848
1849 Obviously if you query Tahoe for information about the filesystem and then act
1850 to change the filesystem (such as by getting a listing of the contents of a
1851 directory and then adding a file to the directory), then the filesystem might
1852 have been changed after you queried it and before you acted upon it.  However,
1853 if you use the URI instead of the pathname of an object when you act upon the
1854 object, then the only change that can happen is if the object is a directory
1855 then the set of child names it has might be different. If, on the other hand,
1856 you act upon the object using its pathname, then a different object might be in
1857 that place, which can result in more kinds of surprises.
1858
1859 For example, suppose you are writing code which recursively downloads the
1860 contents of a directory. The first thing your code does is fetch the listing
1861 of the contents of the directory. For each child that it fetched, if that
1862 child is a file then it downloads the file, and if that child is a directory
1863 then it recurses into that directory. Now, if the download and the recurse
1864 actions are performed using the child's name, then the results might be
1865 wrong, because for example a child name that pointed to a sub-directory when
1866 you listed the directory might have been changed to point to a file (in which
1867 case your attempt to recurse into it would result in an error and the file
1868 would be skipped), or a child name that pointed to a file when you listed the
1869 directory might now point to a sub-directory (in which case your attempt to
1870 download the child would result in a file containing HTML text describing the
1871 sub-directory!).
1872
1873 If your recursive algorithm uses the uri of the child instead of the name of
1874 the child, then those kinds of mistakes just can't happen. Note that both the
1875 child's name and the child's URI are included in the results of listing the
1876 parent directory, so it isn't any harder to use the URI for this purpose.
1877
1878 The read and write caps in a given directory node are separate URIs, and
1879 can't be assumed to point to the same object even if they were retrieved in
1880 the same operation (although the web-API server attempts to ensure this
1881 in most cases). If you need to rely on that property, you should explicitly
1882 verify it. More generally, you should not make assumptions about the
1883 internal consistency of the contents of mutable directories. As a result
1884 of the signatures on mutable object versions, it is guaranteed that a given
1885 version was written in a single update, but -- as in the case of a file --
1886 the contents may have been chosen by a malicious writer in a way that is
1887 designed to confuse applications that rely on their consistency.
1888
1889 In general, use names if you want "whatever object (whether file or
1890 directory) is found by following this name (or sequence of names) when my
1891 request reaches the server". Use URIs if you want "this particular object".
1892
1893
1894 Concurrency Issues
1895 ==================
1896
1897 Tahoe uses both mutable and immutable files. Mutable files can be created
1898 explicitly by doing an upload with ?mutable=true added, or implicitly by
1899 creating a new directory (since a directory is just a special way to
1900 interpret a given mutable file).
1901
1902 Mutable files suffer from the same consistency-vs-availability tradeoff that
1903 all distributed data storage systems face. It is not possible to
1904 simultaneously achieve perfect consistency and perfect availability in the
1905 face of network partitions (servers being unreachable or faulty).
1906
1907 Tahoe tries to achieve a reasonable compromise, but there is a basic rule in
1908 place, known as the Prime Coordination Directive: "Don't Do That". What this
1909 means is that if write-access to a mutable file is available to several
1910 parties, then those parties are responsible for coordinating their activities
1911 to avoid multiple simultaneous updates. This could be achieved by having
1912 these parties talk to each other and using some sort of locking mechanism, or
1913 by serializing all changes through a single writer.
1914
1915 The consequences of performing uncoordinated writes can vary. Some of the
1916 writers may lose their changes, as somebody else wins the race condition. In
1917 many cases the file will be left in an "unhealthy" state, meaning that there
1918 are not as many redundant shares as we would like (reducing the reliability
1919 of the file against server failures). In the worst case, the file can be left
1920 in such an unhealthy state that no version is recoverable, even the old ones.
1921 It is this small possibility of data loss that prompts us to issue the Prime
1922 Coordination Directive.
1923
1924 Tahoe nodes implement internal serialization to make sure that a single Tahoe
1925 node cannot conflict with itself. For example, it is safe to issue two
1926 directory modification requests to a single tahoe node's web-API server at the
1927 same time, because the Tahoe node will internally delay one of them until
1928 after the other has finished being applied. (This feature was introduced in
1929 Tahoe-1.1; back with Tahoe-1.0 the web client was responsible for serializing
1930 web requests themselves).
1931
1932 For more details, please see the "Consistency vs Availability" and "The Prime
1933 Coordination Directive" sections of `mutable.rst <../specifications/mutable.rst>`_.
1934
1935
1936 .. [1] URLs and HTTP and UTF-8, Oh My
1937
1938  HTTP does not provide a mechanism to specify the character set used to
1939  encode non-ASCII names in URLs
1940  (`RFC3986#2.1 <http://tools.ietf.org/html/rfc3986#section-2.1>`_).
1941  We prefer the convention that the ``filename=`` argument shall be a
1942  URL-escaped UTF-8 encoded Unicode string.
1943  For example, suppose we want to provoke the server into using a filename of
1944  "f i a n c e-acute e" (i.e. f i a n c U+00E9 e). The UTF-8 encoding of this
1945  is 0x66 0x69 0x61 0x6e 0x63 0xc3 0xa9 0x65 (or "fianc\\xC3\\xA9e", as python's
1946  ``repr()`` function would show). To encode this into a URL, the non-printable
1947  characters must be escaped with the urlencode ``%XX`` mechanism, giving
1948  us "fianc%C3%A9e". Thus, the first line of the HTTP request will be
1949  "``GET /uri/CAP...?save=true&filename=fianc%C3%A9e HTTP/1.1``". Not all
1950  browsers provide this: IE7 by default uses the Latin-1 encoding, which is
1951  "fianc%E9e" (although it has a configuration option to send URLs as UTF-8).
1952
1953  The response header will need to indicate a non-ASCII filename. The actual
1954  mechanism to do this is not clear. For ASCII filenames, the response header
1955  would look like::
1956
1957   Content-Disposition: attachment; filename="english.txt"
1958
1959  If Tahoe were to enforce the UTF-8 convention, it would need to decode the
1960  URL argument into a Unicode string, and then encode it back into a sequence
1961  of bytes when creating the response header. One possibility would be to use
1962  unencoded UTF-8. Developers suggest that IE7 might accept this::
1963
1964   #1: Content-Disposition: attachment; filename="fianc\xC3\xA9e"
1965     (note, the last four bytes of that line, not including the newline, are
1966     0xC3 0xA9 0x65 0x22)
1967
1968  `RFC2231#4 <http://tools.ietf.org/html/rfc2231#section-4>`_
1969  (dated 1997): suggests that the following might work, and
1970  `some developers have reported <http://markmail.org/message/dsjyokgl7hv64ig3>`_
1971  that it is supported by Firefox (but not IE7)::
1972
1973   #2: Content-Disposition: attachment; filename*=utf-8''fianc%C3%A9e
1974
1975  My reading of `RFC2616#19.5.1 <http://tools.ietf.org/html/rfc2616#section-19.5.1>`_
1976  (which defines Content-Disposition) says that the filename= parameter is
1977  defined to be wrapped in quotes (presumably to allow spaces without breaking
1978  the parsing of subsequent parameters), which would give us::
1979
1980   #3: Content-Disposition: attachment; filename*=utf-8''"fianc%C3%A9e"
1981
1982  However this is contrary to the examples in the email thread listed above.
1983
1984  Developers report that IE7 (when it is configured for UTF-8 URL encoding,
1985  which is not the default in Asian countries), will accept::
1986
1987   #4: Content-Disposition: attachment; filename=fianc%C3%A9e
1988
1989  However, for maximum compatibility, Tahoe simply copies bytes from the URL
1990  into the response header, rather than enforcing the UTF-8 convention. This
1991  means it does not try to decode the filename from the URL argument, nor does
1992  it encode the filename into the response header.