Пример #1
0
int main(void)
{
  struct fastbuf *w, *r;
  int t;

  w = fbmem_create(7);
  r = fbmem_clone_read(w);
  bwrite(w, "12345", 5);
  bwrite(w, "12345", 5);
  printf("<%d>", (int)btell(w));
  bflush(w);
  printf("<%d>", (int)btell(w));
  printf("<%d>", (int)btell(r));
  while ((t = bgetc(r)) >= 0)
    putchar(t);
  printf("<%d>", (int)btell(r));
  bwrite(w, "12345", 5);
  bwrite(w, "12345", 5);
  printf("<%d>", (int)btell(w));
  bclose(w);
  bsetpos(r, 0);
  printf("<!%d>", (int)btell(r));
  while ((t = bgetc(r)) >= 0)
    putchar(t);
  bsetpos(r, 3);
  printf("<!%d>", (int)btell(r));
  while ((t = bgetc(r)) >= 0)
    putchar(t);
  putchar('\n');
  fflush(stdout);
  bclose(r);
  return 0;
}
Пример #2
0
static void
	bclearall_bwin(conn_t *conn, buddywin_t *bwin, int force) {
	FREESTR(bwin->blurb);
	FREESTR(bwin->status);
	switch (bwin->et) {
	  case BUDDY:
		assert(bwin->e.buddy != NULL);
		if (bwin->e.buddy->offline == 0) {
			bwin->e.buddy->offline = 1;
			window_echof(bwin, "<font color=\"#00FFFF\">%s</font> <font color=\"#800000\">[<B>%s</B>]</font> is no longer available :/\n",
				user_name(NULL, 0, conn, bwin->e.buddy), USER_GROUP(bwin->e.buddy));
		}
		if (bwin->keepafterso == 0) {
			bclose(conn, bwin, 1);
			bwin = NULL;
			return;
		}
		break;
	  case CHAT:
		bwin->e.chat->isoper = 0;
		if (bwin->e.chat->offline == 0) {
			bwin->e.chat->offline = 1;
			window_echof(bwin, "Chat <font color=\"#00FFFF\">%s</font> is no longer available :/\n",
				bwin->winname);
		}
		break;
	  case TRANSFER:
		break;
	}
	if (force) {
		bclose(conn, bwin, 1);
		bwin = NULL;
	}
}
Пример #3
0
/**
 * Save OSX specific resource forks and finder info.
 */
static inline bool save_rsrc_and_finder(b_save_ctx &bsctx)
{
   char flags[FOPTS_BYTES];
   int rsrc_stream;
   BSOCK *sd = bsctx.jcr->store_bsock;
   bool retval = false;

   if (bsctx.ff_pkt->hfsinfo.rsrclength > 0) {
      if (bopen_rsrc(&bsctx.ff_pkt->bfd, bsctx.ff_pkt->fname, O_RDONLY | O_BINARY, 0) < 0) {
         bsctx.ff_pkt->ff_errno = errno;
         berrno be;
         Jmsg(bsctx.jcr, M_NOTSAVED, -1,
              _("     Cannot open resource fork for \"%s\": ERR=%s.\n"),
              bsctx.ff_pkt->fname, be.bstrerror());
         bsctx.jcr->JobErrors++;
         if (is_bopen(&bsctx.ff_pkt->bfd)) {
            bclose(&bsctx.ff_pkt->bfd);
         }
      } else {
         int status;

         memcpy(flags, bsctx.ff_pkt->flags, sizeof(flags));
         clear_bit(FO_COMPRESS, bsctx.ff_pkt->flags);
         clear_bit(FO_SPARSE, bsctx.ff_pkt->flags);
         clear_bit(FO_OFFSETS, bsctx.ff_pkt->flags);
         rsrc_stream = bit_is_set(FO_ENCRYPT, flags) ? STREAM_ENCRYPTED_MACOS_FORK_DATA :
                                                       STREAM_MACOS_FORK_DATA;

         status = send_data(bsctx.jcr, rsrc_stream, bsctx.ff_pkt,
                            bsctx.digest, bsctx.signing_digest);

         memcpy(bsctx.ff_pkt->flags, flags, sizeof(flags));
         bclose(&bsctx.ff_pkt->bfd);
         if (!status) {
            goto bail_out;
         }
      }
   }

   Dmsg1(300, "Saving Finder Info for \"%s\"\n", bsctx.ff_pkt->fname);
   sd->fsend("%ld %d 0", bsctx.jcr->JobFiles, STREAM_HFSPLUS_ATTRIBUTES);
   Dmsg1(300, "filed>stored:header %s", sd->msg);
   pm_memcpy(sd->msg, bsctx.ff_pkt->hfsinfo.fndrinfo, 32);
   sd->msglen = 32;
   if (bsctx.digest) {
      crypto_digest_update(bsctx.digest, (uint8_t *)sd->msg, sd->msglen);
   }
   if (bsctx.signing_digest) {
      crypto_digest_update(bsctx.signing_digest, (uint8_t *)sd->msg, sd->msglen);
   }
   sd->send();
   sd->signal(BNET_EOD);

   retval = true;

bail_out:
   return retval;
}
Пример #4
0
/*
 * Compute message digest for the file specified by ff_pkt.
 * In case of errors we need the job control record and file name.
 */
