+ int err, fd, r, is_dev;
+
+ is_dev = STRPREFIX (filename, "/dev/");
+ if (!is_dev) {
+ if (!root_mounted || filename[0] != '/') {
+ cancel_receive ();
+ reply_with_error ("root must be mounted and path must be absolute");
+ return -1;
+ }
+ }
+
+ if (!is_dev) CHROOT_IN;
+ fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
+ if (!is_dev) CHROOT_OUT;
+ if (fd == -1) {
+ err = errno;
+ cancel_receive ();
+ errno = err;
+ reply_with_perror ("%s", filename);
+ return -1;
+ }
+
+ r = receive_file (write_cb, &fd);
+ if (r == -1) { /* write error */
+ err = errno;
+ cancel_receive ();
+ errno = err;
+ reply_with_error ("write error: %s", filename);
+ close (fd);
+ return -1;
+ }
+ if (r == -2) { /* cancellation from library */
+ close (fd);
+ /* Do NOT send any error. */
+ return -1;
+ }
+
+ if (close (fd) == -1) {
+ err = errno;
+ if (r == -1) /* if r == 0, file transfer ended already */
+ cancel_receive ();
+ errno = err;
+ reply_with_perror ("close: %s", filename);
+ return -1;
+ }
+
+ return 0;