Debian Codegraph @

terps/tads/tads3/vmnetfil.cpp

raw symbols SCIP
1 #ifdef RCSID
2 static char RCSid[] =
3 "$Header$";
4 #endif
5
6 /* Copyright (c) 2010 by Michael J. Roberts. All Rights Reserved. */
7 /*
8 Name
9 vmnetfil.cpp - network file operations
10 Function
11 This module contains the network storage server implementation of
12 CVmNetFile.
13 Notes
14
15 Modified
16 09/08/10 MJRoberts - Creation
17 */
18
19 #include "t3std.h"
20 #include "os.h"
21 #include "osifcnet.h"
22 #include "vmnetfil.h"
23 #include "vmnet.h"
24 #include "vmfile.h"
25 #include "vmdatasrc.h"
26 #include "vmerr.h"
27 #include "vmerrnum.h"
28 #include "vmrun.h"
29 #include "vmglob.h"
30 #include "vmpredef.h"
31 #include "vmimport.h"
32 #include "sha2.h"
33 #include "vmhash.h"
34 #include "vmbif.h"
35 #include "vmtype.h"
36 #include "vmobj.h"
37 #include "vmtmpfil.h"
38 #include "vmtobj.h"
39
40
41 /* ------------------------------------------------------------------------ */
42 /*
43 * Ticket generator. Generates the storage server "ticket" for a given
44 * filename. The buffer must be at least 65 characters long.
45 *
46 * The ticket authenticates the game server to the storage server by
47 * proving that the game server has a valid API key, which is the
48 * equivalent of a password.
49 */
50 class ServerTicket
51 {
52 public:
53 ServerTicket(VMG_ const char *fname, int sfid)
54 {
55 /*
56 * The ticket formula is as follows:
57 *
58 *. hash1 = SHA256(fname : gameServerID)
59 *. ticket = SHA256(hash1 : apiKey)
60 *
61 * The filename must be the fully qualified filename with session
62 * ID prefix, of the form ~SID/path.
63 *
64 * The ticket's purpose is to authenticate the game server by
65 * proving that we know the API key, but without revealing the key.
66 * A secure hash accomplishes this by generating a hash value that
67 * can't be reversed (i.e., you can't figure the input given the
68 * output). The double hash is for protection against chosen
69 * plaintext attacks - these aren't a known vulnerability in
70 * SHA256, but they've been used to attack older hash algorithms,
71 * so we've tried to minimize the impact should SHA256 eventually
72 * be found weaker in this area than presently thought. The idea
73 * is that the filename is explicitly chosen by the user, and the
74 * session ID *could* be chosen by an attacker who only wants to
75 * get the server to generate hash codes for analysis (the storage
76 * server issues true session IDs, so an attacker can't choose SIDs
77 * that actually work against the server, but remember, the
78 * attacker's goal is to analyze the hash output to discover the
79 * secret API key). The game server ID *can't* be chosen by the
80 * attacker, so we combine it with the two choosable plaintext
81 * elements to come up with the first hash. The attacker *can't*
82 * choose the output of this hash, since SHA256 is considered
83 * secure against collision attacks (i.e., it's impossible to find
84 * SHA256 input that produces a chosen output). The attacker will
85 * still *know* the plaintext that's hashed with the API key, but
86 * can't *choose* the plaintext.
87 */
88 char hash1[65];
89 sha256_ezf(hash1, "%s:%s",
90 fname, G_net_config->get("serverid"));
91 sha256_ezf(ticket, "%s:%s",
92 hash1, G_net_config->get("storage.apikey"));
93 }
94
95 /* get the ticket string */
96 const char *get() const { return ticket; }
97
98 private:
99 /* the ticket is an SHA256 hash (64 characters) */
100 char ticket[65];
101 };
102
103 /*
104 * Are we in network storage server mode?
105 */
106 int CVmNetFile::is_net_mode(VMG0_)
107 {
108 return (G_net_config != 0
109 && G_net_config->get("storage.domain") != 0
110 && G_net_config->get("storage.sessionid") != 0);
111 }
112
113 /* ------------------------------------------------------------------------ */
114 /*
115 * Build the full server filename for a given path
116 */
117 const char *CVmNetFile::build_server_filename(
118 VMG_ char *dst, size_t dstsiz, const char *fname, int sfid)
119 {
120 /* if it's a special file, generate the server special file path */
121 if (sfid != 0)
122 {
123 t3sprintf(dst, dstsiz, "~%s/special/%d",
124 G_net_config->get("storage.sessionid"), sfid);
125 return dst;
126 }
127
128 /* if the filename doesn't have the session ID prefix, add it */
129 if (fname != 0 && fname[0] != '~')
130 {
131 /* build the full name - ~SID/filename */
132 t3sprintf(dst, dstsiz, "~%s/%s",
133 G_net_config->get("storage.sessionid"), fname);
134 return dst;
135 }
136
137 /* no changes are required */
138 return fname;
139 }
140
141
142 /* ------------------------------------------------------------------------ */
143 /*
144 * Open a network file
145 */
146 CVmNetFile *CVmNetFile::open(VMG_ const char *fname, int sfid,
147 int mode, os_filetype_t typ,
148 const char *mime_type)
149 {
150 /* check to see if we're in network mode */
151 if (is_net_mode(vmg0_))
152 {
153 /*
154 * We're in network mode, so the file is on the remote storage
155 * server. All operations on the open file will actually be
156 * performed on a local temporary copy. Generate a name for the
157 * temp file.
158 */
159 char tmp[OSFNMAX];
160 if (!os_gen_temp_filename(tmp, sizeof(tmp)))
161 err_throw(VMERR_CREATE_FILE);
162
163 /* build the full server filename */
164 char srvname[400];
165 fname = build_server_filename(
166 vmg_ srvname, sizeof(srvname), fname, sfid);
167
168 /*
169 * If we're not truncating the file, and we're going to either read
170 * or write the file (or both), download a copy of the file from
171 * the server and save it into the temp file we just selected. The
172 * truncate flag means that we're replacing any existing contents,
173 * so there's no need to download the old file.
174 *
175 * If NEITHER read nor write modes are set, we don't have to fetch
176 * the file: we're not going to access the contents, and we're not
177 * going to re-upload the contents on close.
178 *
179 * It might seem strange at first glance that we have to fetch a
180 * file in write-only mode. But we do: we need the old contents in
181 * this case, even though we're not going to look at them locally,
182 * because the caller might be patching a file somewhere in the
183 * middle. This means that the rest of the file has to be kept
184 * intact. To do this we have to download the old copy, so that
185 * the updated copy we upload on close retains the rest of the
186 * contents that we didn't modify.
187 *
188 * If we do decide to download the file, and the file doesn't
189 * exist, this is an error unless the CREATE flag is set. The
190 * CREATE flag means that we're meant to create a new file if
191 * there's no existing file, so it's explicitly not an error if the
192 * file doesn't exist.
193 */
194 if ((mode & (NETF_READ | NETF_WRITE)) != 0
195 && (mode & NETF_TRUNC) == 0)
196 {
197 /*
198 * Not in TRUNCATE mode, so we need to download the file. Open
199 * the temp file for writing.
200 */
201 osfildef *fp = osfoprwtb(tmp, typ);
202 if (fp == 0)
203 err_throw(VMERR_CREATE_FILE);
204
205 /* get the storage server "ticket" for the file */
206 ServerTicket ticket(vmg_ fname, sfid);
207
208 /* build the request URL */
209 char *url = t3sprintf_alloc(
210 "%sgetfile?file=%P&ticket=%P",
211 G_net_config->get("storage.rootpath", "/"),
212 fname, ticket.get());
213
214 /* set up a file stream writer on the temp file */
215 CVmFileSource reply(fp);
216
217 /* download the file from the server into the temp file */
218 char *headers = 0;
219 int hstat = OS_HttpClient::request(
220 0, G_net_config->get("storage.domain"), 80,
221 "GET", url, 0, 0, 0, &reply, &headers, 0, 0);
222
223 /* done with the URL */
224 t3free(url);
225
226 /* get the reply status */
227 char *stat = vmnet_get_storagesrv_stat(
228 vmg_ hstat, &reply, headers);
229
230 /* done with the headers */
231 delete headers;
232
233 /*
234 * If the reply is "FileNotFound", and the CREATE flag was set
235 * in the request, this counts as success - the caller wishes
236 * to create the file if it doesn't already exist, so it's not
237 * an error if it doesn't exist. In this case simply replace
238 * the status code with "OK".
239 */
240 if (memcmp(stat, "FileNotFound ", 13) == 0)
241 strcpy(stat, "OK ");
242
243 /* on failure, delete the temp file */
244 if (memcmp(stat, "OK ", 3) != 0)
245 osfdel(tmp);
246
247 /* check the status and throw an error on failure */
248 vmnet_check_storagesrv_stat(vmg_ stat);
249 }
250
251 /*
252 * Success. Return a file info structure with the temporary file
253 * as the local file name, and the caller's filename as the server
254 * filename.
255 */
256 return new CVmNetFile(tmp, sfid, fname, mode, typ, mime_type);
257 }
258 else
259 {
260 /*
261 * Local mode - the given file is our local file. Don't bother
262 * storing the MIME type for these, since we don't use this with
263 * the local file system APIs.
264 */
265 return new CVmNetFile(fname, sfid, 0, mode, typ, 0);
266 }
267 }
268
269 /* ------------------------------------------------------------------------ */
270 /*
271 * Close a network file
272 */
273 void CVmNetFile::close(VMG0_)
274 {
275 /* if there's no network file, it's a local file */
276 if (srvfname == 0 || !is_net_mode(vmg0_))
277 {
278 int err = 0;
279
280 /* if we opened the file in "create" mode, set the OS file type */
281 if ((mode & NETF_CREATE) != 0)
282 os_settype(lclfname, typ);
283
284 /* if we opened the file in "delete" mode, delete the file */
285 if ((mode & NETF_DELETE) != 0 && osfdel(lclfname))
286 err = VMERR_DELETE_FILE;
287
288 /* if the file spec was a TadsObject object, call its closeFile */
289 if (filespec != VM_INVALID_OBJ
290 && CVmObjTads::is_tadsobj_obj(vmg_ filespec)
291 && G_predef->filespec_closeFile != VM_INVALID_PROP)
292 {
293 /* set up an object value for the file spec */
294 vm_val_t fs;
295 fs.set_obj(filespec);
296
297 /* call closeFile */
298 vm_rcdesc rc("System.closeFile");
299 G_interpreter->get_prop(
300 vmg_ 0, &fs, G_predef->filespec_closeFile, &fs, 0, &rc);
301 }
302
303 /* delete self */
304 delete this;
305
306 /* if an error occurred, throw the error */
307 if (err != 0)
308 err_throw(err);
309
310 /* done */
311 return;
312 }
313
314 /*
315 * presume we won't perform a network operation, so there'll be no
316 * server status code generated
317 */
318 char *stat = 0;
319
320 /*
321 * We have a network file.
322 *
323 * If we opened the file in DELETE mode, delete the server file. Note
324 * that we check this before checking WRITE mode, since there's no
325 * point in sending the updated contents to the server if we're just
326 * going to turn around and delete the file anyway.
327 *
328 * Otherwise, if we opened the file with WRITE access, send the updated
329 * version of the temp file back to the server.
330 */
331 if ((mode & NETF_DELETE) != 0)
332 {
333 /* get the ticket for deleting the file */
334 ServerTicket ticket(vmg_ srvfname, sfid);
335
336 /* generate the URL */
337 char *url = t3sprintf_alloc(
338 "%sdelfile?file=%P&ticket=%P",
339 G_net_config->get("storage.rootpath", "/"),
340 srvfname, ticket.get());
341
342 /* send the GET request */
343 char *headers = 0;
344 CVmMemorySource rstr(1024);
345 int hstat = OS_HttpClient::request(
346 0, G_net_config->get("storage.domain"), 80,
347 "GET", url, 0, 0, 0, &rstr, &headers, 0, 0);
348
349 /* done with the URL */
350 t3free(url);
351
352 /* get the reply code from the server */
353 stat = vmnet_get_storagesrv_stat(vmg_ hstat, &rstr, headers);
354
355 /* done with the headers */
356 if (headers != 0)
357 delete [] headers;
358 }
359 else if ((mode & NETF_WRITE) != 0)
360 {
361 /*
362 * open the local temp file for reading - if we can't, throw a
363 * "close file" error, since this is equivalent to an error
364 * flushing the write buffer to disk on closing a regular file
365 */
366 osfildef *fp = osfoprb(lclfname, typ);
367 if (fp == 0)
368 err_throw(VMERR_CLOSE_FILE);
369
370 /* set up a stream reader on the temp file */
371 CVmFileSource *st = new CVmFileSource(fp);
372
373 /* get the ticket for writing this file */
374 ServerTicket ticket(vmg_ srvfname, sfid);
375
376 /* build the POST data */
377 OS_HttpPayload *post = new OS_HttpPayload();
378 post->add("file", srvfname);
379 post->add("sid", G_net_config->get("storage.sessionid"));
380 post->add("ticket", ticket.get());
381 post->add("contents", "noname", mime_type, st);
382
383 /* generate the URL */
384 char *url = t3sprintf_alloc(
385 "%sputfile", G_net_config->get("storage.rootpath", "/"));
386
387 /* send the POST request */
388 CVmMemorySource rstr(128);
389 char *headers = 0;
390 int hstat = OS_HttpClient::request(
391 0, G_net_config->get("storage.domain"), 80,
392 "POST", url, 0, 0, post, &rstr, &headers, 0, 0);
393
394 /* done with the URL and the POST parameters */
395 t3free(url);
396 delete post;
397
398 /* get the reply code from the server */
399 stat = vmnet_get_storagesrv_stat(vmg_ hstat, &rstr, headers);
400
401 /* done with the headers */
402 if (headers != 0)
403 delete [] headers;
404 }
405
406 /* delete the temporary file */
407 osfdel(lclfname);
408 lclfname = 0;
409
410 /* done with the file structure */
411 delete this;
412
413 /* check the status code from the server, if any */
414 if (stat != 0)
415 vmnet_check_storagesrv_stat(vmg_ stat);
416 }
417
418 /* ------------------------------------------------------------------------ */
419 /*
420 * Do a Read or Write check on a server file.
421 */
422 static int server_file_check(VMG_ const char *srvfname, const char *mode)
423 {
424 /* get the server ticket */
425 ServerTicket ticket(vmg_ srvfname, 0);
426
427 /* build the request URL to test file existence */
428 char *url = t3sprintf_alloc(
429 "%stestfile?file=%P&ticket=%P&mode=%s",
430 G_net_config->get("storage.rootpath", "/"),
431 srvfname, ticket.get(), mode);
432
433 /* send the request */
434 CVmMemorySource rstr(128);
435 int hstat = OS_HttpClient::request(
436 0, G_net_config->get("storage.domain"), 80,
437 "GET", url, 0, 0, 0, &rstr, 0, 0, 0);
438
439 /* done with the URL */
440 t3free(url);
441
442 /* check the result */
443 char reply[128];
444 return (hstat == 200
445 && rstr.readc(reply, sizeof(reply)) >= 1
446 && reply[0] == 'Y');
447 }
448
449 /* ------------------------------------------------------------------------ */
450 /*
451 * Check to see if a file exists
452 */
453 int CVmNetFile::exists(VMG_ const char *fname, int sfid)
454 {
455 /* create a no-op descriptor for the file */
456 CVmNetFile *nf = open(vmg_ fname, sfid, 0, OSFTUNK, 0);
457
458 /*
459 * if it's a network file, check with the server; otherwise check the
460 * local file system
461 */
462 int ret = (nf->is_net_file()
463 ? server_file_check(vmg_ nf->srvfname, "R")
464 : !osfacc(nf->lclfname));
465
466 /* done with the descriptor */
467 nf->abandon(vmg0_);
468
469 /* return the result */
470 return ret;
471 }
472
473 /* ------------------------------------------------------------------------ */
474 /*
475 * Check to see if a file is writable
476 */
477 int CVmNetFile::can_write(VMG_ const char *fname, int sfid)
478 {
479 /* create a no-op descriptor for the file */
480 CVmNetFile *nf = open(vmg_ fname, sfid, 0, OSFTUNK, 0);
481
482 /*
483 * if it's a network file, check with the server; otherwise check the
484 * local file system
485 */
486 int ret = (nf->is_net_file()
487 ? server_file_check(vmg_ nf->srvfname, "W")
488 : can_write_local(nf->lclfname));
489
490 /* done with the descriptor */
491 nf->abandon(vmg0_);
492
493 /* return the result */
494 return ret;
495 }
496
497 /* ------------------------------------------------------------------------ */
498 /*
499 * Get the file mode
500 */
501 int CVmNetFile::get_file_mode(
502 VMG_ unsigned long *mode, unsigned long *attrs, int follow_links)
503 {
504 /*
505 * if it's a network file, check with the server to see if the file
506 * exists; otherwise check the local file system
507 */
508 int ret;
509 if (is_net_file())
510 {
511 /*
512 * network file - if the file exists, it's simply a regular file,
513 * since that's all we support
514 */
515 ret = server_file_check(vmg_ srvfname, "R");
516 *mode = (ret ? OSFMODE_FILE : 0);
517 }
518 else
519 {
520 /* local file - get the local file mode */
521 ret = osfmode(lclfname, follow_links, mode, attrs);
522 }
523
524 /* return the result */
525 return ret;
526 }
527
528 /* ------------------------------------------------------------------------ */
529 /*
530 * Get file status
531 */
532 int CVmNetFile::get_file_stat(VMG_ os_file_stat_t *stat, int follow_links)
533 {
534 if (is_net_file())
535 {
536 /* not supported for network files */
537 err_throw(VMERR_NET_FILE_NOIMPL);;
538 AFTER_ERR_THROW(return FALSE);
539 }
540 else
541 {
542 /* local file - get the local file status */
543 return os_file_stat(lclfname, follow_links, stat);
544 }
545 }
546
547 /* ------------------------------------------------------------------------ */
548 /*
549 * Resolve a symbolic link
550 */
551 int CVmNetFile::resolve_symlink(VMG_ char *target, size_t target_size)
552 {
553 if (is_net_file())
554 {
555 /*
556 * the storage server doesn't support symbolic links, so there's
557 * never anything to resolve
558 */
559 if (target_size != 0)
560 target[0] = '\0';
561 return FALSE;
562 }
563 else
564 {
565 /* local file - get the local file status */
566 return os_resolve_symlink(lclfname, target, target_size);
567 }
568 }
569
570
571 /* ------------------------------------------------------------------------ */
572 /*
573 * Rename a file
574 */
575 void CVmNetFile::rename_to(VMG_ CVmNetFile *newname)
576 {
577 if (is_net_file())
578 {
579 /* the storage server doesn't support directory creation */
580 err_throw(VMERR_NET_FILE_NOIMPL);;
581 }
582 else
583 {
584 /* create the file locally */
585 rename_to_local(vmg_ newname);
586 }
587 }
588
589 /* ------------------------------------------------------------------------ */
590 /*
591 * Create a directory
592 */
593 void CVmNetFile::mkdir(VMG_ int create_parents)
594 {
595 if (is_net_file())
596 {
597 /* the storage server doesn't support directory creation */
598 err_throw(VMERR_NET_FILE_NOIMPL);;
599 }
600 else
601 {
602 /* create the file locally */
603 mkdir_local(vmg_ create_parents);
604 }
605 }
606
607 /* ------------------------------------------------------------------------ */
608 /*
609 * Remove a directory
610 */
611 void CVmNetFile::rmdir(VMG_ int remove_contents)
612 {
613 if (is_net_file())
614 {
615 /* the storage server doesn't support directory removal */
616 err_throw(VMERR_NET_FILE_NOIMPL);;
617 }
618 else
619 {
620 /* create the file locally */
621 rmdir_local(vmg_ remove_contents);
622 }
623 }
624
625 /* ------------------------------------------------------------------------ */
626 /*
627 * Read a directory
628 */
629 int CVmNetFile::readdir(VMG_ const char *nominal_path, vm_val_t *retval)
630 {
631 if (is_net_file())
632 {
633 /* the storage server doesn't support directory listings */
634 err_throw(VMERR_NET_FILE_NOIMPL);;
635 AFTER_ERR_THROW(return FALSE);
636 }
637 else
638 {
639 /* read the local directory */
640 return readdir_local(vmg_ nominal_path, retval, 0, 0, FALSE);
641 }
642 }
643
644 /*
645 * Read a directory, enumerating contents through a callback
646 */
647 int CVmNetFile::readdir_cb(VMG_ const char *nominal_path,
648 const struct vm_rcdesc *rc,
649 const vm_val_t *cb, int recursive)
650 {
651 if (is_net_file())
652 {
653 /* the storage server doesn't support directory listings */
654 err_throw(VMERR_NET_FILE_NOIMPL);;
655 AFTER_ERR_THROW(return FALSE);
656 }
657 else
658 {
659 /* read the local directory */
660 return readdir_local(vmg_ nominal_path, 0, rc, cb, recursive);
661 }
662 }
663