int digest_file(JCR *jcr, FF_PKT *ff_pkt, DIGEST *digest)
{
   BFILE bfd;

   Dmsg0(50, "=== digest_file\n");
   binit(&bfd);

   if (ff_pkt->statp.st_size > 0 ||
       ff_pkt->type == FT_RAW ||
       ff_pkt->type == FT_FIFO) {
      int noatime = ff_pkt->flags & FO_NOATIME ? O_NOATIME : 0;
      if ((bopen(&bfd, ff_pkt->fname, O_RDONLY | O_BINARY | noatime, 0, ff_pkt->statp.st_rdev)) < 0) {
         ff_pkt->ff_errno = errno;
         berrno be;
         be.set_errno(bfd.berrno);
         Dmsg2(100, "Cannot open %s: ERR=%s\n", ff_pkt->fname, be.bstrerror());
         Jmsg(jcr, M_ERROR, 1, _("     Cannot open %s: ERR=%s.\n"),
               ff_pkt->fname, be.bstrerror());
         return 1;
      }
      read_digest(&bfd, digest, jcr);
      bclose(&bfd);
   }

   if (have_darwin_os) {
      /*
       * Open resource fork if necessary
       */
      if (ff_pkt->flags & FO_HFSPLUS && ff_pkt->hfsinfo.rsrclength > 0) {
         if (bopen_rsrc(&bfd, ff_pkt->fname, O_RDONLY | O_BINARY, 0) < 0) {
            ff_pkt->ff_errno = errno;
            berrno be;
            Jmsg(jcr, M_ERROR, -1, _("     Cannot open resource fork for %s: ERR=%s.\n"),
                  ff_pkt->fname, be.bstrerror());
            if (is_bopen(&ff_pkt->bfd)) {
               bclose(&ff_pkt->bfd);
            }
            return 1;
         }
         read_digest(&bfd, digest, jcr);
         bclose(&bfd);
      }

      if (digest && ff_pkt->flags & FO_HFSPLUS) {
         crypto_digest_update(digest, (uint8_t *)ff_pkt->hfsinfo.fndrinfo, 32);
      }
   }
   return 0;
}
Пример #5
0
/*@
   beasy_closesocket - closesocket

   Parameters:
+  int bfd - bsocket

   Notes:
@*/
int beasy_closesocket(int bfd)
{
    WSAEVENT hEvent = WSACreateEvent();
    if (hEvent != WSA_INVALID_EVENT)
    {
	if (WSAEventSelect(bget_fd(bfd), hEvent, FD_CLOSE) == 0)
	{
	    shutdown(bget_fd(bfd), SD_BOTH);
	    WaitForSingleObject(hEvent, 200);
	    /*
	    if (WaitForSingleObject(hEvent, 100) == WAIT_TIMEOUT)
	    {
		printf("wait for close timed out\n");fflush(stdout);
	    }
	    else
	    {
		printf("wait for close succeeded\n");fflush(stdout);
	    }
	    */
	    WSACloseEvent(hEvent);
	}
	else
	    shutdown(bget_fd(bfd), SD_BOTH);
    }
    else
	shutdown(bget_fd(bfd), SD_BOTH);
    bclose(bfd);
    return 0;
}
Пример #6
0
static void smooth_hline(const Ink *inky, SHORT x0, const SHORT y, SHORT width)
{
UBYTE buf[SBSIZE+1];
UBYTE *bpt = buf;
SHORT i = width;
UBYTE strength = inky->strength;
SHORT dither = inky->dither;
Aa_ink_data *aid = inky->aid;
int ccount = aid->ccount;
Rcel *undo = aid->undo;
Rgb3 result;
Rgb3 *ctab = undo->cmap->ctab;
void (*blend)(Rgb3 *dest, Rgb3 *source, UBYTE percent, Rgb3 *result) = 
																aid->true_blend;
int (*closestc)(Rgb3 *true_color, Rgb3 *cmap, int ccount) = aid->closestc;
int (*bclose)(Rgb3 *rgb,int count,SHORT dither) = aid->bclosest_col;


	if(x0 + width >= undo->width) /* duplicate last pixel if at end of line */
	{
		GET_HSEG(undo,buf,x0,y,width);
		buf[width] = buf[width-1];
	}
	else
	{
		GET_HSEG(undo,buf,x0,y,width+1);
	}
	while(--i >= 0)
	{
		blend(bpt[0] + ctab, bpt[1] + ctab, strength, &result);
		*bpt++ = bclose(&result, ccount, dither);
	}
	PUT_HSEG(aid->screen,buf,x0,y,width);
}
Пример #7
0
int main(int argc, char *argv[])
{
	int do_restore = argc > 1 && strcmp("-r", argv[1]) == 0;
	const char *mode = (do_restore) ? "r+" : "w+";

	/* call perm() and open() before malloc() */
	perm(PERM_START, PERM_SIZE);
	mopen(MMAP_FILE, mode, MMAP_SIZE);
	bopen(BACK_FILE, mode);
	if (do_restore) {
		restore();
	} else {
		home = (home_st *)malloc(sizeof(home_st));
		/* initialize home struct... */
		mflush(); backup();
	}

	for (;/* each step */;) {
		/* Application_Step(); */
		backup();
	}

	free(home);
	mclose();
	bclose();
	return(0);
}
Пример #8
0
close_rgb_files()
{
int i;

for (i=0; i<3; i++)
	bclose(rgb_files+i);
}
Пример #9
0
void NLMcleanup( void )
{
   P( 23 ) ;

#ifdef WEBS_SSL_SUPPORT
   websSSLClose();
#endif

#ifdef USER_MANAGEMENT_SUPPORT
   umClose();
#endif

/*
 * Close the socket module, report memory leaks and close the memory allocator
 */
   websCloseServer();
   
   P( 24 ) ;

   socketClose();
#ifdef B_STATS
   memLeaks();
#endif
   P( 25 ) ;

   bclose();

   P( 26 ) ;
}
Пример #10
0
void	bgoing(conn_t *conn, const char *buddy) {
	buddywin_t	*bwin = conn->curbwin;
	buddylist_t	*blist = NULL;

	assert(buddy != NULL);

	if (bwin == NULL)
		return;

	if ((blist = rgetlist(conn, buddy)) != NULL) {
		if ((blist->peer <= 0) && (blist->crypt != NULL))
			echof(conn, NULL, "Strangeness while marking %s offline: no autopeer negotiated, but autocrypt set!\n",
				buddy);
		blist->docrypt = blist->peer = 0;
		if (blist->crypt != NULL) {
			free(blist->crypt);
			blist->crypt = NULL;
		}
		if (blist->tzname != NULL) {
			free(blist->tzname);
			blist->tzname = NULL;
		}

		status_echof(conn, "<font color=\"#00FFFF\">%s</font> <font color=\"#800000\">[<B>%s</B>]</font> has just logged off :(\n", 
			user_name(NULL, 0, conn, blist), USER_GROUP(blist));
		blist->offline = 1;
		blist->warnval = blist->typing = blist->isadmin = blist->ismobile = blist->isidle = blist->isaway = 0;
	} else
		return;

	do {
		if ((bwin->et == BUDDY) && (firetalk_compare_nicks(conn->conn, buddy, bwin->winname) == FE_SUCCESS)) {
			int	autoclose = getvar_int(conn, "autoclose"),
				beeponsignon = getvar_int(conn, "beeponsignon");

			assert(bwin->e.buddy == blist);
			window_echof(bwin, "<font color=\"#00FFFF\">%s</font> <font color=\"#800000\">[<B>%s</B>]</font> has just logged off :(\n",
				user_name(NULL, 0, conn, blist), USER_GROUP(blist));
			if ((beeponsignon > 1) || ((awaytime == 0) && (beeponsignon == 1)))
				beep();
			FREESTR(bwin->blurb);
			FREESTR(bwin->status);

			if (bwin->keepafterso == 1) {
				if ((autoclose > 0) && !USER_PERMANENT(bwin->e.buddy) && (bwin->waiting == 0))
					bwin->closetime = now + 60*autoclose;
			} else {
				/* assert(bwin->waiting == 0); */
				bclose(conn, bwin, 1);
				bwin = NULL;
				if ((autoclose > 0) && !USER_PERMANENT(blist)) {
					rdelbuddy(conn, buddy);
					firetalk_im_remove_buddy(conn->conn, buddy);
				}
			}
			bupdate();
			return;
		}
	} while ((bwin = bwin->next) != conn->curbwin);
}
Пример #11
0
int close_file_for_send(BFILE *bfd, FILE **fp)
{
	if(fp) return close_fp(fp);
#ifdef HAVE_WIN32
	if(bfd) return bclose(bfd);
#endif
	return -1;
}
Пример #12
0
int main( int argc, char** argv )
{
    /*
     *	Initialize the memory allocator. Allow use of malloc and start
     *	with a 60K heap.  For each page request approx 8KB is allocated.
     *	60KB allows for several concurrent page requests.  If more space
     *	is required, malloc will be used for the overflow.
     */
    bopen( NULL, ( 60 * 1024 ), B_USE_MALLOC );
    signal( SIGPIPE, SIG_IGN );

    /*
     *	Initialize the web server
     */
    if ( initWebs() < 0 )
    {
        return -1;
    }

#ifdef WEBS_SSL_SUPPORT
    websSSLOpen();
#endif

    /*
     *	Basic event loop. SocketReady returns true when a socket is ready for
     *	service. SocketSelect will block until an event occurs. SocketProcess
     *	will actually do the servicing.
     */
    while ( !finished )
    {
        if ( socketReady( -1 ) || socketSelect( -1, 1000 ) )
        {
            socketProcess( -1 );
        }

        websCgiCleanup();
        emfSchedProcess();
    }

#ifdef WEBS_SSL_SUPPORT
    websSSLClose();
#endif
#ifdef USER_MANAGEMENT_SUPPORT
    umClose();
#endif
    /*
     *	Close the socket module, report memory leaks and close the memory allocator
     */
    websCloseServer();
    socketClose();
#ifdef B_STATS
    memLeaks();
#endif
    bclose();
    return 0;
}
Пример #13
0
static void
rtems_httpd_daemon(rtems_task_argument args)
{
/*
 *	Initialize the memory allocator. Allow use of malloc and start with a 
 *	10K heap.
 */
	bopen(NULL, (10 * 1024), B_USE_MALLOC);

/*
 *	Initialize the web server
 */
	if (initWebs() < 0) {
	  rtems_panic("Unable to initialize Web server !!\n");
	}

#ifdef WEBS_SSL_SUPPORT
	websSSLOpen();
#endif

/*
 *	Basic event loop. SocketReady returns true when a socket is ready for
 *	service. SocketSelect will block until an event occurs. SocketProcess
 *	will actually do the servicing.
 */
	while (!finished) {
	  if (socketReady(-1) || socketSelect(-1, 2000)) {
			socketProcess(-1);
	  }
	  /*websCgiCleanup();*/
	  emfSchedProcess();
	}

#ifdef WEBS_SSL_SUPPORT
	websSSLClose();
#endif

#ifdef USER_MANAGEMENT_SUPPORT
	umClose();
#endif

/*
 *	Close the socket module, report memory leaks and close the memory allocator
 */
	websCloseServer();
	websDefaultClose();
	socketClose();
	symSubClose();
#if B_STATS
	memLeaks();
#endif
	bclose();
        rtems_task_delete( RTEMS_SELF );
}
Пример #14
0
static int open_for_restore(struct asfd *asfd, BFILE *bfd, FILE **fp,
                            const char *path, struct sbuf *sb, int vss_restore, struct conf *conf)
{
#ifdef HAVE_WIN32
    if(bfd->mode!=BF_CLOSED)
    {
        if(bfd->path && !strcmp(bfd->path, path))
        {
            // Already open after restoring the VSS data.
            // Time now for the actual file data.
            return 0;
        }
        else
        {
            if(bclose(bfd, asfd))
            {
                logp("error closing %s in %s()\n",
                     path, __func__);
                return -1;
            }
        }
    }
    binit(bfd, sb->winattr, conf);
    if(vss_restore)
        set_win32_backup(bfd);
    else
        bfd->use_backup_api=0;
    if(bopen(bfd, asfd, path, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
             S_IRUSR | S_IWUSR)<=0)
    {
        berrno be;
        char msg[256]="";
        snprintf(msg, sizeof(msg),
                 "Could not open for writing %s: %s",
                 path, be.bstrerror(errno));
        if(restore_interrupt(asfd, sb, msg, conf))
            return -1;
    }
#else
    if(!(*fp=open_file(path, "wb")))
    {
        char msg[256]="";
        snprintf(msg, sizeof(msg),
                 "Could not open for writing %s: %s",
                 path, strerror(errno));
        if(restore_interrupt(asfd, sb, msg, conf))
            return -1;
    }
#endif
    // Add attributes to bfd so that they can be set when it is closed.
    bfd->winattr=sb->winattr;
    memcpy(&bfd->statp, &sb->statp, sizeof(struct stat));
    return 0;
}
Пример #15
0
/* These receive_a_file() and send_file() functions are for use by extra_comms
   and the CA stuff, rather than backups/restores. */
