Example #1
0
static int setup_out_fd(void)
{
	int fd;
	TALLOC_CTX *ctx = talloc_stackframe();
	char *path = NULL;

	path = talloc_asprintf(ctx,
				"%s/smb.XXXXXX",
				tmpdir());
	if (!path) {
		TALLOC_FREE(ctx);
		errno = ENOMEM;
		return -1;
	}

	/* now create the file */
	fd = smb_mkstemp(path);

	if (fd == -1) {
		DEBUG(0,("setup_out_fd: Failed to create file %s. (%s)\n",
			path, strerror(errno) ));
		TALLOC_FREE(ctx);
		return -1;
	}

	DEBUG(10,("setup_out_fd: Created tmp file %s\n", path ));

	/* Ensure file only kept around by open fd. */
	unlink(path);
	TALLOC_FREE(ctx);
	return fd;
}
Example #2
0
/***************************************************** 
setup the shared area 
*******************************************************/
void smbw_setup_shared(void)
{
	int fd;
	pstring name, s;

	slprintf(name,sizeof(name)-1, "%s/smbw.XXXXXX",tmpdir());

	fd = smb_mkstemp(name);

	if (fd == -1) goto failed;

	unlink(name);

	shared_fd = set_maxfiles(SMBW_MAX_OPEN);
	
	while (shared_fd && dup2(fd, shared_fd) != shared_fd) shared_fd--;

	if (shared_fd == 0) goto failed;

	close(fd);

	DEBUG(4,("created shared_fd=%d\n", shared_fd));

	slprintf(s,sizeof(s)-1,"%d", shared_fd);

	setenv("SMBW_HANDLE", s, 1);

	return;

 failed:
	perror("Failed to setup shared variable area ");
	exit(1);
}
Example #3
0
/***************************************************** 
setup the shared area 
*******************************************************/
void smbw_setup_shared(void)
{
	int fd;
	pstring s, name;

	slprintf(s,sizeof(s)-1, "%s/smbw.XXXXXX",tmpdir());

	fstrcpy(name,(char *)smbd_mktemp(s));

	/* note zero permissions! don't change this */
	fd = sys_open(name,O_RDWR|O_CREAT|O_TRUNC|O_EXCL,0); 
	if (fd == -1) goto failed;
	unlink(name);

	shared_fd = set_maxfiles(SMBW_MAX_OPEN);
	
	while (shared_fd && dup2(fd, shared_fd) != shared_fd) shared_fd--;

	if (shared_fd == 0) goto failed;

	close(fd);

	DEBUG(4,("created shared_fd=%d\n", shared_fd));

	slprintf(s,sizeof(s)-1,"%d", shared_fd);

	smbw_setenv("SMBW_HANDLE", s);

	return;

 failed:
	perror("Failed to setup shared variable area ");
	exit(1);
}
Example #4
0
bool checkForDir(const QString & dir)
{
    QDir tmpdir(dir);
    if (!tmpdir.exists())
        if (!tmpdir.mkpath(dir))
        {
            MessageDialog::ShowErrorMessage(HWApplication::tr("Cannot create directory %1").arg(dir));
            return false;
        }
    return true;
}
Example #5
0
 char const * tmpnam(char * buffer) {
     static char name[512] = {0};
     if (name[0] == 0) {
         boost::filesystem::path tempdir(tmpdir());
         boost::filesystem::path tempfilename =
             boost::filesystem::unique_path("serialization-%%%%");
         boost::filesystem::path temp = tempdir / tempfilename;
         std::strcat(name, temp.string().c_str());
     }
     if (buffer != 0) std::strcpy(buffer, name);
     return name;
 }
