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