int receive_a_file(const char *path, struct cntr *p1cntr)
{
	int c=0;
	int ret=0;
#ifdef HAVE_WIN32
	BFILE bfd;
#else
	FILE *fp=NULL;
#endif
	unsigned long long rcvdbytes=0;
	unsigned long long sentbytes=0;

#ifdef HAVE_WIN32
	binit(&bfd, 0);
	bfd.use_backup_api=0;
	//set_win32_backup(&bfd);
	if(bopen(&bfd, path,
		O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
		S_IRUSR | S_IWUSR, 0)<=0)
	{
		berrno be;
		logp("Could not open for writing %s: %s\n",
			path, be.bstrerror(errno));
		ret=-1;
		goto end;
	}
#else
	if(!(fp=open_file(path, "wb")))
	{
		ret=-1;
		goto end;
	}
#endif

#ifdef HAVE_WIN32
	ret=transfer_gzfile_in(NULL, path, &bfd, NULL,
		&rcvdbytes, &sentbytes, NULL, 0, p1cntr, NULL);
	c=bclose(&bfd);
#else
	ret=transfer_gzfile_in(NULL, path, NULL, fp,
		&rcvdbytes, &sentbytes, NULL, 0, p1cntr, NULL);
	c=close_fp(&fp);
#endif
end:
	if(c)
	{
		logp("error closing %s in receive_a_file\n", path);
		ret=-1;
	}
	if(!ret) logp("Received: %s\n", path);
	return ret;
}
Пример #16
0
 char * la_getdb (char *fn)
/*
 char *fn ;                 			data base file name
*/
{
 	struct 	FAB f ;				/* file access block    */
 	struct 	RAB r ;				/* record access block  */
	struct 	XABFHC x ;			/* file header 		*/
	struct	NAM n;				/*  added nam block to capture file id  (js)  */

	int4		status ;
	int4 		size   ;
	int 		k ;
	char 		*h= NULL ;		/* db in main store 	*/
	char 		*p ;			/* current read buffer  */
	la_prolog	*prol ;			/* db file prolog	*/

	n = cc$rms_nam;
	status= bopen(fn,&f,&r,&x,&n);
	if (status==SS$_NORMAL)
	{
		size= 512 * x.xab$l_ebk + PBUF ;
		if ((h= (char *)malloc(size))!=NULL)
		{
			p= h ;
			while (status==SS$_NORMAL && p<h+size)
		        {
				status= bread(&r,p,BLKS) ; p += BLKS  ;
			}
			if (status!=RMS$_EOF)
			{
				h= NULL ;
			}
			else
			{
				prol= h ;
				if (prol->id!=DBID)	/* invalid file ID */
				{
					h= NULL ;
				}
			}
		}
		bclose(&f) ;
	}
	else
	{
		h= NULL ;
	}
	return(h) ;
}
Пример #17
0
int main (int argc, char *argv[]) {

	const char		*const_str = "ThisStringIsUsedToTestWriteOfMetadata";
	char			*str;
	uint8_t			size, type;
	struct  bitio	*bd;

	bd = bopen("metadata_test.dat", 'w');
	if (bd == NULL)
		goto error;

	meta_write(bd, 1, (void*)const_str, strlen(const_str) + 1);
	meta_write(bd, 2, (void*)const_str, 2);
	meta_finalize(bd);

	bclose(bd);

	bd = bopen("metadata_test.dat", 'r');
	if (bd == NULL)
		goto error;

	str = meta_read(bd, &type, &size);
	if (strcmp(str, const_str) != 0 || type != 1 || size != strlen(str) + 1)
		goto error;

	str = meta_read(bd, &type, &size);
	if (str[0] != const_str[0] || str[1] != const_str[1] || type != 2 || size != 2)
		goto error;

	bclose(bd);
	unlink("metadata_test.dat");
	exit(EXIT_SUCCESS);
error:
	bclose(bd);
	unlink("metadata_test.dat");
	exit(EXIT_FAILURE);
}
Пример #18
0
void close_image(struct cr_img *img)
{
	if (lazy_image(img)) {
		/*
		 * Remove the image file if it's there so that
		 * subsequent restore doesn't read wrong or fake
		 * data from it.
		 */
		unlinkat(get_service_fd(IMG_FD_OFF), img->path, 0);
		xfree(img->path);
	} else if (!empty_image(img))
		bclose(&img->_x);

	xfree(img);
}
Пример #19
0
void bcloseall()
#endif
{
	BLKFILE *bp = NULL;

	/* close all open block files */
	for (bp = biob; bp < (biob + BOPEN_MAX); ++bp) {
		if (bp->flags & BIOOPEN) {
			if (bclose(bp) == -1) {
				BEPRINT;
			}
		}
	}

	return;
}
Пример #20
0
void *
bopen (const char *filename, const char *mode)
{
  struct fhandle *f = &fhandle;
  f->file1 = fopen (filename, mode);
  if (! f->file1)
    return NULL;
  f->file2 = BZ2_bzReadOpen (&bzerror, f->file1, 0, 0, NULL, 0);
  if (bzerror != BZ_OK)
    {
      errno = bzerror;
      bclose (f);
      return NULL;
    }
  return f;
}
Пример #21
0
int
main(int argc, char *argv[])
{
	int c;
	size_t i;
	Buffer *buf;

	errno = 0;

	setpname(argv[0]);
	if (argc < 2)
		die(2, "usage: %s file", getpname());

	if ((c = open(argv[1], O_RDONLY)) == -1)
		die(1, "failed to open file %s:", argv[1]);

	if ((buf = makebuf(512)) == NULL)
		die(1, "allocating buffer failed:");

	if (initbuf(buf, c, O_RDONLY) == EOF)
		die(1, "initializing buffer failed:");

	i = 0;
	while ((c = bgetchar(buf)) != EOF) {
		if (i == 511 || i == 512 || i == 513) {
			if (bungetchar(buf) == EOF) {
				die(1, "bungetchar failed at char %lu", i);
				break;
			}

			if ((c = bgetchar(buf)) == EOF)
				break;
		}
		putc(c, stdout);
		i++;
	}

	if (errno != 0)
		die(1, "bgetchar failed at char %lu:", i);

	fprintf(stderr, "reached end of input file %s\n", argv[1]);
	fprintf(stderr, "%lu bytes read\n", i);
	bclose(buf);

	exit(0);
}
Пример #22
0
static void websTermSigHandler(int signo)
{
	if (signo == SIGTERM) {
		finished = 1;
	} else if (signo == SIGKILL) {
#ifdef WEBS_SSL_SUPPORT
		websSSLClose();
#endif

#ifdef USER_MANAGEMENT_SUPPORT
		umClose();
#endif
		websCloseServer();
		socketClose();
		symSubClose();
#ifdef B_STATS
		memLeaks();
#endif
		bclose();
		exit(1);
	}
}
Пример #23
0
int main(int argc, char** argv)
{
/*
 *	Initialize the memory allocator. Allow use of malloc and start 
 *	with a 60K heap.  For each page request approx 8KB is allocated.
 *	60KB allows for several concurrent page requests.  If more space
 *	is required, malloc will be used for the overflow.
 */
	bopen(NULL, (60 * 1024), B_USE_MALLOC);

/*
 *	Initialize the web server
 */
	if (initWebs() < 0) {
		return -1;
	}

/*
 *	Basic event loop. SocketReady returns true when a socket is ready for
 *	service. SocketSelect will block until an event occurs. SocketProcess
 *	will actually do the servicing.
 */
	while (!finished) {
		if (socketReady(-1) || socketSelect(-1, 2000)) {
			socketProcess(-1);
		}
		emfSchedProcess();
	}

/*
 *	Close the socket module, report memory leaks and close the memory allocator
 */
	websCloseServer();
	socketClose();
	bclose();
	return 0;
}
Пример #24
0
/**
 * Set Extended File Attributes for Win32
 *
 *  fname is the original filename
 *  ofile is the output filename (may be in a different directory)
 *
 * Returns:  true  on success
 *           false on failure
 */