Example #6
0
void createroot(char *src, int console, char *helper) {
  mode_t mask;
  pid_t child;

  root = tmpdir();
  atexit(cleanup);

  if (mount(src, root, NULL, MS_BIND | MS_REC, NULL) < 0)
    die(0, "Failed to bind new root filesystem");
  else if (chdir(root) < 0)
    die(0, "Failed to enter new root filesystem");

  mask = umask(0);
  mkdir("dev" , 0755);
  if (mount("tmpfs", "dev", "tmpfs", 0, "mode=0755") < 0)
    die(0, "Failed to mount /dev tmpfs in new root filesystem");

  mkdir("dev/pts", 0755);
  if (mount("devpts", "dev/pts", "devpts", 0, "newinstance,ptmxmode=666") < 0)
    die(0, "Failed to mount /dev/pts in new root filesystem");

  mkdir("dev/tmp", 0755);
  umask(mask);

  if (console >= 0)
    bindnode(ptsname(console), "dev/console");
  bindnode("/dev/full", "dev/full");
  bindnode("/dev/null", "dev/null");
  bindnode("/dev/random", "dev/random");
  bindnode("/dev/tty", "dev/tty");
  bindnode("/dev/urandom", "dev/urandom");
  bindnode("/dev/zero", "dev/zero");
  symlink("pts/ptmx", "dev/ptmx");

  if (helper)
    switch (child = fork()) {
      case -1:
        die(errno, "fork");
      case 0:
        execlp(SHELL, SHELL, "-c", helper, NULL);
        die(errno, "exec %s", helper);
      default:
        waitforexit(child);
    }
}
Example #7
0
int
oldnew2c_diff(int mindiff, int context, char *ignore, char *function, char *old_fn, char *new_fn, char *c_diff_fn)
{
	char w_diff_fn[CMDLEN];
	int rtrn = 0;

	TRACE(fprintf(STDERR, "oldnew2c_diff(%i,%i,%s,%s,%s,%s,%s)\n", mindiff, context, ignore, function, old_fn, new_fn, c_diff_fn));

	sprintf(w_diff_fn, "%s%c.difflib-%ld-oldnew2c_diff-w_diff", tmpdir(), DIR_SEP, (long) getpid());

	if (!oldnew2w_diff(mindiff, context, ignore, function, old_fn, new_fn, w_diff_fn)) {
		UNLINK(w_diff_fn);
		ERRHNDL(0, "oldnew2w_diff returns 0 in oldnew2c_diff", "", 1);
	}

	rtrn = w_diff2c_diff(mindiff, w_diff_fn, c_diff_fn);

	UNLINK(w_diff_fn);
	return rtrn;
}
Example #8
0
/* Create a temporary policy directory */
static const char *gp_tmpdir(TALLOC_CTX *mem_ctx)
{
	char *gp_dir = talloc_asprintf(mem_ctx, "%s/policy", tmpdir());
	struct stat st;
	int rv;

	if (gp_dir == NULL) return NULL;

	if (stat(gp_dir, &st) != 0) {
		rv = mkdir(gp_dir, 0755);
		if (rv < 0) {
			DEBUG(0, ("Failed to create directory %s: %s\n",
					gp_dir, strerror(errno)));
			talloc_free(gp_dir);
			return NULL;
		}
	}

	return gp_dir;
}
Example #9
0
SAWYER_EXPORT void
PodFormatter::emit(const ParserResult &parsed) {
    // Generate POD documentation into a temporary file.  Since perldoc doesn't support the "name" property, but rather
    // uses the file name, we create a temporary directory and place a POD file inside with the name we want.
    TempDir tmpdir(tempFileName());
    std::string fileName = tmpdir.name + pageName_ + ".pod";
    {
        std::ofstream stream(fileName.c_str());
        parsed.emit(stream, sharedFromThis());
    }

    std::string cmd = "perldoc "
                      " -o man"
                      " -w 'center:" + escapeSingleQuoted(chapterName_) + "'"
                      " -w 'date:" + escapeSingleQuoted(dateString_) + "'"
                      // " -w 'name:" + escapeSingleQuoted(pageName_) + "'"
                      " -w 'release:" + escapeSingleQuoted(versionString_) + "'"
                      " -w 'section:" + escapeSingleQuoted(chapterNumber_) + "'"
                      " " + fileName;
    system(cmd.c_str());
}
Example #10
0
static int setup_out_fd(void)
{  
	int fd;
	pstring path;

	slprintf(path, sizeof(path)-1, "%s/smb.XXXXXX", tmpdir());

	/* now create the file */
	fd = smb_mkstemp(path);

	if (fd == -1) {
		DEBUG(0,("setup_out_fd: Failed to create file %s. (%s)\n",
			path, strerror(errno) ));
		return -1;
	}

	DEBUG(10,("setup_out_fd: Created tmp file %s\n", path ));

	/* Ensure file only kept around by open fd. */
	unlink(path);
	return fd;
}
Example #11
0
/****************************************************************************
get a printer queue
****************************************************************************/
int get_printqueue(int snum,int cnum,print_queue_struct **queue,
		   print_status_struct *status)
{
  char *lpq_command = lp_lpqcommand(snum);
  char *printername = PRINTERNAME(snum);
  int ret=0,count=0;
  pstring syscmd;
  fstring outfile;
  pstring line;
  FILE *f;
  struct stat sbuf;
  BOOL dorun=True;
  int cachetime = lp_lpqcachetime();

  *line = 0;
  check_lpq_cache(snum);
  
  if (!printername || !*printername)
    {
      DEBUG(6,("xx replacing printer name with service (snum=(%s,%d))\n",
	       lp_servicename(snum),snum));
      printername = lp_servicename(snum);
    }
    
  if (!lpq_command || !(*lpq_command))
    {
      DEBUG(5,("No lpq command\n"));
      return(0);
    }
    
  pstrcpy(syscmd,lpq_command);
  string_sub(syscmd,"%p",printername);

  standard_sub(cnum,syscmd);

  slprintf(outfile,sizeof(outfile)-1, "%s/lpq.%08x",tmpdir(),str_checksum(syscmd));
  
  if (!lpq_cache_reset[snum] && cachetime && !stat(outfile,&sbuf)) 
    {
      if (time(NULL) - sbuf.st_mtime < cachetime) {
	DEBUG(3,("Using cached lpq output\n"));
	dorun = False;
      }
    }

  if (dorun) {
    ret = smbrun(syscmd,outfile,True);
    DEBUG(3,("Running the command `%s' gave %d\n",syscmd,ret));
  }

  lpq_cache_reset[snum] = False;

  f = fopen(outfile,"r");
  if (!f) {
    return(0);
  }

  if (status) {
    fstrcpy(status->message,"");
    status->status = LPSTAT_OK;
  }
      
  while (fgets(line,sizeof(pstring),f))
    {
      DEBUG(6,("QUEUE2: %s\n",line));

      *queue = Realloc(*queue,sizeof(print_queue_struct)*(count+1));
      if (! *queue)
	{
	  count = 0;
	  break;
	}

      bzero((char *)&(*queue)[count],sizeof(**queue));
	  
      /* parse it */
      if (!parse_lpq_entry(snum,line,&(*queue)[count],status,count==0))
	continue;
	  
      count++;
    }	      

  fclose(f);

  if (!cachetime) {
    unlink(outfile);
  } else {
    /* we only expect this to succeed on trapdoor systems, on normal systems
     the file is owned by root */
    chmod(outfile,0666);
  }
  return(count);
}
Example #12
0
void loginfrm::saveservers()
{
    int ii = cmbdb->currentIndex();
    
    dbhost= dbserver[ii];
    dbname = dbname_local[ii];
    dbuid = uids[ii];
    dbpwd = pwd[ii];
    dbport = port[ii];
   
    QDir d(QDir::homePath()+"/.first4");
    if(!d.exists() )
    {
		if(!d.mkdir(QDir::homePath()+"/.first4"))
	    	QMessageBox::critical(0,"Error...", tr("Error when storing the server list!"));
    }
    QDir tmpdir(QDir::homePath()+"/.first4/tmp");
    if(!tmpdir.exists() )
    {
		if(!tmpdir.mkdir(QDir::homePath()+"/.first4/tmp"))
	    	QMessageBox::critical(0,"Error...", tr("Error when storing the server list!"));
    }
   
	QStringList lines;
	QFile file ( QDir::homePath() +"/.first4/local.first4.conf" );
	if ( file.open ( QIODevice::ReadOnly ) )
	{
		QTextStream stream ( &file );
		while(!stream.atEnd())
			lines << stream.readLine();
	}
	file.close();
    
	if ( file.open ( QIODevice::WriteOnly ) )
	{
		int i;
		QTextStream stream(&file);
		bool foundsec = FALSE;
		for(i=0;i<lines.count();i++)
		{
			if(lines[i] == "[SERVERS]")
			{
				foundsec = TRUE;
				stream << "[SERVERS]" << "\n";
				if(dbserver[ii] != "")
					stream << "MYSQL:" << uids[ii] << ":" << pwd[ii] << "@" << dbserver[ii] << "/" << dbname_local[ii] << ":" << port[ii] << "\n";
				else
					stream << "SQLITE:" << dbname_local[ii] << "\n";
				for(ii=0;ii<cmbdb->currentIndex();ii++)
				{
					if(dbserver[ii] != "")
		    			stream << "MYSQL:" << uids[ii] << ":" << pwd[ii] << "@" << dbserver[ii] << "/" << dbname_local[ii] << ":" << port[ii] << "\n";	
		    		else
		    			stream << "SQLITE:" << dbname_local[ii] << "\n";
				}
				for(ii=cmbdb->currentIndex()+1;ii<cmbdb->count();ii++)
				{
					if(dbserver[ii] != "")
		    			stream << "MYSQL:" << uids[ii] << ":" << pwd[ii] << "@" << dbserver[ii] << "/" << dbname_local[ii] << ":" << port[ii] << "\n";	
		    		else
		    			stream << "SQLITE:" << dbname_local[ii] << "\n";
				}

				while(lines[i].simplified() != "")
					i++;
				while(i<lines.count())
				{
					stream << lines[i] << "\n";	
					i++;
				}
			}
			else
			{
				stream << lines[i] << "\n";	
			}
		}
		if(!foundsec)
		{
			stream << "\n" << "[SERVERS]" << "\n";
			
			if(dbserver[ii] != "")
				stream << "MYSQL:" << uids[ii] << ":" << pwd[ii] << "@" << dbserver[ii] << "/" << dbname_local[ii] << ":" << port[ii] << "\n";
			else
				stream << "SQLITE:" << dbname_local[ii] << "\n";
				
			for(ii=0;ii<cmbdb->currentIndex();ii++)
			{
				if(dbserver[ii] != "")
	    			stream << "MYSQL:" << uids[ii] << ":" << pwd[ii] << "@" << dbserver[ii] << "/" << dbname_local[ii] << ":" << port[ii] << "\n";	
	    		else
	    			stream << "SQLITE:" << dbname_local[ii] << "\n";
			}
			for(ii=cmbdb->currentIndex()+1;ii<cmbdb->count();ii++)
			{
				if(dbserver[ii] != "")
	    			stream << "MYSQL:" << uids[ii] << ":" << pwd[ii] << "@" << dbserver[ii] << "/" << dbname_local[ii] << ":" << port[ii] << "\n";
	    		else
	    			stream << "SQLITE:" << dbname_local[ii] << "\n";
			}
			stream << "\n";
		}
		file.close();
	}
	else
		QMessageBox::warning(0, "Window positions...", "Can't write to configuration file.");
}
Example #13
0
/****************************************************************************
deliver the message
****************************************************************************/
static void msg_deliver(void)
{
  pstring name;
  int i;
  int fd;
  char *msg;
  int len;

  if (! (*lp_msg_command()))
    {
      DEBUG(1,("no messaging command specified\n"));
      msgpos = 0;
      return;
    }

  /* put it in a temporary file */
  slprintf(name,sizeof(name)-1, "%s/msg.XXXXXX",tmpdir());
  fd = smb_mkstemp(name);

  if (fd == -1) {
    DEBUG(1,("can't open message file %s\n",name));
    return;
  }

  /*
   * Incoming message is in DOS codepage format. Convert to UNIX.
   */
  
  if ((len = convert_string_allocate(NULL,CH_DOS, CH_UNIX, msgbuf, msgpos, (void **) &msg)) < 0 || !msg) {
    DEBUG(3,("Conversion failed, delivering message in DOS codepage format\n"));
    for (i = 0; i < msgpos;) {
      if (msgbuf[i] == '\r' && i < (msgpos-1) && msgbuf[i+1] == '\n') {
	i++; continue;
      }
      write(fd, &msgbuf[i++], 1);
    }
  } else {
    for (i = 0; i < len;) {
      if (msg[i] == '\r' && i < (len-1) && msg[i+1] == '\n') {
	i++; continue;
      }
      write(fd, &msg[i++],1);
    }
    SAFE_FREE(msg);
  }
  close(fd);


  /* run the command */
  if (*lp_msg_command())
    {
      fstring alpha_msgfrom;
      fstring alpha_msgto;
      pstring s;

      pstrcpy(s,lp_msg_command());
      pstring_sub(s,"%f",alpha_strcpy(alpha_msgfrom,msgfrom,NULL,sizeof(alpha_msgfrom)));
      pstring_sub(s,"%t",alpha_strcpy(alpha_msgto,msgto,NULL,sizeof(alpha_msgto)));
      standard_sub_basic(current_user_info.smb_name, s, sizeof(s));
      pstring_sub(s,"%s",name);
      smbrun(s,NULL);
    }

  msgpos = 0;
}
Example #14
0
static NTSTATUS convert_file_from_ucs2(TALLOC_CTX *mem_ctx,
				       const char *filename_in,
				       char **filename_out)
{
	int tmp_fd = -1;
	uint8 *data_in = NULL;
	uint8 *data_out = NULL;
	char *tmp_name = NULL;
	NTSTATUS status;
	size_t n = 0;

	if (!filename_out) {
		return NT_STATUS_INVALID_PARAMETER;
	}

	data_in = (uint8 *)file_load(filename_in, &n, 0);
	if (!data_in) {
		status = NT_STATUS_NO_SUCH_FILE;
		goto out;
	}

	tmp_name = talloc_asprintf(mem_ctx, "%s/convert_file_from_ucs2.XXXXXX",
		tmpdir());
	if (!tmp_name) {
		status = NT_STATUS_NO_MEMORY;
		goto out;
	}

	tmp_fd = smb_mkstemp(tmp_name);
	if (tmp_fd == -1) {
		status = NT_STATUS_ACCESS_DENIED;
		goto out;
	}

	n = convert_string_talloc(mem_ctx, CH_UTF16LE, CH_UNIX,
				  data_in, n, &data_out, False);

	if (n == -1) {
		status = NT_STATUS_INVALID_BUFFER_SIZE;
		goto out;
	}

	/* skip utf8 BOM */
	DEBUG(11,("convert_file_from_ucs2: "
	       "data_out[0]: 0x%x, data_out[1]: 0x%x, data_out[2]: 0x%x\n",
		data_out[0], data_out[1], data_out[2]));

	if ((data_out[0] == 0xef) && (data_out[1] == 0xbb) &&
	    (data_out[2] == 0xbf)) {
		DEBUG(11,("convert_file_from_ucs2: "
			 "%s skipping utf8 BOM\n", tmp_name));
		data_out += 3;
		n -= 3;
	}

	if (sys_write(tmp_fd, data_out, n) != n) {
		status = map_nt_error_from_unix(errno);
		goto out;
	}

	*filename_out = tmp_name;

	status = NT_STATUS_OK;

 out:
	if (tmp_fd != -1) {
		close(tmp_fd);
	}

	SAFE_FREE(data_in);

	return status;
}
Example #15
0
static int
lw_diff2wc_diff(int mindiff, int doChar, char *lw_diff_fn, char *wc_diff_fn)
{
	FILE *lw_diff_fp, *wc_diff_fp, *fp[2], *pipe_fp;
	char line[BUFLEN], command[CMDLEN], pipe_ln[BUFLEN];
	char *ok, *fn[2];
	size_t i;
	int j;
	int space, alpha_, digit, l[2], k[2];
	char wc_old_fn[CMDLEN], wc_new_fn[CMDLEN];
	char *_d = mindiff ? "-d" : "";

	TRACE(fprintf(STDERR, "lw_diff2wc_diff(%i,%i,%s,%s)\n", mindiff, doChar, lw_diff_fn, wc_diff_fn));

	lw_diff_fp = Rfopen(lw_diff_fn);
	if (!(ok = fgets(line, BUFLEN, lw_diff_fp))) {
		fclose(lw_diff_fp);
		ERRHNDL(0, "empty file in lw_diff2wc_diff:", lw_diff_fn, 1);
	}

	sprintf(wc_old_fn, "%s%c.difflib-%ld-lw_diff2wc_diff-old", tmpdir(), DIR_SEP, (long) getpid());
	fn[0] = wc_old_fn;
	sprintf(wc_new_fn, "%s%c.difflib-%ld-lw_diff2wc_diff-new", tmpdir(), DIR_SEP, (long) getpid());
	fn[1] = wc_new_fn;

	wc_diff_fp = Wfopen(wc_diff_fn);
	while (ok && strncmp(line, "@@ -", 4)) {
		fprintf(wc_diff_fp, "%s", line);
		ok = fgets(line, BUFLEN, lw_diff_fp);
	}
	fflush(wc_diff_fp);
	fclose(wc_diff_fp);

	while (ok) {
		wc_diff_fp = Afopen(wc_diff_fn);
		do {
			fprintf(wc_diff_fp, "%s", line);
		} while (line[strlen(line) - 1] != '\n' && (ok = fgets(line, BUFLEN, lw_diff_fp)));
		fflush(wc_diff_fp);
		fclose(wc_diff_fp);

		l[0] = l[1] = k[0] = k[1] = 0;
		for (j = 0; j < 2; j++)
			fp[j] = Wfopen(fn[j]);
		while (ok && (ok = fgets(line, BUFLEN, lw_diff_fp)) && strchr(" -+", line[0])) {
			if (line[0] == ' ') {
				char l1 = line[1];
				while (k[0] < k[1]) {
					markNL(fp[0], k[0]++);
					l[0]++;
				}
				while (k[1] < k[0]) {
					markNL(fp[1], k[1]++);
					l[1]++;
				}
				i = 1;
				do {
					for (j = 0; j < 2; j++) {
						fprintf(fp[j], "%s", line+i);
					}
					i = 0;
				} while (line[strlen(line) - 1] != '\n' && (ok = fgets(line, BUFLEN, lw_diff_fp)));
				for (j = 0; j < 2; j++) {
					l[j]++;
				}
				if (l1 == '\1')
					for (j = 0; j < 2; j++) {
						markNL(fp[j], k[j]++);
						l[j]++;
					}
			} else {
				if (line[0] == '-')
					j = 0;
				else
					j = 1;
				if (line[1] == '\1') {
					fprintf(fp[j], "\1\n");
					markNL(fp[j], k[j]++);
					l[j] += 2;
				} else if (doChar) {
					i = 1;
					do {
						for (; line[i] != '\n' && line[i] != '\0'; i++) {
							fprintf(fp[j], "%c\n", line[i]);
							l[j]++;
						}
						i = 0;
					} while (line[strlen(line) - 1] != '\n' && (ok = fgets(line, BUFLEN, lw_diff_fp)));
				} else {
					space = isspace_((int) (line[1]));
					alpha_ = isalpha_((int) (line[1]));
					digit = isdigit_((int) (line[1]));
					i = 1;
					do {
						for (; line[i] != '\n' && line[i] != '\0'; i++) {
							if ((space && !isspace_((int) line[i])) ||
							    (!space && isspace_((int) line[i])) ||
							    (alpha_ && !isalpha_((int) line[i])) ||
							    (!alpha_ && isalpha_((int) line[i])) ||
							    (digit && !isdigit_((int) line[i])) ||
							    (!digit && isdigit_((int) line[i])) ||
							    (!isspace_((int) line[i]) &&
							     !isalpha_((int) line[i]) &&
							     !isdigit_((int) line[i]))) {
								fprintf(fp[j], "\n");
								space = isspace_((int) line[i]);
								alpha_ = isalpha_((int) line[i]);
								digit = isdigit_((int) line[i]);
								l[j]++;
							}
							fprintf(fp[j], "%c", line[i]);
						}
						i = 0;
					} while (line[strlen(line) - 1] != '\n' && (ok = fgets(line, BUFLEN, lw_diff_fp)));
					fprintf(fp[j], "\n");
					l[j]++;
				}
			}
		}
		for (j = 0; j < 2; j++) {
			fflush(fp[j]);
			fclose(fp[j]);
		}

/*
      sprintf(command,
              "%s -a %s -u%i %s %s | egrep -v '^(@@ \\-|\\+\\+\\+ |\\-\\-\\- |[ \\+\\-]@\\+\\-)' >> %s",
              DIFF,_d,MAX(l[0],l[1]),fn[0],fn[1],wc_diff_fn);
      SYSTEM(command);
*/

		sprintf(command, "%s -a %s -U%d %s %s", DIFF, _d, MAX(l[0], l[1]), fn[0], fn[1]);

		pipe_fp = popen(command, "r");

		wc_diff_fp = Afopen(wc_diff_fn);
		while (fgets(pipe_ln, BUFLEN, pipe_fp)) {
			if (strncmp(pipe_ln, "@@ -", 4) &&
			    strncmp(pipe_ln, "+++ ", 4) &&
			    strncmp(pipe_ln, "--- ", 4) &&
			    strncmp(pipe_ln, " @+-", 4) &&
			    strncmp(pipe_ln, "+@+-", 4) &&
			    strncmp(pipe_ln, "-@+-", 4)) {
				fprintf(wc_diff_fp, "%s", pipe_ln);
			}
		}
		fflush(wc_diff_fp);
		fclose(wc_diff_fp);
		pclose(pipe_fp);
	}
	UNLINK(wc_old_fn);
	UNLINK(wc_new_fn);

	fclose(lw_diff_fp);
	return 1;
}
Example #16
0
// 获得Firefox的下载目录
BOOL bigfilehelper::GetFirefoxDownloadDirs(std::vector<CString>& vDirs)
{
    WCHAR szPath[MAX_PATH] = {0};
    BOOL bRet = FALSE;
    CString szPathFull;
    CString szPathFullEx;
    CString szTarget;
    CString strPath = L"";
    int nPos = -1;
    WCHAR szAppDataPath[MAX_PATH] = { 0 };
    WinVersion winVer;

    winVer = KGetWinVersion();

    if(WINVERSION_WIN7 == winVer)
    {
        bRet = SHGetSpecialFolderPath(NULL, szAppDataPath, CSIDL_PERSONAL, FALSE);
        if(bRet)
        {
            CString tmpdir(szAppDataPath);
            tmpdir = tmpdir.Left(tmpdir.ReverseFind(L'\\'));
            tmpdir += L"\\downloads";
            if(tmpdir.GetAt(0)==GetSystemDrive())
                vDirs.push_back(tmpdir);
        }

    }
    else
    {
        bRet = SHGetSpecialFolderPath(NULL, szAppDataPath, CSIDL_PERSONAL, FALSE);
        if(bRet)
        {
            wcscat(szAppDataPath,L"\\下载");
            if(szAppDataPath[0]==GetSystemDrive())
                vDirs.push_back(szAppDataPath);
        }
    }

    bRet = SHGetSpecialFolderPath(NULL, szPath, CSIDL_APPDATA, FALSE);
    szPathFull = szPath;
    szPathFullEx = szPath;
    szPathFullEx += _T("\\Mozilla\\Firefox");
    szPathFull += _T("\\Mozilla\\Firefox\\profiles.ini");

    WCHAR szRecord[MAX_PATH] = {0};
    std::vector<std::wstring> vLogCache;
    std::vector<std::wstring>::iterator itor;

    GetPrivateProfileString(L"Profile0", L"Path", NULL, szRecord, MAX_PATH - 1, szPathFull);

    szPathFullEx += L"\\";
    szPathFullEx += szRecord;

    szPathFullEx += L"\\prefs.js";

    const WCHAR* Point = NULL;
    HRESULT hrRet = E_FAIL;
    std::vector<std::wstring> vcStrline;
    BYTE* pBuf = NULL;
    FILE* pFile = NULL;
    DWORD dwRealReadSize = 0;

    DWORD dwFileSize  = _DoGetFileSizeByFileName(szPathFullEx);
    if (dwFileSize <= 0)
    {
        hrRet = E_FAIL;
        goto _Exit;
    }

    pBuf = new BYTE[dwFileSize * 2 + 2];
    if (!pBuf)
    {
        hrRet = E_OUTOFMEMORY;
        goto _Exit;
    }

    ::ZeroMemory(pBuf, dwFileSize * 2 + 2);

    pFile = ::_wfopen(szPathFullEx, L"rt,ccs=UTF-8");
    if (!pFile)
    {
        hrRet = E_FAIL;
        goto _Exit;
    }

    dwRealReadSize = (DWORD)::fread(pBuf, sizeof(WCHAR), dwFileSize, pFile);
    if (dwRealReadSize == 0)
    {
        hrRet = E_FAIL;
        goto _Exit;
    }

    WCHAR* pszInfo = (WCHAR*)pBuf;

    DWORD dwLineCount = _DoGetLineByBuf(pszInfo, (DWORD)::wcslen(pszInfo), vLogCache);

    for (itor = vLogCache.begin(); itor != vLogCache.end(); itor++)
    {
        szTarget = (*itor).c_str();
        nPos = szTarget.Find(L"browser.download.dir");
        if (nPos != -1)
        {
            nPos = szTarget.Find(L",");
            szTarget = szTarget.Right(szTarget.GetLength() - nPos - 3);
            nPos = szTarget.Find(L"\"");
            szTarget = szTarget.Left(nPos);
            break;
        }
    }
    if (_wcsicmp(szTarget, L"") == 0)
    {
        return FALSE;
    }

    for (int nIndex=0; nIndex<szTarget.GetLength();)
    {
        if(szTarget.GetAt(nIndex)==L'\\'&&szTarget.GetAt(nIndex+1)==L'\\')
        {
            strPath += L"\\";
            nIndex += 2;
        }
        else
        {
            strPath += szTarget.GetAt(nIndex);
            nIndex++;
        }

    }
    if(strPath.GetAt(0)==GetSystemDrive()||strPath[0]==GetSystemDrive()-32||strPath[0]==GetSystemDrive()+32)
        vDirs.push_back(strPath);
    else goto _Exit;
    hrRet = S_OK;

_Exit:

    if (pBuf)
    {
        delete []pBuf;
        pBuf = NULL;
    }
    if (pFile)
    {
        fclose(pFile);
        pFile = NULL;
    }
    return TRUE;
}
Example #17
0
bool mitk::SceneIO::SaveScene( DataStorage::SetOfObjects::ConstPointer sceneNodes, const DataStorage* storage,
                                           const std::string& filename)
{
  if (!sceneNodes)
  {
    MITK_ERROR << "No set of nodes given. Not possible to save scene.";
    return false;
  }
  if (!storage)
  {
    MITK_ERROR << "No data storage given. Not possible to save scene.";  // \TODO: Technically, it would be possible to save the nodes without their relation
    return false;
  }

  if ( filename.empty() )
  {
    MITK_ERROR << "No filename given. Not possible to save scene.";
    return false;
  }

  try
  {

    m_FailedNodes = DataStorage::SetOfObjects::New();
    m_FailedProperties = PropertyList::New();

    // start XML DOM
    TiXmlDocument document;
    TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "UTF-8", "" ); // TODO what to write here? encoding? standalone would mean that we provide a DTD somewhere...
    document.LinkEndChild( decl );

    TiXmlElement* version = new TiXmlElement("Version");
    version->SetAttribute("Writer",  __FILE__ );
    version->SetAttribute("Revision",  "$Revision: 17055 $" );
    version->SetAttribute("FileVersion",  1 );
    document.LinkEndChild(version);

    //DataStorage::SetOfObjects::ConstPointer sceneNodes = storage->GetSubset( predicate );

    if ( sceneNodes.IsNull() )
    {
      MITK_WARN << "Saving empty scene to " << filename;
    }
    else
    {
      if ( sceneNodes->size() == 0 )
      {
        MITK_WARN << "Saving empty scene to " << filename;
      }

    MITK_INFO << "Storing scene with " << sceneNodes->size() << " objects to " << filename;

      m_WorkingDirectory = CreateEmptyTempDirectory();
      if (m_WorkingDirectory.empty())
      {
        MITK_ERROR << "Could not create temporary directory. Cannot create scene files.";
        return false;
      }

      ProgressBar::GetInstance()->AddStepsToDo( sceneNodes->size() );

      // find out about dependencies
      typedef std::map< DataNode*, std::string > UIDMapType;
      typedef std::map< DataNode*, std::list<std::string> > SourcesMapType;

      UIDMapType nodeUIDs;              // for dependencies: ID of each node
      SourcesMapType sourceUIDs; // for dependencies: IDs of a node's parent nodes

      UIDGenerator nodeUIDGen("OBJECT_");

      for (DataStorage::SetOfObjects::const_iterator iter = sceneNodes->begin();
           iter != sceneNodes->end();
           ++iter)
      {
        DataNode* node = iter->GetPointer();
        if (!node)
          continue; // unlikely event that we get a NULL pointer as an object for saving. just ignore

        // generate UIDs for all source objects
        DataStorage::SetOfObjects::ConstPointer sourceObjects = storage->GetSources( node );
        for ( mitk::DataStorage::SetOfObjects::const_iterator sourceIter = sourceObjects->begin();
              sourceIter != sourceObjects->end();
              ++sourceIter )
        {
          if ( std::find( sceneNodes->begin(), sceneNodes->end(), *sourceIter ) == sceneNodes->end() )
            continue; // source is not saved, so don't generate a UID for this source

          // create a uid for the parent object
          if ( nodeUIDs[ *sourceIter ].empty() )
          {
            nodeUIDs[ *sourceIter ] = nodeUIDGen.GetUID();
          }

          // store this dependency for writing
          sourceUIDs[ node ].push_back( nodeUIDs[*sourceIter] );
        }

        if ( nodeUIDs[ node ].empty() )
        {
          nodeUIDs[ node ] = nodeUIDGen.GetUID();
        }
      }

      // write out objects, dependencies and properties
      for (DataStorage::SetOfObjects::const_iterator iter = sceneNodes->begin();
           iter != sceneNodes->end();
           ++iter)
      {
        DataNode* node = iter->GetPointer();

        if (node)
        {
          TiXmlElement* nodeElement = new TiXmlElement("node");
          std::string filenameHint( node->GetName() );
          filenameHint = itksys::SystemTools::MakeCindentifier(filenameHint.c_str()); // escape filename <-- only allow [A-Za-z0-9_], replace everything else with _

          // store dependencies
          UIDMapType::iterator searchUIDIter = nodeUIDs.find(node);
          if ( searchUIDIter != nodeUIDs.end() )
          {
            // store this node's ID
            nodeElement->SetAttribute("UID", searchUIDIter->second.c_str() );
          }

          SourcesMapType::iterator searchSourcesIter = sourceUIDs.find(node);
          if ( searchSourcesIter != sourceUIDs.end() )
          {
            // store all source IDs
            for ( std::list<std::string>::iterator sourceUIDIter = searchSourcesIter->second.begin();
                  sourceUIDIter != searchSourcesIter->second.end();
                  ++sourceUIDIter )
            {
              TiXmlElement* uidElement = new TiXmlElement("source");
              uidElement->SetAttribute("UID", sourceUIDIter->c_str() );
              nodeElement->LinkEndChild( uidElement );
            }
          }

          // store basedata
          if ( BaseData* data = node->GetData() )
          {
            //std::string filenameHint( node->GetName() );
            bool error(false);
            TiXmlElement* dataElement( SaveBaseData( data, filenameHint, error ) ); // returns a reference to a file
            if (error)
            {
              m_FailedNodes->push_back( node );
            }

            // store basedata properties
            PropertyList* propertyList = data->GetPropertyList();
            if (propertyList && !propertyList->IsEmpty() )
            {
              TiXmlElement* baseDataPropertiesElement( SavePropertyList( propertyList, filenameHint + "-data") ); // returns a reference to a file
              dataElement->LinkEndChild( baseDataPropertiesElement );
            }

            nodeElement->LinkEndChild( dataElement );
          }

          // store all renderwindow specific propertylists
          const RenderingManager::RenderWindowVector& allRenderWindows( RenderingManager::GetInstance()->GetAllRegisteredRenderWindows() );
          for ( RenderingManager::RenderWindowVector::const_iterator rw = allRenderWindows.begin();
                rw != allRenderWindows.end();
                ++rw)
          {
            if (vtkRenderWindow* renderWindow = *rw)
            {
              std::string renderWindowName( mitk::BaseRenderer::GetInstance(renderWindow)->GetName() );
              BaseRenderer* renderer = mitk::BaseRenderer::GetInstance(renderWindow);
              PropertyList* propertyList = node->GetPropertyList(renderer);
              if ( propertyList && !propertyList->IsEmpty() )
              {
                TiXmlElement* renderWindowPropertiesElement( SavePropertyList( propertyList, filenameHint + "-" + renderWindowName) ); // returns a reference to a file
                renderWindowPropertiesElement->SetAttribute("renderwindow", renderWindowName);
                nodeElement->LinkEndChild( renderWindowPropertiesElement );
              }
            }
          }

          // don't forget the renderwindow independent list
          PropertyList* propertyList = node->GetPropertyList();
          if ( propertyList && !propertyList->IsEmpty() )
          {
            TiXmlElement* propertiesElement( SavePropertyList( propertyList, filenameHint + "-node") ); // returns a reference to a file
            nodeElement->LinkEndChild( propertiesElement );
          }
          document.LinkEndChild( nodeElement );
        }
        else
        {
          MITK_WARN << "Ignoring NULL node during scene serialization.";
        }

        ProgressBar::GetInstance()->Progress();
      } // end for all nodes

    } // end if sceneNodes

    if ( !document.SaveFile( m_WorkingDirectory + Poco::Path::separator() + "index.xml" ) )
    {
      MITK_ERROR << "Could not write scene to " << m_WorkingDirectory << Poco::Path::separator() << "index.xml" << "\nTinyXML reports '" << document.ErrorDesc() << "'";
      return false;
    }
    else
    {
      try
      {
        Poco::File deleteFile( filename.c_str() );
        if (deleteFile.exists())
        {
          deleteFile.remove();
        }

        // create zip at filename
        std::ofstream file( filename.c_str(), std::ios::binary | std::ios::out);
        if (!file.good())
        {
          MITK_ERROR << "Could not open a zip file for writing: '" << filename << "'";
        }
        else
        {
          Poco::Zip::Compress zipper( file, true );
          Poco::Path tmpdir( m_WorkingDirectory );
          zipper.addRecursive( tmpdir );
          zipper.close();
        }
        try
        {
          Poco::File deleteDir( m_WorkingDirectory );
          deleteDir.remove(true); // recursive
        }
        catch(...)
        {
          MITK_ERROR << "Could not delete temporary directory " << m_WorkingDirectory;
          return false; // ok?
        }
      }
      catch(std::exception& e)
      {
        MITK_ERROR << "Could not create ZIP file from " << m_WorkingDirectory << "\nReason: " << e.what();
        return false;
      }
      return true;
    }
  }
  catch(std::exception& e)
  {
    MITK_ERROR << "Caught exception during saving temporary files to disk. Error description: '" << e.what() << "'";
    return false;
  }
}