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