static bool set_win32_attributes(JCR *jcr, ATTR *attr, BFILE *ofd)
{
   char *p = attr->attrEx;
   int64_t val;
   WIN32_FILE_ATTRIBUTE_DATA atts;
   ULARGE_INTEGER li;
   POOLMEM *win32_ofile;

   /** if we have neither Win ansi nor wchar API, get out */
   if (!(p_SetFileAttributesW || p_SetFileAttributesA)) {
      return false;
   }

   if (!p || !*p) {                   /* we should have attributes */
      Dmsg2(100, "Attributes missing. of=%s ofd=%d\n", attr->ofname, ofd->fid);
      if (is_bopen(ofd)) {
         bclose(ofd);
      }
      return false;
   } else {
      Dmsg2(100, "Attribs %s = %s\n", attr->ofname, attr->attrEx);
   }

   p += from_base64(&val, p);
   plug(atts.dwFileAttributes, val);
   p++;                               /* skip space */
   p += from_base64(&val, p);
   li.QuadPart = val;
   atts.ftCreationTime.dwLowDateTime = li.LowPart;
   atts.ftCreationTime.dwHighDateTime = li.HighPart;
   p++;                               /* skip space */
   p += from_base64(&val, p);
   li.QuadPart = val;
   atts.ftLastAccessTime.dwLowDateTime = li.LowPart;
   atts.ftLastAccessTime.dwHighDateTime = li.HighPart;
   p++;                               /* skip space */
   p += from_base64(&val, p);
   li.QuadPart = val;
   atts.ftLastWriteTime.dwLowDateTime = li.LowPart;
   atts.ftLastWriteTime.dwHighDateTime = li.HighPart;
   p++;
   p += from_base64(&val, p);
   plug(atts.nFileSizeHigh, val);
   p++;
   p += from_base64(&val, p);
   plug(atts.nFileSizeLow, val);

   /** Convert to Windows path format */
   win32_ofile = get_pool_memory(PM_FNAME);
   unix_name_to_win32(&win32_ofile, attr->ofname);

   /** At this point, we have reconstructed the WIN32_FILE_ATTRIBUTE_DATA pkt */

   if (!is_bopen(ofd)) {
      Dmsg1(100, "File not open: %s\n", attr->ofname);
      bopen(ofd, attr->ofname, O_WRONLY|O_BINARY, 0);   /* attempt to open the file */
   }

   if (is_bopen(ofd)) {
      Dmsg1(100, "SetFileTime %s\n", attr->ofname);
      if (!SetFileTime(bget_handle(ofd),
                         &atts.ftCreationTime,
                         &atts.ftLastAccessTime,
                         &atts.ftLastWriteTime)) {
         win_error(jcr, "SetFileTime:", win32_ofile);
      }
      bclose(ofd);
   }

   Dmsg1(100, "SetFileAtts %s\n", attr->ofname);
   if (!(atts.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
      if (p_SetFileAttributesW) {
         POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);   
         make_win32_path_UTF8_2_wchar(&pwszBuf, attr->ofname);

         BOOL b=p_SetFileAttributesW((LPCWSTR)pwszBuf, atts.dwFileAttributes & SET_ATTRS);
         free_pool_memory(pwszBuf);
      
         if (!b) 
            win_error(jcr, "SetFileAttributesW:", win32_ofile); 
      }
      else {
         if (!p_SetFileAttributesA(win32_ofile, atts.dwFileAttributes & SET_ATTRS)) {
            win_error(jcr, "SetFileAttributesA:", win32_ofile);
         }
      }
   }
   free_pool_memory(win32_ofile);
   return true;
}
Пример #25
0
/**
 * Set file modes, permissions and times
 *
 *  fname is the original filename
 *  ofile is the output filename (may be in a different directory)
 *
 * Returns:  true  on success
 *           false on failure
 */
bool set_attributes(JCR *jcr, ATTR *attr, BFILE *ofd)
{
   struct utimbuf ut;
   mode_t old_mask;
   bool ok = true;
   boffset_t fsize;
 
   if (uid_set) {
      my_uid = getuid();
      my_gid = getgid();
      uid_set = true;
   }

#if defined(HAVE_WIN32)
   if (attr->stream == STREAM_UNIX_ATTRIBUTES_EX &&
       set_win32_attributes(jcr, attr, ofd)) {
       if (is_bopen(ofd)) {
           bclose(ofd);
       }
       pm_strcpy(attr->ofname, "*none*");
       return true;
   }
   if (attr->data_stream == STREAM_WIN32_DATA ||
       attr->data_stream == STREAM_WIN32_GZIP_DATA ||
       attr->data_stream == STREAM_WIN32_COMPRESSED_DATA) {
      if (is_bopen(ofd)) {
         bclose(ofd);
      }
      pm_strcpy(attr->ofname, "*none*");
      return true;
   }


   /**
    * If Windows stuff failed, e.g. attempt to restore Unix file
    *  to Windows, simply fall through and we will do it the
    *  universal way.
    */
#endif

   old_mask = umask(0);
   if (is_bopen(ofd)) {
      char ec1[50], ec2[50];
      fsize = blseek(ofd, 0, SEEK_END);
      bclose(ofd);                    /* first close file */
      if (attr->type == FT_REG && fsize > 0 && attr->statp.st_size > 0 && 
                        fsize != (boffset_t)attr->statp.st_size) {
         Jmsg3(jcr, M_ERROR, 0, _("File size of restored file %s not correct. Original %s, restored %s.\n"),
            attr->ofname, edit_uint64(attr->statp.st_size, ec1),
            edit_uint64(fsize, ec2));
      }
   }

   /**
    * We do not restore sockets, so skip trying to restore their
    *   attributes.
    */
   if (attr->type == FT_SPEC && S_ISSOCK(attr->statp.st_mode)) {
      goto bail_out;
   }

   ut.actime = attr->statp.st_atime;
   ut.modtime = attr->statp.st_mtime;

   /* ***FIXME**** optimize -- don't do if already correct */
   /**
    * For link, change owner of link using lchown, but don't
    *   try to do a chmod as that will update the file behind it.
    */
   if (attr->type == FT_LNK) {
      /** Change owner of link, not of real file */
      if (lchown(attr->ofname, attr->statp.st_uid, attr->statp.st_gid) < 0 && my_uid == 0) {
         berrno be;
         Jmsg2(jcr, M_ERROR, 0, _("Unable to set file owner %s: ERR=%s\n"),
            attr->ofname, be.bstrerror());
         ok = false;
      }
   } else {
      if (chown(attr->ofname, attr->statp.st_uid, attr->statp.st_gid) < 0 && my_uid == 0) {
         berrno be;
         Jmsg2(jcr, M_ERROR, 0, _("Unable to set file owner %s: ERR=%s\n"),
            attr->ofname, be.bstrerror());
         ok = false;
      }
      if (chmod(attr->ofname, attr->statp.st_mode) < 0 && my_uid == 0) {
         berrno be;
         Jmsg2(jcr, M_ERROR, 0, _("Unable to set file modes %s: ERR=%s\n"),
            attr->ofname, be.bstrerror());
         ok = false;
      }

      /**
       * Reset file times.
       */
      if (utime(attr->ofname, &ut) < 0 && my_uid == 0) {
         berrno be;
         Jmsg2(jcr, M_ERROR, 0, _("Unable to set file times %s: ERR=%s\n"),
            attr->ofname, be.bstrerror());
         ok = false;
      }
#ifdef HAVE_CHFLAGS
      /**
       * FreeBSD user flags
       *
       * Note, this should really be done before the utime() above,
       *  but if the immutable bit is set, it will make the utimes()
       *  fail.
       */
      if (chflags(attr->ofname, attr->statp.st_flags) < 0 && my_uid == 0) {
         berrno be;
         Jmsg2(jcr, M_ERROR, 0, _("Unable to set file flags %s: ERR=%s\n"),
            attr->ofname, be.bstrerror());
         ok = false;
      }
#endif
   }

bail_out:
   pm_strcpy(attr->ofname, "*none*");
   umask(old_mask);
   return ok;
}
Пример #26
0
int main (int argc, char *argv[])
{

    int my_rank, proc_num;
    MPI_Status status;
    MPI_Init(&argc, &argv);

    MPI_Comm_size(MPI_COMM_WORLD, &proc_num);
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);

    double diff;  /* change in value */
    int    i, j, m, n;
    int N=DEFAULT_N;
    double epsilon=0.01;
    double mean;
    FILE *fp;

    /* Argument processing */
    int edgeElems = DEFAULT_ELEM; /* edge elements */
    int cfreq = DEFAULT_FREQ; /* checkpoint frequency */
    char *cpath = DEFAULT_PATH; /* checkpoint path */
    int nok = 0; /* arguments not OK */
    int pinit=1;

    char *s;
    while (--argc > 0 && (*++argv)[0] == '-') {
        for(s=argv[0]+1;*s;s++)
        switch (*s) {
        case 'd':
            if (isdigit(s[1]))
                edgeElems = atoi(s+1);
            else
                nok = 1;
            s+=strlen(s+1);
            break;
        case 'c':
            if (isdigit(s[i]))
                cfreq = atoi(s+1);
            else
                nok = 1;
            s+=strlen(s+1);
            break;
        case 'p':
            cpath = s+1;
            s+=strlen(s+1);
            break;
        case 'r':
            pinit = 0;
            break;
        case 'n':
            if (isdigit(s[1])) 
                N = atoi(s+1);
            else
                nok = 1;
            s+=strlen(s+1);
            break;
        case 'e':
            if (isdigit(s[1]))
                epsilon = atof(s+1);
            else
                nok = 1;
            s+=strlen(s+1);
            break;
        default:
            nok = 1;
            break;
        }
    }

    if (nok) {
        fprintf(stderr, "Usage: %s -e<int> -c<int> -p<str> -r -n<int> -epsilon<double>\n", argv[0]);
        fprintf(stderr, "  -d  edge elements, default: %d\n", DEFAULT_ELEM);
        fprintf(stderr, "  -c  checkpoint frequency, default: %d\n", DEFAULT_FREQ);
        fprintf(stderr, "  -p  path to checkpoint file, default: %s\n", DEFAULT_PATH);
        fprintf(stderr, "  -r  restore\n");
        fprintf(stderr, "  -n  size of n, default:1000\n");
        fprintf(stderr, "  -e  epsilon, default:0.01\n");

        exit(EXIT_FAILURE);
    }

