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