#ifdef DEBUG
    if(my_rank==0)
        printf("n=%d, epsilon=%lf\n", N, epsilon);
#endif

	if(N>1000){
		printf("Too big value for N, use no more than 1000, or change DEFAULT_N\n");
		return 0;
	}
   // Persistent memory initialization 
   const char *mode = (pinit) ? "w+" : "r+";
   char back_fname[128];
   char my_rank_str[4];
   perm(PERM_START, PERM_SIZE);
   strcpy(back_fname, cpath);
   strcat(back_fname,"hw5_mpi.back.");
   sprintf(my_rank_str, "%d", my_rank);
   strcat(back_fname,my_rank_str);
//   printf("mopen: %s\n", back_fname);
   mopen(back_fname, mode, MMAP_SIZE);
   strcpy(back_fname, cpath);
   strcat(back_fname,"hw5_mpi.mmap.");
   strcat(back_fname,my_rank_str);
//   printf("bopen: %s\n", back_fname);
   bopen(back_fname, mode);



   if (!pinit){ 
       restore();

       printf("Resotored, iter=%d, myN=%d\n", iter, myN);
   }
   else{

       iter = 0;
        /* Set boundary values and compute mean boundary value */
        mean = 0.0;
        for (i=0; i<N; i++) {
            u[i][0] = u[i][N-1] = u[0][i] = 100.0;
            u[N-1][i] = 0.0;
            mean += u[i][0] + u[i][N-1] + u[0][i] + u[N-1][i];
        }
        mean /= (4.0 *N);
    
        /* Initialize interior values */
        for (i =1; i<N-1; i++)
            for (j=1; j<N-1; j++)
                u[i][j] = mean;
    
    
        // distribute data 
        myN = N / proc_num;
        if(N%proc_num!=0){
            if(my_rank==proc_num-1)
                myN=N-(proc_num-1)*myN;
        }
        if(proc_num > 1) {
            // ghost rows
            if(my_rank == 0 || my_rank == proc_num - 1)
                myN++;
            else
                myN += 2;
        }
    
        // initial value
        for(i = 0; i < myN; i++) {
            for(j = 0; j < N; j++) {
                if(my_rank == 0)
                    myu[i][j] = u[i][j];
                else
                    myu[i][j] = u[my_rank*(N/proc_num)-1+i][j];
        
                myw[i][j]=myu[i][j];
            }
        }
        
        mflush();
        backup();
   }
    struct timeval start_tv, end_tv;
    gettimeofday(&start_tv, NULL);

    double alldiff=0;
    int left  = my_rank - 1;
    int right = my_rank +1;
    MPI_Request send_req1, recv_req1;
    MPI_Request send_req2, recv_req2;
    while(1)
    {
        iter++;

        diff = 0.0;
        for (i=1; i<myN-1; i++) {
            for (j=1; j<N-1; j++) {
                myw[i][j] = (myu[i-1][j] + myu[i+1][j] + myu[i][j-1] + myu[i][j+1])/4.0;
                if (fabs (myw[i][j] - myu[i][j]) > diff)
                    diff = fabs(myw[i][j] - myu[i][j]);
            }
        }

        // reduce diff
        MPI_Allreduce(&diff, &alldiff, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD);
        #ifdef PRINTITER
        if(my_rank==0){
            printf("iter=%d, diff=%lf\n", iter, alldiff);
            fflush(stdout);
        }
        #endif

        if (alldiff <= epsilon)
            break;


        if(proc_num > 1) {

            // send second top row
            if(my_rank != 0){ 
                MPI_Isend(myw[1], N, MPI_DOUBLE, left, 0, MPI_COMM_WORLD, &send_req1);
                //printf("Send: %d->%d\n", my_rank, left);
            }
            // send second to bottom row
            if(my_rank != proc_num - 1){ 
                MPI_Isend(myw[myN-2], N, MPI_DOUBLE, right, 1, MPI_COMM_WORLD, &send_req2);
                //printf("Send %d->%d\n", my_rank, right);
            }
            
            // recive top
            if(my_rank != 0){ 
                MPI_Irecv(myw[0], N, MPI_DOUBLE, left, 1, MPI_COMM_WORLD, &recv_req1);
                //printf("Recv: %d->%d\n", my_rank, left);
            }

            // receive bottom
            if(my_rank != proc_num - 1) {
                MPI_Irecv(myw[myN-1], N, MPI_DOUBLE, right, 0, MPI_COMM_WORLD, &recv_req2);
                //printf("Recv %d->%d\n", my_rank, right);
            }

            if(my_rank != 0) 
                MPI_Wait(&send_req1, &status);
            if(my_rank != proc_num - 1) 
                MPI_Wait(&send_req2, &status);
            if(my_rank != 0) 
                MPI_Wait(&recv_req1, &status);
            if(my_rank != proc_num - 1) 
                MPI_Wait(&recv_req2, &status);
        }
        
        for (i=0; i<myN; i++) {
            if( (i==0&&my_rank==0) ||(i==myN-1&&my_rank==proc_num-1))
                continue;
            for (j=1; j<N-1; j++)
                myu[i][j] = myw[i][j];
        }
        
        // backup
        if(iter%cfreq == 0)
            backup();
    }

    gettimeofday(&end_tv, NULL);
    printf("Elapsed time: %f sec\n",
           (double)( (double)(end_tv.tv_sec - start_tv.tv_sec) + ( (double)(end_tv.tv_usec - start_tv.tv_usec)/1000000)) );

    // gather data
    if(my_rank==0) {
        for (i=0; i<myN; i++) {
            for(j=0; j<N; j++) {
                u[i][j] = myu[i][j];
            }
        }

        if(proc_num > 1) {
            for (i=1; i<proc_num-1; i++) 
                MPI_Recv(u[i*(N/proc_num)], (N/proc_num)*N, MPI_DOUBLE, i, 0, MPI_COMM_WORLD, &status);

            // special care for last one
            if(N%proc_num==0)
                MPI_Recv(u[i*(N/proc_num)], (N/proc_num)*N, MPI_DOUBLE, i, 0, MPI_COMM_WORLD, &status);
            else{
                MPI_Recv(u[i*(N/proc_num)], (N-(N/proc_num)*(proc_num-1))*N, MPI_DOUBLE, i, 0, MPI_COMM_WORLD, &status);
            }
        }
    }
    else {
            if(N%proc_num==0)
                MPI_Send(myu[1], (N/proc_num)*N, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);
            else{
                if(my_rank != proc_num-1)
                    MPI_Send(myu[1], (myN-2)*N, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);
                else
                    MPI_Send(myu[1], (myN-1)*N, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);
            }
    }


    if(my_rank == 0) {

        /* Print Solution */
        fp = fopen("output.dat", "w");
        for (i=0; i<N; i++) {
            for (j=0; j<N; j++) {
                fprintf(fp, "%6.2f ", u[i][j]);
            }
            fprintf(fp, "\n");
        }
        fclose(fp);

    }
	mclose();
	bclose();
    MPI_Finalize();
    return 0;
}
Пример #27
0
/*
 *	Main -- entry point from LINUX
 */
int main(int argc, char** argv)
{
    int i, demo = 0;
    printf("OK open data!!!\n");
    printf("open data OK!\n");
    for (i = 0; i < argc; i++) {
        if (strcmp(argv[i], "-demo") == 0) {
			demo++;
		}
	}
/*	Initialize the memory allocator. Allow use of malloc and start 
 *	with a 60K heap.  For each page request approx 8KB is allocated.
 *	60KB allows for several concurrent page requests.  If more space
 *	is required, malloc will be used for the overflow.
 */
	bopen(NULL, (60 * 1024), B_USE_MALLOC);
	signal(SIGPIPE, SIG_IGN);
	signal(SIGINT, sigintHandler);
    signal(SIGTERM, sigintHandler);
/*
 *	Initialize the web server
 */
	if (initWebs(demo) < 0) 
    {
		return -1;
	}
    printf("Init Web service ok!\n");
#ifdef WEBS_SSL_SUPPORT
	websSSLOpen();
        /*	websRequireSSL("/"); */	/* Require all files be served via https */
#endif

        /*
         *	Basic event loop. SocketReady returns true when a socket is ready for
         *	service. SocketSelect will block until an event occurs. SocketProcess
         *	will actually do the servicing.
         */
	finished = 0;
	while (!finished)
    {
		if (socketReady(-1) || socketSelect(-1, 1000))
        {
			socketProcess(-1);
		}
        websCgiCleanup();
        emfSchedProcess();
    }
#ifdef WEBS_SSL_SUPPORT
	websSSLClose();
#endif
#ifdef USER_MANAGEMENT_SUPPORT
	umClose();
#endif
/*
 *	Close the socket module, report memory leaks and close the memory allocator
 */
	websCloseServer();
	socketClose();
#ifdef B_STATS
	memLeaks();
#endif
	bclose();
	return 0;
}
Пример #28
0
int do_restore_client_burp1(struct asfd *asfd,
                            struct conf *conf, enum action act, int vss_restore)
{
    int ars=0;
    int ret=-1;
    char msg[512]="";
    struct sbuf *sb=NULL;
// Windows needs to have the VSS data written first, and the actual data
// written immediately afterwards. The server is transferring them in two
// chunks. So, leave bfd open after a Windows metadata transfer.
    BFILE bfd;
#ifdef HAVE_WIN32
    binit(&bfd, 0, conf);
#endif

    logp("doing %s\n", act_str(act));

    snprintf(msg, sizeof(msg), "%s %s:%s", act_str(act),
             conf->backup?conf->backup:"", conf->regex?conf->regex:"");
    if(asfd->write_str(asfd, CMD_GEN, msg)
            || asfd->read_expect(asfd, CMD_GEN, "ok"))
        return -1;
    logp("doing %s confirmed\n", act_str(act));

    if(conf->send_client_cntr)
    {
// FIX THIS
//		if(cntr_recv(conf)) goto end;
    }

#if defined(HAVE_WIN32)
    if(act==ACTION_RESTORE) win32_enable_backup_privileges();
#endif

    if(!(sb=sbuf_alloc(conf))) goto end;
    while(1)
    {
        char *fullpath=NULL;

        sbuf_free_content(sb);
        if((ars=sbufl_fill(sb, asfd, NULL, NULL, conf->cntr)))
        {
            if(ars<0) goto end;
            else
            {
                // ars==1 means it ended ok.
                //logp("got %s end\n", act_str(act));
                if(asfd->write_str(asfd,
                                   CMD_GEN, "restoreend ok")) goto end;
            }
            break;
        }

        switch(sb->path.cmd)
        {
        case CMD_DIRECTORY:
        case CMD_FILE:
        case CMD_ENC_FILE:
        case CMD_SOFT_LINK:
        case CMD_HARD_LINK:
        case CMD_SPECIAL:
        case CMD_METADATA:
        case CMD_ENC_METADATA:
        case CMD_VSS:
        case CMD_ENC_VSS:
        case CMD_VSS_T:
        case CMD_ENC_VSS_T:
        case CMD_EFS_FILE:
            if(conf->strip)
            {
                int s;
                s=strip_path_components(asfd, sb,
                                        &(sb->path.buf), conf);
                if(s<0) goto end; // error
                else if(s==0)
                {
                    // Too many components stripped
                    // - carry on.
                    continue;
                }
                // It is OK, sb->path is now stripped.
            }
            if(!(fullpath=prepend_s(conf->restoreprefix,
                                    sb->path.buf)))
            {
                log_and_send_oom(asfd, __func__);
                goto end;
            }
            if(act==ACTION_RESTORE)
            {
                strip_invalid_characters(&fullpath);
                if(!overwrite_ok(sb, conf, &bfd, fullpath))
                {
                    char msg[512]="";
                    // Something exists at that path.
                    snprintf(msg, sizeof(msg),
                             "Path exists: %s", fullpath);
                    if(restore_interrupt(asfd, sb, msg, conf))
                        goto end;
                    else
                    {
                        if(fullpath) free(fullpath);
                        continue;
                    }
                }
            }
            break;
        default:
            break;
        }

        switch(sb->path.cmd)
        {
        case CMD_WARNING:
            cntr_add(conf->cntr, sb->path.cmd, 1);
            printf("\n");
            logp("%s", sb->path);
            break;
        case CMD_DIRECTORY:
            if(restore_dir(asfd, sb, fullpath, act, conf))
                goto end;
            break;
        case CMD_FILE:
        case CMD_VSS_T:
            // Have it a separate statement to the
            // encrypted version so that encrypted and not
            // encrypted files can be restored at the
            // same time.
            if(restore_file_or_get_meta(asfd, &bfd, sb,
                                        fullpath, act,
                                        NULL, NULL, NULL,
                                        vss_restore, conf))
            {
                logp("restore_file error\n");
                goto end;
            }
            break;
        case CMD_ENC_FILE:
        case CMD_ENC_VSS_T:
            if(restore_file_or_get_meta(asfd, &bfd, sb,
                                        fullpath, act,
                                        conf->encryption_password,
                                        NULL, NULL, vss_restore, conf))
            {
                logp("restore_file error\n");
                goto end;
            }
            break;
        case CMD_SOFT_LINK:
        case CMD_HARD_LINK:
            if(restore_link(asfd, sb, fullpath,
                            conf->restoreprefix, act, conf))
                goto end;
            break;
        case CMD_SPECIAL:
            if(restore_special(asfd, sb, fullpath, act, conf))
                goto end;
            break;
        case CMD_METADATA:
        case CMD_VSS:
            if(restore_metadata(asfd, &bfd, sb, fullpath,
                                act, NULL, vss_restore, conf))
                goto end;
            break;
        case CMD_ENC_METADATA:
        case CMD_ENC_VSS:
            if(restore_metadata(asfd, &bfd, sb, fullpath,
                                act, conf->encryption_password,
                                vss_restore, conf))
                goto end;
            break;
        case CMD_EFS_FILE:
            if(restore_file_or_get_meta(asfd, &bfd, sb,
                                        fullpath, act,
                                        NULL, NULL, NULL, vss_restore, conf))
            {
                logp("restore_file error\n");
                goto end;
            }
            break;
        default:
            logp("unknown cmd: %c\n", sb->path.cmd);
            goto end;
            break;
        }

        if(fullpath) free(fullpath);
    }

    ret=0;
end:
    sbuf_free(sb);

#ifdef HAVE_WIN32
    // It is possible for a bfd to still be open.
    bclose(&bfd, asfd);
#endif

    cntr_print_end(conf->cntr);
    cntr_print(conf->cntr, act);

    if(!ret) logp("%s finished\n", act_str(act));
    else logp("ret: %d\n", ret);

    return ret;
}
Пример #29
0
/**
 * Called here by find() for each file included.
 *   This is a callback. The original is find_files() above.
 *
 *  Send the file and its data to the Storage daemon.
 *
 *  Returns: 1 if OK
 *           0 if error
 *          -1 to ignore file/directory (not used here)
 */
int save_file(JCR *jcr, FF_PKT *ff_pkt, bool top_level)
{
   bool do_read = false;
   bool plugin_started = false;
   bool do_plugin_set = false;
   int status, data_stream;
   int rtnstat = 0;
   b_save_ctx bsctx;
   bool has_file_data = false;
   struct save_pkt sp;          /* use by option plugin */
   BSOCK *sd = jcr->store_bsock;

   if (jcr->is_canceled() || jcr->is_incomplete()) {
      return 0;
   }

   jcr->num_files_examined++;         /* bump total file count */

   switch (ff_pkt->type) {
   case FT_LNKSAVED:                  /* Hard linked, file already saved */
      Dmsg2(130, "FT_LNKSAVED hard link: %s => %s\n", ff_pkt->fname, ff_pkt->link);
      break;
   case FT_REGE:
      Dmsg1(130, "FT_REGE saving: %s\n", ff_pkt->fname);
      has_file_data = true;
      break;
   case FT_REG:
      Dmsg1(130, "FT_REG saving: %s\n", ff_pkt->fname);
      has_file_data = true;
      break;
   case FT_LNK:
      Dmsg2(130, "FT_LNK saving: %s -> %s\n", ff_pkt->fname, ff_pkt->link);
      break;
   case FT_RESTORE_FIRST:
      Dmsg1(100, "FT_RESTORE_FIRST saving: %s\n", ff_pkt->fname);
      break;
   case FT_PLUGIN_CONFIG:
      Dmsg1(100, "FT_PLUGIN_CONFIG saving: %s\n", ff_pkt->fname);
      break;
   case FT_DIRBEGIN:
      jcr->num_files_examined--;      /* correct file count */
      return 1;                       /* not used */
   case FT_NORECURSE:
      Jmsg(jcr, M_INFO, 1, _("     Recursion turned off. Will not descend from %s into %s\n"),
           ff_pkt->top_fname, ff_pkt->fname);
      ff_pkt->type = FT_DIREND;       /* Backup only the directory entry */
      break;
   case FT_NOFSCHG:
      /* Suppress message for /dev filesystems */
      if (!is_in_fileset(ff_pkt)) {
         Jmsg(jcr, M_INFO, 1, _("     %s is a different filesystem. Will not descend from %s into it.\n"),
              ff_pkt->fname, ff_pkt->top_fname);
      }
      ff_pkt->type = FT_DIREND;       /* Backup only the directory entry */
      break;
   case FT_INVALIDFS:
      Jmsg(jcr, M_INFO, 1, _("     Disallowed filesystem. Will not descend from %s into %s\n"),
           ff_pkt->top_fname, ff_pkt->fname);
      ff_pkt->type = FT_DIREND;       /* Backup only the directory entry */
      break;
   case FT_INVALIDDT:
      Jmsg(jcr, M_INFO, 1, _("     Disallowed drive type. Will not descend into %s\n"),
           ff_pkt->fname);
      break;
   case FT_REPARSE:
   case FT_JUNCTION:
   case FT_DIREND:
      Dmsg1(130, "FT_DIREND: %s\n", ff_pkt->link);
      break;
   case FT_SPEC:
      Dmsg1(130, "FT_SPEC saving: %s\n", ff_pkt->fname);
      if (S_ISSOCK(ff_pkt->statp.st_mode)) {
        Jmsg(jcr, M_SKIPPED, 1, _("     Socket file skipped: %s\n"), ff_pkt->fname);
        return 1;
      }
      break;
   case FT_RAW:
      Dmsg1(130, "FT_RAW saving: %s\n", ff_pkt->fname);
      has_file_data = true;
      break;
   case FT_FIFO:
      Dmsg1(130, "FT_FIFO saving: %s\n", ff_pkt->fname);
      break;
   case FT_NOACCESS: {
      berrno be;
      Jmsg(jcr, M_NOTSAVED, 0, _("     Could not access \"%s\": ERR=%s\n"),
           ff_pkt->fname, be.bstrerror(ff_pkt->ff_errno));
      jcr->JobErrors++;
      return 1;
   }
   case FT_NOFOLLOW: {
      berrno be;
      Jmsg(jcr, M_NOTSAVED, 0, _("     Could not follow link \"%s\": ERR=%s\n"),
           ff_pkt->fname, be.bstrerror(ff_pkt->ff_errno));
      jcr->JobErrors++;
      return 1;
   }
   case FT_NOSTAT: {
      berrno be;
      Jmsg(jcr, M_NOTSAVED, 0, _("     Could not stat \"%s\": ERR=%s\n"),
           ff_pkt->fname, be.bstrerror(ff_pkt->ff_errno));
      jcr->JobErrors++;
      return 1;
   }
   case FT_DIRNOCHG:
   case FT_NOCHG:
      Jmsg(jcr, M_SKIPPED, 1, _("     Unchanged file skipped: %s\n"), ff_pkt->fname);
      return 1;
   case FT_ISARCH:
      Jmsg(jcr, M_NOTSAVED, 0, _("     Archive file not saved: %s\n"), ff_pkt->fname);
      return 1;
   case FT_NOOPEN: {
      berrno be;
      Jmsg(jcr, M_NOTSAVED, 0, _("     Could not open directory \"%s\": ERR=%s\n"),
           ff_pkt->fname, be.bstrerror(ff_pkt->ff_errno));
      jcr->JobErrors++;
      return 1;
   }
   case FT_DELETED:
      Dmsg1(130, "FT_DELETED: %s\n", ff_pkt->fname);
      break;
   default:
      Jmsg(jcr, M_NOTSAVED, 0,  _("     Unknown file type %d; not saved: %s\n"),
           ff_pkt->type, ff_pkt->fname);
      jcr->JobErrors++;
      return 1;
   }

   Dmsg1(130, "filed: sending %s to stored\n", ff_pkt->fname);

   /*
    * Setup backup signing context.
    */
   memset(&bsctx, 0, sizeof(b_save_ctx));
   bsctx.digest_stream = STREAM_NONE;
   bsctx.jcr = jcr;
   bsctx.ff_pkt = ff_pkt;

   /*
    * Digests and encryption are only useful if there's file data
    */
   if (has_file_data) {
      if (!setup_encryption_digests(bsctx)) {
         goto good_rtn;
      }
   }

   /*
    * Initialize the file descriptor we use for data and other streams.
    */
   binit(&ff_pkt->bfd);
   if (bit_is_set(FO_PORTABLE, ff_pkt->flags)) {
      set_portable_backup(&ff_pkt->bfd); /* disable Win32 BackupRead() */
   }

   /*
    * Option and cmd plugin are not compatible together
    */
   if (ff_pkt->cmd_plugin) {
      do_plugin_set = true;
   } else if (ff_pkt->opt_plugin) {
      /*
       * Ask the option plugin what to do with this file
       */
      switch (plugin_option_handle_file(jcr, ff_pkt, &sp)) {
      case bRC_OK:
         Dmsg2(10, "Option plugin %s will be used to backup %s\n", ff_pkt->plugin, ff_pkt->fname);
         jcr->opt_plugin = true;
         jcr->plugin_sp = &sp;
         plugin_update_ff_pkt(ff_pkt, &sp);
         do_plugin_set = true;
         break;
      case bRC_Skip:
         Dmsg2(10, "Option plugin %s decided to skip %s\n", ff_pkt->plugin, ff_pkt->fname);
         goto good_rtn;
      case bRC_Core:
         Dmsg2(10, "Option plugin %s decided to let bareos handle %s\n", ff_pkt->plugin, ff_pkt->fname);
         break;
      default:
         goto bail_out;
      }
   }

   if (do_plugin_set) {
      /*
       * Tell bfile that it needs to call plugin
       */
      if (!set_cmd_plugin(&ff_pkt->bfd, jcr)) {
         goto bail_out;
      }
      send_plugin_name(jcr, sd, true);      /* signal start of plugin data */
      plugin_started = true;
   }

   /*
    * Send attributes -- must be done after binit()
    */
   if (!encode_and_send_attributes(jcr, ff_pkt, data_stream)) {
      goto bail_out;
   }

   /*
    * Meta data only for restore object
    */
   if (IS_FT_OBJECT(ff_pkt->type)) {
      goto good_rtn;
   }

   /*
    * Meta data only for deleted files
    */
   if (ff_pkt->type == FT_DELETED) {
      goto good_rtn;
   }

   /*
    * Set up the encryption context and send the session data to the SD
    */
   if (has_file_data && jcr->crypto.pki_encrypt) {
      if (!crypto_session_send(jcr, sd)) {
         goto bail_out;
      }
   }

   /*
    * For a command plugin use the setting from the plugins savepkt no_read field
    * which is saved in the ff_pkt->no_read variable. do_read is the inverted
    * value of this variable as no_read == TRUE means do_read == FALSE
    */
   if (ff_pkt->cmd_plugin) {
      do_read = !ff_pkt->no_read;
   } else {
      /*
       * Open any file with data that we intend to save, then save it.
       *
       * Note, if is_win32_backup, we must open the Directory so that
       * the BackupRead will save its permissions and ownership streams.
       */
      if (ff_pkt->type != FT_LNKSAVED && S_ISREG(ff_pkt->statp.st_mode)) {
#ifdef HAVE_WIN32
         do_read = !is_portable_backup(&ff_pkt->bfd) || ff_pkt->statp.st_size > 0;
#else
         do_read = ff_pkt->statp.st_size > 0;
#endif
      } else if (ff_pkt->type == FT_RAW ||
                 ff_pkt->type == FT_FIFO ||
                 ff_pkt->type == FT_REPARSE ||
                 ff_pkt->type == FT_JUNCTION ||
                (!is_portable_backup(&ff_pkt->bfd) &&
                 ff_pkt->type == FT_DIREND)) {
         do_read = true;
      }
   }

   Dmsg2(150, "type=%d do_read=%d\n", ff_pkt->type, do_read);
   if (do_read) {
      btimer_t *tid;
      int noatime;

      if (ff_pkt->type == FT_FIFO) {
         tid = start_thread_timer(jcr, pthread_self(), 60);
      } else {
         tid = NULL;
      }

      noatime = bit_is_set(FO_NOATIME, ff_pkt->flags) ? O_NOATIME : 0;
      ff_pkt->bfd.reparse_point = (ff_pkt->type == FT_REPARSE ||
                                   ff_pkt->type == FT_JUNCTION);

      if (bopen(&ff_pkt->bfd, ff_pkt->fname, O_RDONLY | O_BINARY | noatime, 0, ff_pkt->statp.st_rdev) < 0) {
         ff_pkt->ff_errno = errno;
         berrno be;
         Jmsg(jcr, M_NOTSAVED, 0,
              _("     Cannot open \"%s\": ERR=%s.\n"),
              ff_pkt->fname, be.bstrerror());
         jcr->JobErrors++;
         if (tid) {
            stop_thread_timer(tid);
            tid = NULL;
         }
         goto good_rtn;
      }

      if (tid) {
         stop_thread_timer(tid);
         tid = NULL;
      }

      status = send_data(jcr, data_stream, ff_pkt, bsctx.digest, bsctx.signing_digest);

      if (bit_is_set(FO_CHKCHANGES, ff_pkt->flags)) {
         has_file_changed(jcr, ff_pkt);
      }

      bclose(&ff_pkt->bfd);

      if (!status) {
         goto bail_out;
      }
   }

   if (have_darwin_os) {
      /*
       * Regular files can have resource forks and Finder Info
       */
      if (ff_pkt->type != FT_LNKSAVED &&
         (S_ISREG(ff_pkt->statp.st_mode) &&
          bit_is_set(FO_HFSPLUS, ff_pkt->flags))) {
         if (!save_rsrc_and_finder(bsctx)) {
            goto bail_out;
         }
      }
   }

   /*
    * Save ACLs when requested and available for anything not being a symlink.
    */
   if (have_acl) {
      if (bit_is_set(FO_ACL, ff_pkt->flags) && ff_pkt->type != FT_LNK) {
         if (!do_backup_acl(jcr, ff_pkt)) {
            goto bail_out;
         }
      }
   }

   /*
    * Save Extended Attributes when requested and available for all files.
    */
   if (have_xattr) {
      if (bit_is_set(FO_XATTR, ff_pkt->flags)) {
         if (!do_backup_xattr(jcr, ff_pkt)) {
            goto bail_out;
         }
      }
   }

   /*
    * Terminate the signing digest and send it to the Storage daemon
    */
   if (bsctx.signing_digest) {
      if (!terminate_signing_digest(bsctx)) {
         goto bail_out;
      }
   }

   /*
    * Terminate any digest and send it to Storage daemon
    */
   if (bsctx.digest) {
      if (!terminate_digest(bsctx)) {
         goto bail_out;
      }
   }

   /*
    * Check if original file has a digest, and send it
    */
   if (ff_pkt->type == FT_LNKSAVED && ff_pkt->digest) {
      Dmsg2(300, "Link %s digest %d\n", ff_pkt->fname, ff_pkt->digest_len);
      sd->fsend("%ld %d 0", jcr->JobFiles, ff_pkt->digest_stream);

      sd->msg = check_pool_memory_size(sd->msg, ff_pkt->digest_len);
      memcpy(sd->msg, ff_pkt->digest, ff_pkt->digest_len);
      sd->msglen = ff_pkt->digest_len;
      sd->send();

      sd->signal(BNET_EOD);              /* end of hardlink record */
   }

good_rtn:
   rtnstat = jcr->is_canceled() ? 0 : 1; /* good return if not canceled */

bail_out:
   if (jcr->is_incomplete() || jcr->is_canceled()) {
      rtnstat = 0;
   }
   if (plugin_started) {
      send_plugin_name(jcr, sd, false); /* signal end of plugin data */
   }
   if (ff_pkt->opt_plugin) {
      jcr->plugin_sp = NULL;            /* sp is local to this function */
      jcr->opt_plugin = false;
   }
   if (bsctx.digest) {
      crypto_digest_free(bsctx.digest);
   }
   if (bsctx.signing_digest) {
      crypto_digest_free(bsctx.signing_digest);
   }

   return rtnstat;
}
Пример #30
0
static int restore_file_or_get_meta(struct asfd *asfd, BFILE *bfd,
	struct sbuf *sb, const char *fname, enum action act,
	const char *encpassword, char **metadata, size_t *metalen,
	int vss_restore, struct conf *conf)
{
	int ret=0;
	char *rpath=NULL;

	if(act==ACTION_VERIFY)
	{
		cntr_add(conf->cntr, sb->path.cmd, 1);
		return 0;
	}

	if(build_path(fname, "", &rpath, NULL))
	{
		char msg[256]="";
		// failed - do a warning
		snprintf(msg, sizeof(msg), "build path failed: %s", fname);
		if(restore_interrupt(asfd, sb, msg, conf))
			ret=-1;
		goto end;
	}

#ifndef HAVE_WIN32
	// We always want to open the file if it is on Windows. Otherwise,
	// only open it if we are not doing metadata.
	if(!metadata)
	{
#endif
		if(open_for_restore(asfd, bfd, rpath, sb, vss_restore, conf))
		{
			ret=-1;
			goto end;
		}
#ifndef HAVE_WIN32
	}
#endif

	if(!ret)
	{
		int enccompressed=0;
		unsigned long long rcvdbytes=0;
		unsigned long long sentbytes=0;

		enccompressed=dpthl_is_compressed(sb->compression, sb->burp1->datapth.buf);
/*
		printf("%s \n", fname);
		if(encpassword && !enccompressed)
			printf("encrypted and not compressed\n");
		else if(!encpassword && enccompressed)
			printf("not encrypted and compressed\n");
		else if(!encpassword && !enccompressed)
			printf("not encrypted and not compressed\n");
		else if(encpassword && enccompressed)
			printf("encrypted and compressed\n");
*/

		if(metadata)
		{
			ret=transfer_gzfile_inl(asfd, sb, fname, NULL,
				&rcvdbytes, &sentbytes,
				encpassword, enccompressed,
				conf->cntr, metadata);
			*metalen=sentbytes;
			// skip setting cntr, as we do not actually
			// restore until a bit later
			goto end;
		}
		else
		{
			ret=transfer_gzfile_inl(asfd, sb, fname, bfd,
				&rcvdbytes, &sentbytes,
				encpassword, enccompressed, conf->cntr, NULL);
#ifndef HAVE_WIN32
			if(bclose(bfd, asfd))
			{
				logp("error closing %s in %s\n",
					fname, __func__);
				ret=-1;
			}
#endif
			if(!ret) attribs_set(asfd, rpath,
				&(sb->statp), sb->winattr, conf);
		}
		if(ret)
		{
			char msg[256]="";
			snprintf(msg, sizeof(msg),
				"Could not transfer file in: %s", rpath);
			if(restore_interrupt(asfd, sb, msg, conf))
				ret=-1;
			goto end;
		}
	}
	if(!ret) cntr_add(conf->cntr, sb->path.cmd, 1);
end:
	if(rpath) free(rpath);
	return ret;
}