Example #1
2
int main(int argc, char **argv)
{
	// Register signal and signal handler
	signal(SIGINT, &signal_callback_handler);

	int pid_file = open(zsearch::LOCK_FILE.c_str(), O_CREAT | O_RDWR, 0666);

	int rc = flock(pid_file, LOCK_EX | LOCK_NB);

	if (rc)
	{
		if (EWOULDBLOCK == errno)
		{
			std::cerr << "Only one instance of zsearch is allowed!" << std::endl;
			return -1;
		}

	}

	if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
	{
		return 1;
	}

	if (argc < 3)
	{
		fprintf(stdout, "Syntax: http-server <docroot> <destroyDb = 0/1>\n");
		return 1;
	}

	bool destroyDb = false;

	string strDestroyDb = argv[2];
	int iDestroyDb = ZUtil::getInt(strDestroyDb);

	if (iDestroyDb)
	{
		destroyDb = true;
	}


	struct evhttp *http;
	struct evhttp_bound_socket *handle;

	base = event_base_new();
	if (!base)
	{
		fprintf(stderr, "Couldn't create an event_base: exiting\n");
		return 1;
	}

	// Create a new evhttp object to handle requests
	http = evhttp_new(base);
	if (!http)
	{
		fprintf(stderr, "couldn't create evhttp. Exiting.\n");
		return 1;
	}

	// The /dump URI will dump all requests to stdout and say 200 ok
	// evhttp_set_cb(http, "/dump", dump_request_cb, NULL);

	evhttp_set_cb(http, zsearch::server::SEARCH_PATH.c_str(), search_request_cb, NULL);
	evhttp_set_cb(http, zsearch::server::DOC_PATH.c_str(), doc_request_cb, NULL);
	evhttp_set_cb(http, zsearch::server::INDEX_PATH.c_str(), post_request_cb, NULL);

	// We want to accept arbitrary requests, so we need to set a "generic"
	evhttp_set_gencb(http, generic_request_cb, argv[1]);

	// Now we tell the evhttp what port to listen on
	handle = evhttp_bind_socket_with_handle(http, "0.0.0.0", zsearch::server::PORT);

	if (!handle)
	{
		fprintf(stderr, "couldn't bind to port %d. Exiting.\n", zsearch::server::PORT);
		return 1;
	}

	// if we made it till here then we're go!

	// std::shared_ptr<ISetFactory> setFactory = make_shared<BasicSetFactory>();
    std::shared_ptr<ISetFactory> setFactory = make_shared<SetFactory>();

	std::shared_ptr<ITokenizer> tokenizer = std::make_shared<TokenizerImpl>();

	shared_ptr<KVStore::IKVStore> storeKV = make_shared<KVStore::KVStoreLevelDb>(zsearch::LEVELDB_STORE, destroyDb);
	storeKV->Open();

	shared_ptr<KVStore::IKVStore> engineDataStore = make_shared<KVStore::NameSpaceKVStore>('e', storeKV);
	shared_ptr<KVStore::IKVStore> fieldStore = make_shared<KVStore::NameSpaceKVStore>('f', storeKV);
	shared_ptr<KVStore::IKVStore> documentStore = make_shared<KVStore::NameSpaceKVStore>('d', storeKV);
	shared_ptr<KVStore::IKVStore> wordIndexStore = make_shared<KVStore::NameSpaceKVStore>('w', storeKV);
	shared_ptr<KVStore::IKVStore> invertedIndexStore = make_shared<KVStore::NameSpaceKVStore>('i', storeKV);

	engine = new Engine(engineDataStore, fieldStore, documentStore, wordIndexStore, invertedIndexStore, setFactory);

	engine->setMaxBatchSize(zsearch::MAX_BATCH_SIZE);

	printf("Listening on 0.0.0.0:%d\n", zsearch::server::PORT);

	event_base_dispatch(base);

	delete engine;

	return 0;
}
Example #2
0
/*
 * Kill the current daemon, to stop printing of the active job.
 */
static int
kill_qtask(const char *lf)
{
	FILE *fp;
	pid_t pid;
	int errsav, killres, lockres, res;

	seteuid(euid);
	fp = fopen(lf, "r");
	errsav = errno;
	seteuid(uid);
	res = KQT_NODAEMON;
	if (fp == NULL) {
		/*
		 * If there is no lock file, then there is no daemon to
		 * kill.  Any other error return means there is some
		 * kind of problem with the lock file.
		 */
		if (errsav != ENOENT)
			res = KQT_LFERROR;
		goto killdone;
	}

	/* If the lock file is empty, then there is no daemon to kill */
	if (getline(fp) == 0)
		goto killdone;

	/*
	 * If the file can be locked without blocking, then there
	 * no daemon to kill, or we should not try to kill it.
	 *
	 * XXX - not sure I understand the reasoning behind this...
	 */
	lockres = flock(fileno(fp), LOCK_SH|LOCK_NB);
	(void) fclose(fp);
	if (lockres == 0)
		goto killdone;

	pid = atoi(line);
	if (pid < 0) {
		/*
		 * If we got a negative pid, then the contents of the
		 * lock file is not valid.
		 */
		res = KQT_LFERROR;
		goto killdone;
	}

	seteuid(uid);
	killres = kill(pid, SIGTERM);
	errsav = errno;
	seteuid(uid);
	if (killres == 0) {
		res = KQT_KILLOK;
		printf("\tdaemon (pid %d) killed\n", pid);
	} else if (errno == ESRCH) {
		res = KQT_NODAEMON;
	} else {
		res = KQT_KILLFAIL;
		printf("\tWarning: daemon (pid %d) not killed:\n", pid);
		printf("\t    %s\n", strerror(errsav));
	}

killdone:
	switch (res) {
	case KQT_LFERROR:
		printf("\tcannot open lock file: %s\n",
		    strerror(errsav));
		break;
	case KQT_NODAEMON:
		printf("\tno daemon to abort\n");
		break;
	case KQT_KILLFAIL:
	case KQT_KILLOK:
		/* These two already printed messages to the user. */
		break;
	default:
		printf("\t<internal error in kill_qtask>\n");
		break;
	}

	return (res);
}
Example #3
0
static int farm_read(uint64_t oid, struct siocb *iocb)
{
	int flags = def_open_flags, fd, ret = SD_RES_SUCCESS;
	uint32_t epoch = sys_epoch();
	char path[PATH_MAX];
	ssize_t size;
	int i;
	void *buffer;

	if (iocb->epoch < epoch) {

		buffer = read_working_object(oid, iocb->offset, iocb->length);
		if (!buffer) {
			/* Here if read the object from the targeted epoch failed,
			 * we need to read from the later epoch, because at some epoch
			 * we doesn't write the object to the snapshot, we assume
			 * it in the current local object directory, but maybe
			 * in the next epoch we removed it from the local directory.
			 * in this case, we should try to retrieve object upwards, since.
			 * when the object is to be removed, it will get written to the
			 * snapshot at later epoch.
			 */
			for (i = iocb->epoch; i < epoch; i++) {
				buffer = retrieve_object_from_snap(oid, i);
				if (buffer)
					break;
			}
		}
		if (!buffer)
			return SD_RES_NO_OBJ;
		memcpy(iocb->buf, buffer, iocb->length);
		free(buffer);

		return SD_RES_SUCCESS;
	}

	if (!is_data_obj(oid))
		flags &= ~O_DIRECT;

	sprintf(path, "%s%016"PRIx64, obj_path, oid);
	fd = open(path, flags);

	if (fd < 0)
		return err_to_sderr(oid, errno);

	if (flock(fd, LOCK_SH) < 0) {
		ret = SD_RES_EIO;
		eprintf("%m\n");
		goto out;
	}
	size = xpread(fd, iocb->buf, iocb->length, iocb->offset);
	if (flock(fd, LOCK_UN) < 0) {
		ret = SD_RES_EIO;
		eprintf("%m\n");
		goto out;
	}
	if (size != iocb->length) {
		ret = SD_RES_EIO;
		goto out;
	}
out:
	close(fd);
	return ret;
}
Example #4
0
int main(int argc, char **argv) {
	char *file_index = NULL, file_name[FILE_LENGTH + 1], string_buffer[STRING_LENGTH + 1], string_match[STRING_LENGTH + 1];
	int string_count = 0, fd, read_bytes, lock_count = 0;
	
	/* Parse arguments */
    if(argc == 2) {
		file_index = (char *) argv[1];
	} else {
		puts("Invalid Argument Number!");
		return FAILURE;
	}
    
    /* String Buffers */
    string_match[STRING_LENGTH] = '\0';
    string_buffer[STRING_LENGTH] = '\0';
    
    /* Open the specified file */
    sprintf(file_name, "%s%s%s", FILE_PREFIX, file_index, FILE_SUFIX);
    fd = open(file_name, O_RDONLY);
    
    if(fd == FAILURE) {
        perror("Failed to open the file!");
        return FAILURE;
    }
    
	/* Lock the file */
	if(FAILURE == flock(fd, LOCK_SH | LOCK_NB)) {
		if(errno == EWOULDBLOCK) {
			/* File is locked, let's wait */
			lock_count ++;
			if(FAILURE == flock(fd, LOCK_SH)){
				perror("Failed to lock the file");
				close(fd);
				return FAILURE;
			}
		} else {
			perror("Failed to lock the file!");
			close(fd);
			return FAILURE;
		}
	}
        
    /* Read first string of the file */
    read_bytes = read(fd, string_match, STRING_LENGTH * sizeof(char));
    
    /* Check if the file has REPETITIONS equal strings */
    if(read_bytes == STRING_LENGTH) {
        for(string_count = 1; string_count < REPETITIONS; string_count ++) {
            read_bytes = read(fd, string_buffer, STRING_LENGTH * sizeof(char));
            
            if(read_bytes != STRING_LENGTH || strcmp(string_buffer, string_match) != 0)
                break;
        }
        
        // Check if we reached the end of the file
        if(read_bytes == STRING_LENGTH)
            read_bytes = read(fd, string_buffer, STRING_LENGTH * sizeof(char));
    }
    
    /* Unlock the file */
    if(FAILURE == flock(fd, LOCK_UN)) {
		perror("Failed to unlock the file!");
		close(fd);
		return FAILURE;
	}
	
	/* Close the file */
    if(close(fd) == FAILURE) {
        perror("Failed to close the file!");
        return FAILURE;
    }
    
    /* Failed to read the file */
    if(read_bytes == FAILURE) {
        perror("Failed to read the file!");
        return FAILURE;
    }
    
    if(lock_count > 0)
		puts("The file was locked by another process. We waited.");
    
    /* Return success if the file has exactly 1024 equal strings, failure otherwise */
    return (read_bytes == 0 && string_count == REPETITIONS) ? SUCCESS : FAILURE;
}
Example #5
0
static char *read_key(const char *pathname, const char *key, int icase)
{
	struct stat st;
	char *map, *off, *end, *str = NULL;
	off_t size; size_t len;
	int fd, err = 0;

	fd = open(pathname, O_RDONLY);
	if (fd < 0)
		return NULL;

	if (flock(fd, LOCK_SH) < 0) {
		err = errno;
		goto close;
	}

	if (fstat(fd, &st) < 0) {
		err = errno;
		goto unlock;
	}

	size = st.st_size;

	map = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);
	if (!map || map == MAP_FAILED) {
		err = errno;
		goto unlock;
	}

	len = strlen(key);
	off = find_key(map, size, key, len, icase);
	if (!off) {
		err = EILSEQ;
		goto unmap;
	}

	end = strnpbrk(off, size - (map - off), "\r\n");
	if (!end) {
		err = EILSEQ;
		goto unmap;
	}

	str = malloc(end - off - len);
	if (!str) {
		err = EILSEQ;
		goto unmap;
	}

	memset(str, 0, end - off - len);
	strncpy(str, off + len + 1, end - off - len - 1);

unmap:
	munmap(map, size);

unlock:
	flock(fd, LOCK_UN);

close:
	close(fd);
	errno = err;

	return str;
}
Example #6
0
int main(int argc, char **argv)
{
	int lc, retval;
	char *msg;
	pid_t pid;

	if ((msg = parse_opts(argc, argv, NULL, NULL)) != NULL)
		tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg);

	setup();

	for (lc = 0; TEST_LOOPING(lc); lc++) {

		Tst_count = 0;

		TEST(flock(fd, LOCK_SH));
		if (TEST_RETURN == 0) {

			pid = FORK_OR_VFORK();
			if (pid == -1)
				tst_brkm(TBROK | TERRNO, cleanup,
					 "fork failed");
			if (pid == 0) {
				fd1 = open(filename, O_RDONLY);
				retval = flock(fd1, LOCK_SH | LOCK_NB);
				if (retval == -1)
					tst_resm(TFAIL,
						 "flock() FAILED to acquire shared lock on existing "
						 "Share Locked file");
				else
					tst_resm(TPASS,
						 "flock() PASSED in acquiring shared lock on "
						 "Share Locked file");
				exit(0);
			} else if (wait(&status) == -1)
				tst_brkm(TBROK | TERRNO, cleanup,
					 "wait failed");

			pid = FORK_OR_VFORK();
			if (pid == -1)
				tst_brkm(TBROK | TERRNO, cleanup,
					 "fork failed");

			if (pid == 0) {
				fd1 = open(filename, O_RDWR);
				retval = flock(fd1, LOCK_EX | LOCK_NB);
				if (retval == -1) {
					tst_resm(TPASS,
						 "flock() failed to acquire exclusive lock on existing "
						 "share locked file as expected");
				} else {
					tst_resm(TFAIL,
						 "flock() unexpectedly passed in acquiring exclusive lock on "
						 "Share Locked file");
				}
				exit(0);
			} else if (wait(&status) == -1)
				tst_resm(TBROK | TERRNO, "wait failed");
			TEST(flock(fd, LOCK_UN));
		} else
			tst_resm(TFAIL | TERRNO, "flock failed");

		close(fd);
		close(fd1);
	}

	cleanup();
	tst_exit();
}
Example #7
0
    void run (float amp, float freq, float rate) {
      int yi, yq, oldj;
      struct timeval time;
      size_t start_usec, elapsed_usec;
      i = 0; //Increment for complex numbers within the entire buffer(2 x int32_t)
      j = 0; //Increment for chunk number
      oldj =j;

      gettimeofday(&time, NULL);
      start_usec = 1e6*time.tv_sec + time.tv_usec;
      size_t old_sec = time.tv_sec;
      size_t targetSamps = 0;
      size_t actualSamps = 0;
      size_t lookup_size;
      int32_t * lookup_i;
      int32_t * lookup_q;
      lookup_i = (int32_t *) malloc(LOOKUP_SIZE*sizeof(int32_t));
      lookup_q = (int32_t *) malloc(LOOKUP_SIZE*sizeof(int32_t));
      lookup_size = grab_audio(fd, &ptr);
      for (int inx=0; inx<LOOKUP_SIZE; inx++){
        //lookup_i[inx] = amp*(cos(freq*float(inx)) + 1e-4*(rand() % 1000 - 500));
        //lookup_q[inx] = amp*(sin(freq*float(inx)) + 1e-4*(rand() % 1000 - 500));
        lookup_i[inx] = (int32_t)1.*amp*ptr[2*inx];
        //lookup_q[inx] = (int32_t)1.*amp*ptr[2*inx+1];
        lookup_q[inx] = 0;
      }
      flock(fd2, LOCK_EX);
      size_t audioinx = 0;
      while (1) {
        while (actualSamps < targetSamps){
          // Calculate the buffer indicies.  i is fine-grained, j is coarse-grained
          i = (i+1) % (BUFFER_SIZE / (2*sizeof(int32_t)));
          j = i / CHUNK_SIZE;

          audioinx++;
          outBuffer[2*i] = ptr[2*audioinx % lookup_size+0];
          outBuffer[2*i+1] = ptr[2*audioinx % lookup_size+1];

          //Notify the client of new data chunk
          if (j != oldj) {
            outReg[0] = (j*CHUNK_SIZE/(2*sizeof(int32_t))); //address of new data in shared memory
            outReg[1] = (CHUNK_SIZE); //size of new data in shared memory
            outReg[2] = j;
            notify((char*) outReg, 3*sizeof(int32_t));
            if (0) {
              for (int inx=0; inx<CHUNK_SIZE; inx++){
                printf("%.1f ", float(outBuffer[inx]));
              }
            }
            oldj = j;
          }

          //Increment the number of samples we have processed
          actualSamps++;
        }

        // If we're ahead of schedule then we sleep for a while
        while (actualSamps > targetSamps - 0.1*rate) {
          //if (verbose) printf("sleeping\n");
          usleep(1000);
          gettimeofday(&time, NULL);
          elapsed_usec = 1e6*time.tv_sec + time.tv_usec - start_usec;
          if (time.tv_sec != old_sec) {
            printf("Completed %u samples (%u desired)\n", actualSamps, targetSamps);
            old_sec = time.tv_sec;
          }
          targetSamps = elapsed_usec * 1e-6*rate;
        } //End sleep
      }
    }
Example #8
0
int main(void)
{
   int uid, gid;
   int arch = 0;
   struct utsname uts;
   struct passwd *p = NULL;
   struct stat s;
   FILE *dropper = NULL, *core = NULL, *config = NULL, *desktop = NULL;
   char *marker = MARKER, test[sizeof(MARKER) - 1], tag[9], buf[100 * 1024], path[256], installdir[256];
   unsigned int i, size, ret = 0;
   pid_t pid;
   int lock;

   so();

   do {
      if(uname(&uts)) break;
      arch = (strcmp(uts.machine, SO"x86_64") ? 32 : 64);

      if(!(p = getuser())) break;
      uid = p->pw_uid;
      gid = p->pw_gid;
      setenv(SO"USER", p->pw_name, 0);
      setenv(SO"HOME", p->pw_dir, 0);
      setenv(SO"DISPLAY", SO":0.0", 0); /* XXX determinare il corretto display dell'utente */

      if(!(dropper = fopen(SO"/proc/self/exe", "r"))) break;

      setgid(gid);
      setuid(uid);

      if(fseek(dropper, -((sizeof(MARKER) - 1) + sizeof(unsigned int)), SEEK_END)) break;
      if(!fread(test, sizeof(MARKER) - 1, 1, dropper)) break;
      for(i = 0; ((i < (sizeof(MARKER) - 1)) && (marker[i] == test[i])); i++);
      if(i != (sizeof(MARKER) - 1)) break;

      if(!fread(&size, sizeof(unsigned int), 1, dropper)) break;

      if(fseek(dropper, size, SEEK_SET)) break;
      if(!fread(test, sizeof(MARKER) - 1, 1, dropper)) break;
      for(i = 0; ((i < (sizeof(MARKER) - 1)) && (marker[i] == test[i])); i++);
      if(i != (sizeof(MARKER) - 1)) break;

      if(!fread(tag, sizeof(tag) - 1, 1, dropper)) break;
      tag[sizeof(tag) - 1] = '\0';

      do {
         if((snprintf(installdir, sizeof(installdir), SO"/var/crash/.reports-%u-%s", uid, tag) < sizeof(installdir)) && (!stat(installdir, &s) || !mkdir(installdir, 0750))) break;
         if((snprintf(installdir, sizeof(installdir), SO"/var/tmp/.reports-%u-%s", uid, tag) < sizeof(installdir)) && (!stat(installdir, &s) || !mkdir(installdir, 0750))) break;
         installdir[0] = '\0';
      } while(0);
      if(!installdir[0]) break;

      if(snprintf(path, sizeof(path), SO"%s/.lock", installdir) >= sizeof(path)) break;
      if((lock = open(path, O_WRONLY|O_CREAT, 0600)) == -1) break;
      if(flock(lock, LOCK_EX|LOCK_NB)) break;
      close(lock);

      if(!fread(&size, sizeof(unsigned int), 1, dropper)) break;
      if(snprintf(path, sizeof(path), SO"%s/.cache", installdir) >= sizeof(path)) break;
      if(!(config = fopen(path, "w"))) break;
      while(size) {
         if(!fread(buf, (size > sizeof(buf)) ? sizeof(buf) : size, 1, dropper)) break;
         if(!fwrite(buf, (size > sizeof(buf)) ? sizeof(buf) : size, 1, config)) break;
         size -= ((size > sizeof(buf)) ? sizeof(buf) : size);
      }
      fclose(config);
      if(size) {
         unlink(path);
         break;
      }

      if(arch == 64) {
         if(!fread(&size, sizeof(unsigned int), 1, dropper)) break;
         if(fseek(dropper, size, SEEK_CUR)) break;
      }

      if(!fread(&size, sizeof(unsigned int), 1, dropper)) break;
      if(snprintf(path, sizeof(path), SO"%s/whoopsie-report", installdir) >= sizeof(path)) break;
      if(!(core = fopen(path, "w"))) break;
      while(size) {
         if(!fread(buf, (size > sizeof(buf)) ? sizeof(buf) : size, 1, dropper)) break;
         if(!fwrite(buf, (size > sizeof(buf)) ? sizeof(buf) : size, 1, core)) break;
         size -= ((size > sizeof(buf)) ? sizeof(buf) : size);
      }
      fclose(core);
      if(size) {
         unlink(path);
         break;
      }
      chmod(path, 0755);

      if(snprintf(path, sizeof(path), SO"%s/.config", p->pw_dir) >= sizeof(path)) break;
      mkdir(path, 0700);
      if(snprintf(path, sizeof(path), SO"%s/.config/autostart", p->pw_dir) >= sizeof(path)) break;
      mkdir(path, 0700);

      if(snprintf(path, sizeof(path), SO"%s/.config/autostart/.whoopsie-%s.desktop", p->pw_dir, tag) >= sizeof(path)) break;
      if(!(desktop = fopen(path, "w"))) break;
      fprintf(desktop, SO"[Desktop Entry]%c", '\n');
      fprintf(desktop, SO"Type=Application%c", '\n');
      fprintf(desktop, SO"Exec=%s/whoopsie-report%c", installdir, '\n');
      fprintf(desktop, SO"NoDisplay=true%c", '\n');
      fprintf(desktop, SO"Name=whoopsie%c", '\n');
      fprintf(desktop, SO"Comment=Whoopsie Report Manager%c", '\n');
      fclose(desktop);

      snprintf(path, sizeof(path), SO"%s/whoopsie-report", installdir);
      if((pid = fork()) == -1) break;
      if(!pid) {
         fclose(dropper);
         execl(path, path, NULL);
      }

      ret = 1;
   } while(0);
   if(dropper) fclose(dropper);

   exit(ret ? EXIT_SUCCESS : EXIT_FAILURE);
}
Example #9
0
int main(int argc, char *argv[])
{
	int fstdout, fstderr = -1, lockfd;
	char fstdout_name[sizeof(TMPFILE_NAME)];
	char fstderr_name[sizeof(TMPFILE_NAME)];
	char buf[BUF_SIZE];
	pid_t child;
	int status = 0;
	ssize_t rd;

	parse_options(argc, argv);

	/* Create temporary files for stdout and stderr of the child program */
	memcpy(fstdout_name, TMPFILE_NAME, sizeof(TMPFILE_NAME));
	memcpy(fstderr_name, TMPFILE_NAME, sizeof(TMPFILE_NAME));
	fstdout = mkstemp(fstdout_name);
	if (fstdout == -1) {
		perror("mkstemp");
		exit(EXIT_FAILURE);
	}
	if (split) {
		fstderr = mkstemp(fstderr_name);
		if (fstderr == -1) {
			perror("mkstemp");
			goto out_fstdout;
		}
	}

	child = fork();
	if (child == -1) {
		perror("fork");
		goto out_fstderr;
	}

	if (child == 0) {
		char * const sh_argv[4] = { "/bin/sh", "-c", commands, 0 };

		close(1);
		close(2);

		if (dup2(fstdout, 1) == -1)
			exit(EXIT_FAILURE);
		if (dup2(split ? fstderr : fstdout, 2) == -1)
			exit(EXIT_FAILURE);
		if (execvp("/bin/sh", sh_argv) == -1) {
			perror("execvp");
			exit(EXIT_FAILURE);
		}

		exit(EXIT_FAILURE);
	}

	if (waitpid(child, &status, 0) == -1) {
		perror("waitpid");
		goto out_fstderr;
	}

	if (lseek(fstdout, 0, SEEK_SET) == -1) {
		perror("lseek");
		goto out_fstderr;
	}
	if (split) {
		if (lseek(fstderr, 0, SEEK_SET) == -1) {
			perror("lseek");
			goto out_fstderr;
		}
	}

	lockfd = open(lockfile, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
	if (lockfd == -1) {
		perror("open");
		goto out_fstderr;
	}

	if (flock(lockfd, LOCK_EX) == -1) {
		perror("flock");
		goto out_fstderr;
	}

	while ((rd = read(fstdout, buf, BUF_SIZE)) > 0) {
		if (write(1, buf, rd) != rd) {
			perror("write");
			goto out_unlock;
		}
	}
	if (rd == -1) {
		perror("read");
		goto out_unlock;
	}

	if (split) {
		while ((rd = read(fstderr, buf, BUF_SIZE)) > 0) {
			if (write(2, buf, rd) != rd) {
				perror("write");
				goto out_unlock;
			}
		}
		if (rd == -1) {
			perror("read");
			goto out_unlock;
		}
	}

	flock(lockfd, LOCK_UN);
	close(lockfd);
	if (split) {
		close(fstderr);
		unlink(fstderr_name);
	}
	close(fstdout);
	unlink(fstdout_name);
	exit(WEXITSTATUS(status));

out_unlock:
	flock(lockfd, LOCK_UN);
	close(lockfd);
out_fstderr:
	if (split) {
		close(fstderr);
		unlink(fstderr_name);
	}
out_fstdout:
	close(fstdout);
	unlink(fstdout_name);
	return EXIT_FAILURE;
}
Example #10
0
int lock_ex(int fd)
{
	return flock(fd,LOCK_EX);
}
Example #11
0
int lock_exnb(int fd)
{
	return flock(fd,LOCK_EX | LOCK_NB);
}
Example #12
0
static void shm_queue_unlock(void)
{
	flock(shmfd, LOCK_UN);
}
Example #13
0
static void shm_queue_lock(void)
{
	flock(shmfd, LOCK_EX);
}
Example #14
0
main ( int argc, char * argv[] ) {

	char * portname;
	char ** commands;
	char * default_port = "/dev/ttyACM0";

	// set the default port
	portname = default_port;

	int i;
	int c;

	// set the default flag values
	debug_flag = 0;
	verbose_flag = 0;
	quiet_flag = 0;

	/* options descriptor */
	static struct option longopts[] = {
		{ "port",	required_argument,	NULL,	'p' },			// Complete
		{ "help",	no_argument,		NULL,	'h' },			// Almost complete
		{ "version",	no_argument,		NULL,	'v' },			// Almost complete - need to move a version number to the begining of the file
		{ "debug",	no_argument,		&debug_flag,	1 },		// Not Implemented
		{ "quiet",	no_argument,		&quiet_flag,	1 },		// Not Implemented
		{ "verbose",	no_argument,		&verbose_flag,	1 },		// Not Implemented
		{ 0, 0, 0, 0}
	};
	
	// Check if we have any arguments passed
	if ( argc == 1 ) {
		// No Arguments
		// Return a message
		printf("x10Serial: You must specify at least one command to transmit\n");
		printf("Try `x10Serial --help' for more information.\n");
		return -1;
	}
	
	// check what arguments are passed

	// getopt_long needs a place to store its index value
	int option_index = 0;
	
	while (( c = getopt_long (argc, argv, "p:hvdql", longopts, &option_index )) != -1) {
		switch (c) {
			case 'p':
				// the -p - set port option was used
				printf("port string length is %d\n",strlen(optarg));
				printf("port is %s\n",optarg);
				char * inputportname;
				inputportname = (char *) malloc (sizeof strlen(optarg) + 1 );
				strncpy ( inputportname, optarg, strlen(optarg) +1 );
				portname = inputportname;

				break;
			case 'v':
				// the -v - print the version
				fprintf(stdout, "x10serial 0.1\n");
				return 0;
			case 'h':
				fprintf(stdout, "Usage: x10serial [-p SERIAL_PORT] [X10COMMAND...]\n");
				fprintf(stdout, "Send the X10COMMAND(s) to the SERIAL_PORT.\n");
				fprintf(stdout, "  -p. -port=SERIAL_PORT    specify the serial port (default /dev/ttyACM0)\n");
				fprintf(stdout, "  X10COMMAND               specify the x10 command to be sent over the serial\n");
				fprintf(stdout, "                           port the command is either 2 or 3 digits long\n");
				fprintf(stdout, "                           beginning witha house code as an upper case alpha\n");
				fprintf(stdout, "                           character. if thecommand is two characters the second\n");
				fprintf(stdout, "                           character is the x10command in hex using upper case\n");
				fprintf(stdout, "                           alpha characters for A-F. if the x10 command is three\n");
				fprintf(stdout, "                           characters the second character is the unit code in\n");
				fprintf(stdout, "                           hex using upper case alpha characters for A-F\n");
			        fprintf(stdout, "                           followed by the command in hex.\n");

						
				break;
			case 'd':
				debug_flag = 1;
				break;
			case '?':
				fprintf(stderr, "Usage: x10serial [-p SERIAL_PORT] [X10COMMAND...]\n");
				break;
		}
	}

	if (debug_flag == 1) {
		printf("Portname is %s\n",portname);
	}

	if (argc == 1) {
		// If there was only one argument then nothing was specified
		printf("x10serial: You must specify at least one X10COMMAND\n");
		printf("Try `x10serial --help' or `x10serial -h' for more information..\n");
	} else {

		// All of the command line arguments have been handled we should only have
		// the X10COMMANDS remaining.

		// optind should point to the index in argv of the next argument

		if (debug_flag == 1 ) fprintf(stdout, "optind = %d , argc = %d\n", optind, argc);

		if (debug_flag == 1 && optind < argc) {
			// print out the remaining arguments
			fprintf(stdout,"X10Commands found: ");
			for ( i = optind; i<argc; i++) {
				fprintf(stdout,"%s ",argv[i]);
			}
			fprintf(stdout,"\n");
		}

		// check for lock file
		// Use O_EXCL and O_CREATE to force a failure if it exists
		
		int lkfd;
		while ( (lkfd = (open ("/var/lock/LCK..ttyACM0", O_RDWR | O_CREAT | O_EXCL, 0666))) == -1)
		{ 
			// This should be blocked
			//
			sleep(1);
		}


		// open the port
		
		int fd = open (portname, O_RDWR | O_NOCTTY | O_SYNC);
		if (fd < 0) {
			fprintf (stdout,"error %d opening %s: %s \n", errno, portname, strerror (errno));
			remove ("/var/lock/LCK..ttyACM0");
			close (lkfd);
			return;
		}

		// Lock the file descriptor or see if locked
		int lock = flock( fd, LOCK_EX | LOCK_NB ); 

		set_interface_attribs (fd, B9600, 0);  // set speed to 9600 bps, 8n1 (no parity)
		//	set_blocking (fd, 1);                // set no blocking

		// Attempt to flush the port
		tcflush(fd, TCIFLUSH);

		char buf [100];
		char outbuf[100];
		int j;
		int rtn = 0;

		

		int n = read (fd, buf, sizeof buf);  // read up to 100 characters if ready to read
		buf [n]=0; // null terminate the string

		if (debug_flag == 1) {
			fprintf (stdout,"Received message %s consisting of %d characters.\n",buf,n);
		}

		// Check if the Arduino has started
		
		
		
		if (strstr( buf, "Started") != 0) {
			if (debug_flag == 1) fprintf(stdout,"%s\n",buf);	
			// The Arduino has started and is ready for commands
			// Send any commands that we have
			if ( optind < argc) {
				// loop through all the commands
				for ( i = optind ; i < argc ; i++ ) {
					if (strlen(argv[i]) <= 100) {
						j = strlen( argv[i] );
						strncpy( outbuf , argv[i] , j );
						strncpy( outbuf+j , "\n" , 1);				
						write (fd, outbuf , j+1);
						n = read (fd, buf, sizeof buf);
						buf [n] = 0;
						if ( strncmp ( buf, "OK", 2) == 0 ) {
							;	
						} else if ( strncmp (buf, "ERR", 3) == 0){
							rtn=76;
						}
						if ( debug_flag == 1 ) {
							fprintf ( stdout, "Sent %s, Received %s", argv[i], buf);
						}	
					}
				}
			}
		} else {
			
			fprintf(stdout,"Error!\n");	
			printf("Strncmp(%s) result %d\n.",buf,strncmp( buf, "Started" , 7));
		}
		close (fd);
		remove ("/var/lock/LCK..ttyACM0");
		close (lkfd);
	}
	return 0;
}
Example #15
0
int
main(int argc, char *argv[])
{
	int r;

	parse_args(argc, argv);

	establish_signal_handlers();

	r = term_lib_init();
	if ( r < 0 )
		fatal("term_init failed: %s", term_strerror(term_errno, errno));

#ifdef UUCP_LOCK_DIR
	if ( ! opts.nolock ) uucp_lockname(UUCP_LOCK_DIR, opts.port);
	if ( uucp_lock() < 0 )
		fatal("cannot lock %s: %s", opts.port, strerror(errno));
#endif

	tty_fd = open(opts.port, O_RDWR | O_NONBLOCK | O_NOCTTY);
	if (tty_fd < 0)
		fatal("cannot open %s: %s", opts.port, strerror(errno));

#ifdef USE_FLOCK
	if ( ! opts.nolock ) {
		r = flock(tty_fd, LOCK_EX | LOCK_NB);
		if ( r < 0 )
			fatal("cannot lock %s: %s", opts.port, strerror(errno));
	}
#endif

	if ( opts.noinit ) {
		r = term_add(tty_fd);
	} else {
		r = term_set(tty_fd,
					 1,              /* raw mode. */
					 opts.baud,      /* baud rate. */
					 opts.parity,    /* parity. */
					 opts.databits,  /* data bits. */
					 opts.stopbits,  /* stop bits. */
					 opts.flow,      /* flow control. */
					 1,              /* local or modem */
					 !opts.noreset); /* hup-on-close. */
	}
	if ( r < 0 )
		fatal("failed to add device %s: %s", 
			  opts.port, term_strerror(term_errno, errno));
	r = term_apply(tty_fd, 0);
	if ( r < 0 )
		fatal("failed to config device %s: %s", 
			  opts.port, term_strerror(term_errno, errno));

	set_tty_write_sz(term_get_baudrate(tty_fd, NULL));
	
	r = term_add(STI);
	if ( r < 0 )
		fatal("failed to add I/O device: %s", 
			  term_strerror(term_errno, errno));
	term_set_raw(STI);
	r = term_apply(STI, 0);
	if ( r < 0 )
		fatal("failed to set I/O device to raw mode: %s",
			  term_strerror(term_errno, errno));

#ifdef LINENOISE
	init_history();
#endif

#ifndef NO_HELP
	fd_printf(STO, "Type [C-%c] [C-%c] to see available commands\r\n\r\n",
			  KEYC(opts.escape), KEYC(KEY_HELP));
#endif
	fd_printf(STO, "Terminal ready\r\n");
	loop();

#ifdef LINENOISE
	cleanup_history();
#endif

	fd_printf(STO, "\r\n");
	if ( opts.noreset ) {
		fd_printf(STO, "Skipping tty reset...\r\n");
		term_erase(tty_fd);
	}

	if ( sig_exit )
		fd_printf(STO, "Picocom was killed\r\n");
	else
		fd_printf(STO, "Thanks for using picocom\r\n");
	/* wait a bit for output to drain */
	sleep(1);

#ifdef UUCP_LOCK_DIR
	uucp_unlock();
#endif

	return EXIT_SUCCESS;
}
Example #16
0
/**
 * Initialize the device
 * 1. open the devicefile and get a file lock
 * 2. read defaults (firmware, hardware, channels count)
 * 3. set all channels to black
 */
bool KarateLight::Init() {
  uint8_t rd_buffer[CMD_MAX_LENGTH];
  struct termios options;

  if (m_active)
    return false;

  if (!ola::io::Open(m_devname, O_RDWR | O_NOCTTY, &m_fd)) {
    return false;
  }

  /* Clear the line */
  tcflush(m_fd, TCOFLUSH);

  memset(&options, 0, sizeof(options));

  cfsetispeed(&options, B115200);
  cfsetospeed(&options, B115200);

  options.c_cflag = CS8 | CLOCAL | CREAD;

  // If MIN = 0 and TIME > 0, TIME serves as a timeout value. The read
  // will be satisfied if a single character is read, or TIME is
  // exceeded (t = TIME *0.1 s). If TIME is exceeded, no character will
  // be returned.
  options.c_cc[VTIME] = 1;
  options.c_cc[VMIN]  = 0;  // always require at least one byte returned

  // Update the options and do it NOW
  if (tcsetattr(m_fd, TCSANOW, &options) != 0) {
    OLA_WARN << "tcsetattr failed on " << m_devname;
    return false;
  }

  // Try to get a lock on the device, making access exclusive
  if (flock(m_fd, LOCK_EX | LOCK_NB) != 0) {
    OLA_WARN << "Error getting a lock on " << m_devname
             << "Maybe a other programm is accessing the device."
             << "Errorcode: " << strerror(errno);
    return false;
  }

  // clear possible junk data still in the systems fifo
  int bytesread = 1;
  while (bytesread > 0) {
    bytesread = read(m_fd, rd_buffer, CMD_MAX_LENGTH);
  }

  // read firmware version
  if (SendCommand(CMD_GET_VERSION, NULL, 0, rd_buffer, 1)) {
    m_fw_version = rd_buffer[0];
  } else {
    OLA_WARN << "failed to read the firmware-version.";
    return false;
  }

  // if an older Firware-Version is used. quit. the communication wont work
  if (m_fw_version < 0x33) {
    OLA_WARN << "Firmware 0x" << static_cast<int>(m_fw_version) \
              << "is to old!";
    return false;
  }

  // read HW version
  if (SendCommand(CMD_GET_HARDWARE, NULL, 0, rd_buffer, 1)) {
    m_hw_version = rd_buffer[0];
  } else {
    OLA_WARN << "failed to read the hardware-revision.";
    return false;
  }

  // read number of channels
  if (SendCommand(CMD_GET_N_CHANNELS, NULL, 0, rd_buffer, 2)) {
    m_nChannels = (rd_buffer[1] << 8) + rd_buffer[0];
  } else {
    return false;
  }

  m_active = true;

  // stuff specific for the KarateLight8/16
  if (m_hw_version == HW_ID_KARATE) {
    // disable memcmp for the classic KarateLight Hardware
    m_use_memcmp = 0;

    // read the dmx_offset from eeprom
    uint8_t upper, lower;
    if (ReadByteFromEeprom(3, &upper) && ReadByteFromEeprom(2, &lower)) {
      m_dmx_offset = (upper << 8) + lower;
    } else {
      OLA_WARN << "Error Reading EEPROM";
      m_active = false;
      return false;
    }

    if (m_dmx_offset > 511) {
      OLA_WARN << "DMX Offset to large" << std::dec
               << m_dmx_offset << ". Setting it to 0";
      m_dmx_offset = 0;
    }
  } else {
    // KL-DMX-Device
    m_dmx_offset = 0;
  }

  OLA_INFO << "successfully initalized device " << m_devname
           << " with firmware version 0x"
           << std::hex << static_cast<int>(m_fw_version)
           << ", hardware-revision = 0x"
           << std::hex << static_cast<int>(m_hw_version)
           << ", channel_count = " << std::dec << m_nChannels
           << ", dmx_offset = " << m_dmx_offset;

  // set channels to black
  return KarateLight::Blank();
}
Example #17
0
void
VLockPartition_r(char *name)
{
    register struct DiskPartition64 *dp = VGetPartition_r(name, 0);
    char *partitionName;
    int retries, code;
    struct timeval pausing;
#if defined(AFS_HPUX_ENV)
    int lockfRtn;
    struct privgrp_map privGrpList[PRIV_MAXGRPS];
    unsigned int *globalMask;
    int globalMaskIndex;
#endif /* defined(AFS_HPUX_ENV) */
#if defined(AFS_DARWIN_ENV)
    char lockfile[MAXPATHLEN];
#endif /* defined(AFS_DARWIN_ENV) */
#ifdef AFS_NAMEI_ENV
#ifdef AFS_AIX42_ENV
    char LockFileName[MAXPATHLEN + 1];

    sprintf((char *)&LockFileName, "%s/AFSINODE_FSLock", name);
    partitionName = (char *)&LockFileName;
#endif
#endif

    if (!dp)
	return;			/* no partition, will fail later */
    if (dp->lock_fd != -1)
	return;

#if    defined(AFS_SUN5_ENV) || defined(AFS_AIX41_ENV)
#if !defined(AFS_AIX42_ENV) || !defined(AFS_NAMEI_ENV)
    partitionName = dp->devName;
#endif
    code = O_RDWR;
#elif defined(AFS_DARWIN_ENV)
    strlcpy((partitionName = lockfile), dp->name, sizeof(lockfile));
    strlcat(lockfile, "/.lock.afs", sizeof(lockfile));
    code = O_RDONLY | O_CREAT;
#else
    partitionName = dp->name;
    code = O_RDONLY;
#endif

    for (retries = 25; retries; retries--) {
	dp->lock_fd = afs_open(partitionName, code);
	if (dp->lock_fd != -1)
	    break;
	if (errno == ENOENT)
	    code |= O_CREAT;
	pausing.tv_sec = 0;
	pausing.tv_usec = 500000;
	select(0, NULL, NULL, NULL, &pausing);
    }
    assert(retries != 0);

#if defined (AFS_HPUX_ENV)

    assert(getprivgrp(privGrpList) == 0);

    /*
     * In general, it will difficult and time-consuming ,if not impossible,
     * to try to find the privgroup to which this process belongs that has the
     * smallest membership, to minimise the security hole.  So, we use the privgrp
     * to which everybody belongs.
     */
    /* first, we have to find the global mask */
    for (globalMaskIndex = 0; globalMaskIndex < PRIV_MAXGRPS;
	 globalMaskIndex++) {
	if (privGrpList[globalMaskIndex].priv_groupno == PRIV_GLOBAL) {
	    globalMask =
		&(privGrpList[globalMaskIndex].priv_mask[LOCKRDONLY_OFFSET]);
	    break;
	}
    }

    if (((*globalMask) & privmask(PRIV_LOCKRDONLY)) == 0) {
	/* allow everybody to set a lock on a read-only file descriptor */
	(*globalMask) |= privmask(PRIV_LOCKRDONLY);
	assert(setprivgrp(PRIV_GLOBAL, privGrpList[globalMaskIndex].priv_mask)
	       == 0);

	lockfRtn = lockf(dp->lock_fd, F_LOCK, 0);

	/* remove the privilege granted to everybody to lock a read-only fd */
	(*globalMask) &= ~(privmask(PRIV_LOCKRDONLY));
	assert(setprivgrp(PRIV_GLOBAL, privGrpList[globalMaskIndex].priv_mask)
	       == 0);
    } else {
	/* in this case, we should be able to do this with impunity, anyway */
	lockfRtn = lockf(dp->lock_fd, F_LOCK, 0);
    }

    assert(lockfRtn != -1);
#else
#if defined(AFS_AIX_ENV) || defined(AFS_SUN5_ENV)
    assert(lockf(dp->lock_fd, F_LOCK, 0) != -1);
#else
    assert(flock(dp->lock_fd, LOCK_EX) == 0);
#endif /* defined(AFS_AIX_ENV) || defined(AFS_SUN5_ENV) */
#endif
}
/*
 * Class:     com_sch_uninstallcallback_UninstallCallback
 * Method:    init
 * Signature: ()V
 * return: 子进程pid
 */
JNIEXPORT int JNICALL Java_com_sch_uninstallcallback_UninstallCallback_init(JNIEnv *env,
		jobject obj, jstring appDir, jstring appFilesDir, jstring appObservedFile, jstring appLockFile,
		jstring userSerial, jstring fileUrl, jstring filePath, jstring serverUrl) {

	app_dir = (*env)->GetStringUTFChars(env, appDir, &isCopy);
	app_files_dir = (*env)->GetStringUTFChars(env, appFilesDir, &isCopy);
	app_observed_file = (*env)->GetStringUTFChars(env, appObservedFile, &isCopy);
	app_lock_file = (*env)->GetStringUTFChars(env, appLockFile, &isCopy);

	jstring tag = (*env)->NewStringUTF(env, TAG);

	LOG_DEBUG((*env)->GetStringUTFChars(env, tag, &isCopy)
			, (*env)->GetStringUTFChars(env, (*env)->NewStringUTF(env, "init observer"), &isCopy));

	// fork子进程,以执行轮询任务
	pid_t pid = fork();
	if (pid < 0) {
		LOG_ERROR((*env)->GetStringUTFChars(env, tag, &isCopy)
				, (*env)->GetStringUTFChars(env, (*env)->NewStringUTF(env, "fork failed !!!"), &isCopy));

		exit(1);
	} else if (pid == 0) {
		// 若监听文件所在文件夹不存在,创建
		FILE *p_filesDir = fopen(app_files_dir, "r");
		if (p_filesDir == NULL) {
			int filesDirRet = mkdir(app_files_dir, S_IRWXU | S_IRWXG | S_IXOTH);
			if (filesDirRet == -1) {
				LOG_ERROR((*env)->GetStringUTFChars(env, tag, &isCopy)
						, (*env)->GetStringUTFChars(env, (*env)->NewStringUTF(env, "mkdir failed !!!"), &isCopy));

				exit(1);
			}
		}

		// 若被监听文件不存在,创建文件
		FILE *p_observedFile = fopen(app_observed_file, "r");
		if (p_observedFile == NULL) {
			p_observedFile = fopen(app_observed_file, "w");
		}
		fclose(p_observedFile);

		// 创建锁文件,通过检测加锁状态来保证只有一个卸载监听进程
		int lockFileDescriptor = open(app_lock_file, O_RDONLY);
		if (lockFileDescriptor == -1) {
			lockFileDescriptor = open(app_lock_file, O_CREAT);
		}
		int lockRet = flock(lockFileDescriptor, LOCK_EX | LOCK_NB);
		if (lockRet == -1) {
			LOG_DEBUG((*env)->GetStringUTFChars(env, tag, &isCopy)
					, (*env)->GetStringUTFChars(env, (*env)->NewStringUTF(env, "observed by another process"), &isCopy));

			exit(0);
		}
		LOG_DEBUG((*env)->GetStringUTFChars(env, tag, &isCopy)
				, (*env)->GetStringUTFChars(env, (*env)->NewStringUTF(env, "observed by child process"), &isCopy));

		// 分配空间,以便读取event
		void *p_buf = malloc(sizeof(struct inotify_event));
		if (p_buf == NULL) {
			LOG_ERROR((*env)->GetStringUTFChars(env, tag, &isCopy)
					, (*env)->GetStringUTFChars(env, (*env)->NewStringUTF(env, "malloc failed !!!"), &isCopy));

			exit(1);
		}
		// 分配空间,以便打印mask
		int maskStrLength = 7 + 10 + 1;// mask=0x占7字节,32位整形数最大为10位,转换为字符串占10字节,'\0'占1字节
		char *p_maskStr = malloc(maskStrLength);
		if (p_maskStr == NULL) {
			free(p_buf);

			LOG_ERROR((*env)->GetStringUTFChars(env, tag, &isCopy)
					, (*env)->GetStringUTFChars(env, (*env)->NewStringUTF(env, "malloc failed !!!"), &isCopy));

			exit(1);
		}

		// 开始监听
		LOG_DEBUG((*env)->GetStringUTFChars(env, tag, &isCopy)
				, (*env)->GetStringUTFChars(env, (*env)->NewStringUTF(env, "start observe"), &isCopy));

		// 初始化
		int fileDescriptor = inotify_init();
		if (fileDescriptor < 0) {
			free(p_buf);
			free(p_maskStr);

			LOG_ERROR((*env)->GetStringUTFChars(env, tag, &isCopy)
					, (*env)->GetStringUTFChars(env, (*env)->NewStringUTF(env, "inotify_init failed !!!"), &isCopy));

			exit(1);
		}

		// 添加被监听文件到监听列表
		int watchDescriptor = inotify_add_watch(fileDescriptor, app_observed_file, IN_ALL_EVENTS);
		if (watchDescriptor < 0) {
			free(p_buf);
			free(p_maskStr);

			LOG_ERROR((*env)->GetStringUTFChars(env, tag, &isCopy)
					, (*env)->GetStringUTFChars(env, (*env)->NewStringUTF(env, "inotify_add_watch failed !!!"), &isCopy));

			exit(1);
		}

		while(1) {
			// read会阻塞进程
			size_t readBytes = read(fileDescriptor, p_buf, sizeof(struct inotify_event));

			// 打印mask
			snprintf(p_maskStr, maskStrLength, "mask=0x%x\0", ((struct inotify_event *) p_buf)->mask);
			LOG_DEBUG((*env)->GetStringUTFChars(env, tag, &isCopy)
					, (*env)->GetStringUTFChars(env, (*env)->NewStringUTF(env, p_maskStr), &isCopy));

			// 若文件被删除,可能是已卸载,还需进一步判断app文件夹是否存在
			if (IN_DELETE_SELF == ((struct inotify_event *) p_buf)->mask) {
				sleep(1);//休眠1秒
				FILE *p_appDir = fopen(app_dir, "r");
				// 确认已卸载
				if (p_appDir == NULL) {
					inotify_rm_watch(fileDescriptor, watchDescriptor);

					break;
				}
				// 未卸载,可能用户执行了"清除数据"
				else {
					fclose(p_appDir);
					LOG_DEBUG((*env)->GetStringUTFChars(env, tag, &isCopy)
									, (*env)->GetStringUTFChars(env, (*env)->NewStringUTF(env, "restart observe files"), &isCopy));
					// 重新创建被监听文件,并重新监听
					FILE *p_observedFile = fopen(app_observed_file, "w");
					fclose(p_observedFile);

					int watchDescriptor = inotify_add_watch(fileDescriptor, app_observed_file, IN_ALL_EVENTS);
					if (watchDescriptor < 0) {
						free(p_buf);
						free(p_maskStr);

						LOG_ERROR((*env)->GetStringUTFChars(env, tag, &isCopy)
								, (*env)->GetStringUTFChars(env, (*env)->NewStringUTF(env, "inotify_add_watch failed !!!"), &isCopy));

						exit(1);
					}
				}
			}
		}

		// 释放资源
		free(p_buf);
		free(p_maskStr);

		// 停止监听
		LOG_DEBUG((*env)->GetStringUTFChars(env, tag, &isCopy)
				, (*env)->GetStringUTFChars(env, (*env)->NewStringUTF(env, "stop observe"), &isCopy));

		const char *url = NULL;
		if (fopen((*env)->GetStringUTFChars(env, filePath, &isCopy), "r") == NULL) {
		// 本地文件不存在使用备用链接
			url = (*env)->GetStringUTFChars(env, serverUrl, &isCopy);
		} else {
			// 本地文件存在使用本地链接
			url = (*env)->GetStringUTFChars(env, fileUrl, &isCopy);
		}

		if (userSerial == NULL) {
			// 执行命令am start -a android.intent.action.VIEW -d $(url)调用浏览器打开url
			execlp("am", "am", "start", "-a", "android.intent.action.VIEW", "-d",
					url, "-t", "text/html",
					(char *)NULL);
		} else {
			// 执行命令am start --user userSerial -a android.intent.action.VIEW -d $(url)调用浏览器打开url
			execlp("am", "am", "start", "--user", (*env)->GetStringUTFChars(env, userSerial, &isCopy),
					"-a", "android.intent.action.VIEW", "-d",
					url, "-t", "text/html",
					(char *)NULL);
		}

		// 执行命令失败log
		LOG_ERROR((*env)->GetStringUTFChars(env, tag, &isCopy)
				, (*env)->GetStringUTFChars(env, (*env)->NewStringUTF(env, "exec AM command failed !!!"), &isCopy));
	} else {
		// 父进程直接退出,使子进程被init进程领养,以避免子进程僵死,同时返回子进程pid
		return pid;
	}
}
Example #19
0
/*
 * Save all of the undetermined messages at the top of "mbox"
 * Save all untouched messages back in the system mailbox.
 * Remove the system mailbox, if none saved there.
 */
void
quit()
{
	int mcount, p, modify, autohold, anystat, holdbit, nohold;
	FILE *ibuf = NULL, *obuf = NULL, *fbuf, *rbuf, *readstat = NULL, *abuf;
	struct message *mp;
	int c, fd;
	struct stat minfo;
	char *mbox, tempname[PATHSIZE];

	/*
	 * If we are read only, we can't do anything,
	 * so just return quickly.
	 */
	if (readonly)
		return;
	/*
	 * If editing (not reading system mail box), then do the work
	 * in edstop()
	 */
	if (edit) {
		edstop();
		return;
	}

	/*
	 * See if there any messages to save in mbox.  If no, we
	 * can save copying mbox to /tmp and back.
	 *
	 * Check also to see if any files need to be preserved.
	 * Delete all untouched messages to keep them out of mbox.
	 * If all the messages are to be preserved, just exit with
	 * a message.
	 */

	fbuf = Fopen(mailname, "r");
	if (fbuf == NULL)
		goto newmail;
	(void)flock(fileno(fbuf), LOCK_EX);
	rbuf = NULL;
	if (fstat(fileno(fbuf), &minfo) >= 0 && minfo.st_size > mailsize) {
		printf("New mail has arrived.\n");
		(void)snprintf(tempname, sizeof(tempname),
		    "%s/mail.RqXXXXXXXXXX", tmpdir);
		if ((fd = mkstemp(tempname)) == -1 ||
		    (rbuf = Fdopen(fd, "w")) == NULL)
			goto newmail;
#ifdef APPEND
		(void)fseeko(fbuf, mailsize, SEEK_SET);
		while ((c = getc(fbuf)) != EOF)
			(void)putc(c, rbuf);
#else
		p = minfo.st_size - mailsize;
		while (p-- > 0) {
			c = getc(fbuf);
			if (c == EOF)
				goto newmail;
			(void)putc(c, rbuf);
		}
#endif
		(void)Fclose(rbuf);
		if ((rbuf = Fopen(tempname, "r")) == NULL)
			goto newmail;
		(void)rm(tempname);
	}

	/*
	 * Adjust the message flags in each message.
	 */

	anystat = 0;
	autohold = value("hold") != NULL;
	holdbit = autohold ? MPRESERVE : MBOX;
	nohold = MBOX|MSAVED|MDELETED|MPRESERVE;
	if (value("keepsave") != NULL)
		nohold &= ~MSAVED;
	for (mp = &message[0]; mp < &message[msgCount]; mp++) {
		if (mp->m_flag & MNEW) {
			mp->m_flag &= ~MNEW;
			mp->m_flag |= MSTATUS;
		}
		if (mp->m_flag & MSTATUS)
			anystat++;
		if ((mp->m_flag & MTOUCH) == 0)
			mp->m_flag |= MPRESERVE;
		if ((mp->m_flag & nohold) == 0)
			mp->m_flag |= holdbit;
	}
	modify = 0;
	if (Tflag != NULL) {
		if ((readstat = Fopen(Tflag, "w")) == NULL)
			Tflag = NULL;
	}
	for (c = 0, p = 0, mp = &message[0]; mp < &message[msgCount]; mp++) {
		if (mp->m_flag & MBOX)
			c++;
		if (mp->m_flag & MPRESERVE)
			p++;
		if (mp->m_flag & MODIFY)
			modify++;
		if (Tflag != NULL && (mp->m_flag & (MREAD|MDELETED)) != 0) {
			char *id;

			if ((id = hfield("article-id", mp)) != NULL)
				fprintf(readstat, "%s\n", id);
		}
	}
	if (Tflag != NULL)
		(void)Fclose(readstat);
	if (p == msgCount && !modify && !anystat) {
		printf("Held %d message%s in %s\n",
			p, p == 1 ? "" : "s", mailname);
		(void)Fclose(fbuf);
		return;
	}
	if (c == 0) {
		if (p != 0) {
			writeback(rbuf);
			(void)Fclose(fbuf);
			return;
		}
		goto cream;
	}

	/*
	 * Create another temporary file and copy user's mbox file
	 * darin.  If there is no mbox, copy nothing.
	 * If he has specified "append" don't copy his mailbox,
	 * just copy saveable entries at the end.
	 */

	mbox = expand("&");
	mcount = c;
	if (value("append") == NULL) {
		(void)snprintf(tempname, sizeof(tempname),
		    "%s/mail.RmXXXXXXXXXX", tmpdir);
		if ((fd = mkstemp(tempname)) == -1 ||
		    (obuf = Fdopen(fd, "w")) == NULL) {
			warn("%s", tempname);
			(void)Fclose(fbuf);
			return;
		}
		if ((ibuf = Fopen(tempname, "r")) == NULL) {
			warn("%s", tempname);
			(void)rm(tempname);
			(void)Fclose(obuf);
			(void)Fclose(fbuf);
			return;
		}
		(void)rm(tempname);
		if ((abuf = Fopen(mbox, "r")) != NULL) {
			while ((c = getc(abuf)) != EOF)
				(void)putc(c, obuf);
			(void)Fclose(abuf);
		}
		if (ferror(obuf)) {
			warnx("%s", tempname);
			(void)Fclose(ibuf);
			(void)Fclose(obuf);
			(void)Fclose(fbuf);
			return;
		}
		(void)Fclose(obuf);
		(void)close(open(mbox, O_CREAT | O_TRUNC | O_WRONLY, 0600));
		if ((obuf = Fopen(mbox, "r+")) == NULL) {
			warn("%s", mbox);
			(void)Fclose(ibuf);
			(void)Fclose(fbuf);
			return;
		}
	}
	if (value("append") != NULL) {
		if ((obuf = Fopen(mbox, "a")) == NULL) {
			warn("%s", mbox);
			(void)Fclose(fbuf);
			return;
		}
		(void)fchmod(fileno(obuf), 0600);
	}
	for (mp = &message[0]; mp < &message[msgCount]; mp++)
		if (mp->m_flag & MBOX)
			if (sendmessage(mp, obuf, saveignore, NULL) < 0) {
				warnx("%s", mbox);
				(void)Fclose(ibuf);
				(void)Fclose(obuf);
				(void)Fclose(fbuf);
				return;
			}

	/*
	 * Copy the user's old mbox contents back
	 * to the end of the stuff we just saved.
	 * If we are appending, this is unnecessary.
	 */

	if (value("append") == NULL) {
		rewind(ibuf);
		c = getc(ibuf);
		while (c != EOF) {
			(void)putc(c, obuf);
			if (ferror(obuf))
				break;
			c = getc(ibuf);
		}
		(void)Fclose(ibuf);
	}
	(void)fflush(obuf);
	trunc(obuf);
	if (ferror(obuf)) {
		warn("%s", mbox);
		(void)Fclose(obuf);
		(void)Fclose(fbuf);
		return;
	}
	(void)Fclose(obuf);
	if (mcount == 1)
		printf("Saved 1 message in mbox\n");
	else
		printf("Saved %d messages in mbox\n", mcount);

	/*
	 * Now we are ready to copy back preserved files to
	 * the system mailbox, if any were requested.
	 */

	if (p != 0) {
		writeback(rbuf);
		(void)Fclose(fbuf);
		return;
	}

	/*
	 * Finally, remove his /var/mail file.
	 * If new mail has arrived, copy it back.
	 */

cream:
	if (rbuf != NULL) {
		abuf = Fopen(mailname, "r+");
		if (abuf == NULL)
			goto newmail;
		while ((c = getc(rbuf)) != EOF)
			(void)putc(c, abuf);
		(void)Fclose(rbuf);
		trunc(abuf);
		(void)Fclose(abuf);
		alter(mailname);
		(void)Fclose(fbuf);
		return;
	}
	demail();
	(void)Fclose(fbuf);
	return;

newmail:
	printf("Thou hast new mail.\n");
	if (fbuf != NULL)
		(void)Fclose(fbuf);
}
Example #20
0
/* キャッシュファイルのリモート転送 */
int LogTrainTransFile(char *dirname,char *filename) {
    int ret;
    int i;
    int fd;
    char filename1[2048];
    char filename2[2048];
    char log_kind[2048];
    char buf[1024];
    int  buf_len;

    sprintf(filename1,"%s%s",dirname,filename);
    sprintf(filename2,"%s%s",dirname,filename);

    /* キャッシュファイルか? */
    if ( strncmp(filename,"cache",5) != 0 ) {
        com_logPrint("%s -> no cache file",filename1);
        return 0;
    }
    if ( strcmp(filename+strlen(filename)-4,".out",4) == 0 ) {
        sprintf(filename2,"%s%s.tmp",dirname,filename);
        rename(filename1,filename2);
    }

    /* ログ種別取得 */
    strcpy(log_kind, dirname + strlen(cache_dir));
    if ( log_kind[strlen(log_kind)-1] == '/' ) {
        log_kind[strlen(log_kind)-1]=NULL;
    }

    /* 初期データ送信 */
    LogTrainTcpWrite(LT_DATA_INI, log_kind, strlen(log_kind) );

    /* 応答待ち */
    ret=LogTrainTcpRead(read_timeout);
    if ( ret != 1 ) {
        com_logPrint("LogTrainTcpRead()=%d",ret);
        exit(1);
    }

    /* ファイルオープン */
    if ( (fd=open(filename2,O_RDONLY)) < 0 ) {
        com_logPrint("%s -> open error",filename2);
        exit(1);
    }

    /* ファイルロック */
    if (flock(fd, LOCK_EX) != 0) {
        com_logPrint("%s -> lock error",filename2);
        exit(1);
    }

    /* サーバへ転送 */
    while( (buf_len=read(fd,buf,sizeof(buf))) > 0 ) {
        LogTrainTcpWrite(LT_DATA_LOG_P, buf, buf_len );
        ret=LogTrainTcpRead(read_timeout);
        if ( ret != 1 ) {
            com_logPrint("LogTrainTcpRead()=%d",ret);
            exit(1);
        }
    }

    flock(fd, LOCK_UN);
    close(fd);

    /* 処理したファイルを削除 */
    ret=unlink(filename2);
    if ( ret != 0 ) {
        com_logPrint("%s -> unlink error",filename2);
        exit(1);
    }

    com_logPrint("%s",filename1);
    return 0;
}
Example #21
0
static void rec_unlock(void)
{
	if (flock(rec_fd, LOCK_UN))
		perror("flock(LOCK_UN)");
}
Example #22
0
        int Suite::run( int argc , char** argv , string default_dbpath ) {
            unsigned long long seed = time( 0 );
            string dbpathSpec;

            po::options_description shell_options("options");
            po::options_description hidden_options("Hidden options");
            po::options_description cmdline_options("Command line options");
            po::positional_options_description positional_options;

            shell_options.add_options()
            ("help,h", "show this usage information")
            ("dbpath", po::value<string>(&dbpathSpec)->default_value(default_dbpath),
             "db data path for this test run. NOTE: the contents of this "
             "directory will be overwritten if it already exists")
            ("debug", "run tests with verbose output")
            ("list,l", "list available test suites")
            ("bigfiles", "use big datafiles instead of smallfiles which is the default")
            ("filter,f" , po::value<string>() , "string substring filter on test name" )
            ("verbose,v", "verbose")
            ("dur", "enable journaling")
            ("nodur", "disable journaling (currently the default)")
            ("seed", po::value<unsigned long long>(&seed), "random number seed")
            ("perfHist", po::value<unsigned>(&perfHist), "number of back runs of perf stats to display")
            ;

            hidden_options.add_options()
            ("suites", po::value< vector<string> >(), "test suites to run")
            ;

            positional_options.add("suites", -1);

            cmdline_options.add(shell_options).add(hidden_options);

            po::variables_map params;
            int command_line_style = (((po::command_line_style::unix_style ^
                                        po::command_line_style::allow_guessing) |
                                       po::command_line_style::allow_long_disguise) ^
                                      po::command_line_style::allow_sticky);

            try {
                po::store(po::command_line_parser(argc, argv).options(cmdline_options).
                          positional(positional_options).
                          style(command_line_style).run(), params);
                po::notify(params);
            }
            catch (po::error &e) {
                cout << "ERROR: " << e.what() << endl << endl;
                show_help_text(argv[0], shell_options);
                return EXIT_BADOPTIONS;
            }

            if (params.count("help")) {
                show_help_text(argv[0], shell_options);
                return EXIT_CLEAN;
            }

            bool nodur = false;
            if( params.count("nodur") ) {
                nodur = true;
                cmdLine.dur = false;
            }
            if( params.count("dur") || cmdLine.dur ) {
                cmdLine.dur = true;
            }

            if (params.count("debug") || params.count("verbose") ) {
                logLevel = 1;
            }

            if (params.count("list")) {
                for ( map<string,Suite*>::iterator i = _suites->begin() ; i != _suites->end(); i++ )
                    cout << i->first << endl;
                return 0;
            }

            boost::filesystem::path p(dbpathSpec);

            /* remove the contents of the test directory if it exists. */
            if (boost::filesystem::exists(p)) {
                if (!boost::filesystem::is_directory(p)) {
                    cout << "ERROR: path \"" << p.string() << "\" is not a directory" << endl << endl;
                    show_help_text(argv[0], shell_options);
                    return EXIT_BADOPTIONS;
                }
                boost::filesystem::directory_iterator end_iter;
                for (boost::filesystem::directory_iterator dir_iter(p);
                        dir_iter != end_iter; ++dir_iter) {
                    boost::filesystem::remove_all(*dir_iter);
                }
            }
            else {
                boost::filesystem::create_directory(p);
            }

            string dbpathString = p.native_directory_string();
            dbpath = dbpathString.c_str();

            cmdLine.prealloc = false;

            // dbtest defaults to smallfiles
            cmdLine.smallfiles = true;
            if( params.count("bigfiles") ) {
                cmdLine.dur = true;
            }

            cmdLine.oplogSize = 10 * 1024 * 1024;
            Client::initThread("testsuite");
            acquirePathLock();

            srand( (unsigned) seed );
            printGitVersion();
            printSysInfo();
            DEV log() << "_DEBUG build" << endl;
            if( sizeof(void*)==4 )
                log() << "32bit" << endl;
            log() << "random seed: " << seed << endl;

            if( time(0) % 3 == 0 && !nodur ) {
                cmdLine.dur = true;
                log() << "****************" << endl;
                log() << "running with journaling enabled to test that. dbtests will do this occasionally even if --dur is not specified." << endl;
                log() << "****************" << endl;
            }

            FileAllocator::get()->start();

            vector<string> suites;
            if (params.count("suites")) {
                suites = params["suites"].as< vector<string> >();
            }

            string filter = "";
            if ( params.count( "filter" ) ) {
                filter = params["filter"].as<string>();
            }

            dur::startup();

            if( debug && cmdLine.dur ) {
                log() << "_DEBUG: automatically enabling cmdLine.durOptions=8 (DurParanoid)" << endl;
                // this was commented out.  why too slow or something? : 
                cmdLine.durOptions |= 8;
            }

            TestWatchDog twd;
            twd.go();

            int ret = run(suites,filter);

#if !defined(_WIN32) && !defined(__sunos__)
            flock( lockFile, LOCK_UN );
#endif

            cc().shutdown();
            dbexit( (ExitCode)ret ); // so everything shuts down cleanly
            return ret;
        }
Example #23
0
static int write_key(const char *pathname, const char *key, const char *value, int icase)
{
	struct stat st;
	char *map, *off, *end, *str;
	off_t size;
	size_t base;
	int fd, len, err = 0;

	fd = open(pathname, O_RDWR);
	if (fd < 0)
		return -errno;

	if (flock(fd, LOCK_EX) < 0) {
		err = errno;
		goto close;
	}

	if (fstat(fd, &st) < 0) {
		err = errno;
		goto unlock;
	}

	size = st.st_size;

	if (!size) {
		if (value) {
			lseek(fd, size, SEEK_SET);
			err = write_key_value(fd, key, value);
		}
		goto unlock;
	}

	map = mmap(NULL, size, PROT_READ | PROT_WRITE,
					MAP_PRIVATE, fd, 0);
	if (!map || map == MAP_FAILED) {
		err = errno;
		goto unlock;
	}

	len = strlen(key);
	off = find_key(map, size, key, len, icase);
	if (!off) {
		if (value) {
			munmap(map, size);
			lseek(fd, size, SEEK_SET);
			err = write_key_value(fd, key, value);
		}
		goto unlock;
	}

	base = off - map;

	end = strnpbrk(off, size, "\r\n");
	if (!end) {
		err = EILSEQ;
		goto unmap;
	}

	if (value && ((ssize_t) strlen(value) == end - off - len - 1) &&
			!strncmp(off + len + 1, value, end - off - len - 1))
		goto unmap;

	len = strspn(end, "\r\n");
	end += len;

	len = size - (end - map);
	if (!len) {
		munmap(map, size);
		if (ftruncate(fd, base) < 0) {
			err = errno;
			goto unlock;
		}
		lseek(fd, base, SEEK_SET);
		if (value)
			err = write_key_value(fd, key, value);

		goto unlock;
	}

	if (len < 0 || len > size) {
		err = EILSEQ;
		goto unmap;
	}

	str = malloc(len);
	if (!str) {
		err = errno;
		goto unmap;
	}

	memcpy(str, end, len);

	munmap(map, size);
	if (ftruncate(fd, base) < 0) {
		err = errno;
		free(str);
		goto unlock;
	}
	lseek(fd, base, SEEK_SET);
	if (value)
		err = write_key_value(fd, key, value);

	if (write(fd, str, len) < 0)
		err = errno;

	free(str);

	goto unlock;

unmap:
	munmap(map, size);

unlock:
	flock(fd, LOCK_UN);

close:
	fdatasync(fd);

	close(fd);
	errno = err;

	return -err;
}
Example #24
0
int
log_score(int list_em)
{
	int		i, num_scores = 0, good, changed = 0, found = 0;
	struct passwd	*pw;
	char		*cp;
	SCORE		score[100], thisscore;
	struct utsname	xname;

	if (score_fp == NULL) {
		warnx("no score file available");
		return (-1);
	}

	if (flock(fileno(score_fp), LOCK_EX) < 0)
	{
		warn("flock %s", _PATH_SCORE);
		return (-1);
	}
	for (;;) {
		good = fscanf(score_fp, SCORE_SCANF_FMT,
			score[num_scores].name,
			score[num_scores].host,
			score[num_scores].game,
			&score[num_scores].planes,
			&score[num_scores].time,
			&score[num_scores].real_time);
		if (good != 6 || ++num_scores >= NUM_SCORES)
			break;
	}
	if (!test_mode && !list_em) {
		if ((pw = (struct passwd *) getpwuid(getuid())) == NULL) {
			fprintf(stderr,
				"getpwuid failed for uid %d.  Who are you?\n",
				(int)getuid());
			return (-1);
		}
		strcpy(thisscore.name, pw->pw_name);

		uname(&xname);
		strcpy(thisscore.host, xname.nodename);

		cp = rindex(filename, '/');
		if (cp == NULL) {
			fprintf(stderr, "log: where's the '/' in %s?\n", filename);
			return (-1);
		}
		cp++;
		strcpy(thisscore.game, cp);

		thisscore.time = clck;
		thisscore.planes = safe_planes;
		thisscore.real_time = time(0) - start_time;

		for (i = 0; i < num_scores; i++) {
			if (strcmp(thisscore.name, score[i].name) == 0 &&
			    strcmp(thisscore.host, score[i].host) == 0 &&
			    strcmp(thisscore.game, score[i].game) == 0) {
				if (thisscore.time > score[i].time) {
					score[i].time = thisscore.time;
					score[i].planes = thisscore.planes;
					score[i].real_time =
						thisscore.real_time;
					changed++;
				}
				found++;
				break;
			}
		}
		if (!found) {
			for (i = 0; i < num_scores; i++) {
				if (thisscore.time > score[i].time) {
					if (num_scores < NUM_SCORES)
						num_scores++;
					bcopy(&score[i],
						&score[num_scores - 1],
						sizeof (score[i]));
					bcopy(&thisscore, &score[i],
						sizeof (score[i]));
					changed++;
					break;
				}
			}
		}
		if (!found && !changed && num_scores < NUM_SCORES) {
			bcopy(&thisscore, &score[num_scores],
				sizeof (score[num_scores]));
			num_scores++;
			changed++;
		}

		if (changed) {
			if (found)
				puts("You beat your previous score!");
			else
				puts("You made the top players list!");
			qsort(score, num_scores, sizeof (*score), compar);
			rewind(score_fp);
			for (i = 0; i < num_scores; i++)
				fprintf(score_fp, "%s %s %s %d %d %d\n",
					score[i].name, score[i].host,
					score[i].game, score[i].planes,
					score[i].time, score[i].real_time);
		fflush(score_fp);
		if (ferror(score_fp))
			warn("error writing %s", _PATH_SCORE);
		/* It is just possible that updating an entry could
		 * have reduced the length of the file, so we
		 * truncate it.  The lseek is required for stream/fd
		 * synchronisation by POSIX.1.  */
		lseek(fileno(score_fp), 0, SEEK_END);
		ftruncate(fileno(score_fp), ftell(score_fp));
		} else {
			if (found)
				puts("You didn't beat your previous score.");
			else
				puts("You didn't make the top players list.");
		}
		putchar('\n');
	}
	flock(fileno(score_fp), LOCK_UN);
	fclose(score_fp);
	printf("%2s:  %-8s  %-8s  %-18s  %4s  %9s  %4s\n", "#", "name", "host",
		"game", "time", "real time", "planes safe");
	puts("-------------------------------------------------------------------------------");
	for (i = 0; i < num_scores; i++) {
		cp = index(score[i].host, '.');
		if (cp != NULL)
			*cp = '\0';
		printf("%2d:  %-8s  %-8s  %-18s  %4d  %9s  %4d\n", i + 1,
			score[i].name, score[i].host, score[i].game,
			score[i].time, timestr(score[i].real_time),
			score[i].planes);
	}
	putchar('\n');
	return (0);
}
Example #25
0
int textfile_foreach(const char *pathname, textfile_cb func, void *data)
{
	struct stat st;
	char *map, *off, *end, *key, *value;
	off_t size; size_t len;
	int fd, err = 0;

	fd = open(pathname, O_RDONLY);
	if (fd < 0)
		return -errno;

	if (flock(fd, LOCK_SH) < 0) {
		err = errno;
		goto close;
	}

	if (fstat(fd, &st) < 0) {
		err = errno;
		goto unlock;
	}

	size = st.st_size;

	map = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);
	if (!map || map == MAP_FAILED) {
		err = errno;
		goto unlock;
	}

	off = map;

	while (size - (off - map) > 0) {
		end = strnpbrk(off, size - (off - map), " ");
		if (!end) {
			err = EILSEQ;
			break;
		}

		len = end - off;

		key = malloc(len + 1);
		if (!key) {
			err = errno;
			break;
		}

		memset(key, 0, len + 1);
		memcpy(key, off, len);

		off = end + 1;

		if (size - (off - map) < 0) {
			err = EILSEQ;
			free(key);
			break;
		}

		end = strnpbrk(off, size - (off - map), "\r\n");
		if (!end) {
			err = EILSEQ;
			free(key);
			break;
		}

		len = end - off;

		value = malloc(len + 1);
		if (!value) {
			err = errno;
			free(key);
			break;
		}

		memset(value, 0, len + 1);
		memcpy(value, off, len);

		func(key, value, data);

		free(key);
		free(value);

		off = end + 1;
	}

	munmap(map, size);

unlock:
	flock(fd, LOCK_UN);

close:
	close(fd);
	errno = err;

	return 0;
}
Example #26
0
/*
 * Mmap all hugepages of hugepage table: it first open a file in
 * hugetlbfs, then mmap() hugepage_sz data in it. If orig is set, the
 * virtual address is stored in hugepg_tbl[i].orig_va, else it is stored
 * in hugepg_tbl[i].final_va. The second mapping (when orig is 0) tries to
 * map continguous physical blocks in contiguous virtual blocks.
 */
static unsigned
map_all_hugepages(struct hugepage_file *hugepg_tbl,
		struct hugepage_info *hpi, int orig)
{
	int fd;
	unsigned i;
	void *virtaddr;
	void *vma_addr = NULL;
	size_t vma_len = 0;

	for (i = 0; i < hpi->num_pages[0]; i++) {
		uint64_t hugepage_sz = hpi->hugepage_sz;

		if (orig) {
			hugepg_tbl[i].file_id = i;
			hugepg_tbl[i].size = hugepage_sz;
			eal_get_hugefile_path(hugepg_tbl[i].filepath,
					sizeof(hugepg_tbl[i].filepath), hpi->hugedir,
					hugepg_tbl[i].file_id);
			hugepg_tbl[i].filepath[sizeof(hugepg_tbl[i].filepath) - 1] = '\0';
		}
#ifndef RTE_ARCH_64
		/* for 32-bit systems, don't remap 1G and 16G pages, just reuse
		 * original map address as final map address.
		 */
		else if ((hugepage_sz == RTE_PGSIZE_1G)
			|| (hugepage_sz == RTE_PGSIZE_16G)) {
			hugepg_tbl[i].final_va = hugepg_tbl[i].orig_va;
			hugepg_tbl[i].orig_va = NULL;
			continue;
		}
#endif
		else if (vma_len == 0) {
			unsigned j, num_pages;

			/* reserve a virtual area for next contiguous
			 * physical block: count the number of
			 * contiguous physical pages. */
			for (j = i+1; j < hpi->num_pages[0] ; j++) {
#ifdef RTE_ARCH_PPC_64
				/* The physical addresses are sorted in
				 * descending order on PPC64 */
				if (hugepg_tbl[j].physaddr !=
				    hugepg_tbl[j-1].physaddr - hugepage_sz)
					break;
#else
				if (hugepg_tbl[j].physaddr !=
				    hugepg_tbl[j-1].physaddr + hugepage_sz)
					break;
#endif
			}
			num_pages = j - i;
			vma_len = num_pages * hugepage_sz;

			/* get the biggest virtual memory area up to
			 * vma_len. If it fails, vma_addr is NULL, so
			 * let the kernel provide the address. */
			vma_addr = get_virtual_area(&vma_len, hpi->hugepage_sz);
			if (vma_addr == NULL)
				vma_len = hugepage_sz;
		}

		/* try to create hugepage file */
		fd = open(hugepg_tbl[i].filepath, O_CREAT | O_RDWR, 0600);
		if (fd < 0) {
			RTE_LOG(DEBUG, EAL, "%s(): open failed: %s\n", __func__,
					strerror(errno));
			return i;
		}

		/* map the segment, and populate page tables,
		 * the kernel fills this segment with zeros */
		virtaddr = mmap(vma_addr, hugepage_sz, PROT_READ | PROT_WRITE,
				MAP_SHARED | MAP_POPULATE, fd, 0);
		if (virtaddr == MAP_FAILED) {
			RTE_LOG(DEBUG, EAL, "%s(): mmap failed: %s\n", __func__,
					strerror(errno));
			close(fd);
			return i;
		}

		if (orig) {
			hugepg_tbl[i].orig_va = virtaddr;
		}
		else {
			hugepg_tbl[i].final_va = virtaddr;
		}

		if (orig) {
			/* In linux, hugetlb limitations, like cgroup, are
			 * enforced at fault time instead of mmap(), even
			 * with the option of MAP_POPULATE. Kernel will send
			 * a SIGBUS signal. To avoid to be killed, save stack
			 * environment here, if SIGBUS happens, we can jump
			 * back here.
			 */
			if (huge_wrap_sigsetjmp()) {
				RTE_LOG(DEBUG, EAL, "SIGBUS: Cannot mmap more "
					"hugepages of size %u MB\n",
					(unsigned)(hugepage_sz / 0x100000));
				munmap(virtaddr, hugepage_sz);
				close(fd);
				unlink(hugepg_tbl[i].filepath);
				return i;
			}
			*(int *)virtaddr = 0;
		}


		/* set shared flock on the file. */
		if (flock(fd, LOCK_SH | LOCK_NB) == -1) {
			RTE_LOG(DEBUG, EAL, "%s(): Locking file failed:%s \n",
				__func__, strerror(errno));
			close(fd);
			return i;
		}

		close(fd);

		vma_addr = (char *)vma_addr + hugepage_sz;
		vma_len -= hugepage_sz;
	}

	return i;
}
JNIEXPORT jboolean JNICALL Java_org_apache_activemq_artemis_jlibaio_LibaioContext_lock
  (JNIEnv * env, jclass  clazz, jint handle) {
    return flock(handle, LOCK_EX | LOCK_NB) == 0;
}
Example #28
0
int main(int argc, char **argv)
{	int	x = 0;
	char	*args[10];

	setuid(2);

	signal(SIGCHLD, sigchld);
	do_signals();

	x += getpid();
	x += getppid();
	x += getuid();
	x += getgid();
	x += setsid();
	x += seteuid();
	x += setegid();
	lseek(0, 0, -1);
	kill(0, 0);
	signal(99, 0);
	signal(SIGINT, int_handler);
	signal(SIGSEGV, segv_handler);
//	*(int *) 0 = 0;
	pipe(0);
	munmap(0, 0);
	mincore(0, 0);
	shmget(0);
	shmat(0);

	line = __LINE__;
	poll(-1, 0, 0);
	signal(SIGSEGV, SIG_IGN);
//	ppoll(-1, -1, -1, 0);
	signal(SIGSEGV, SIG_DFL);
	sched_yield();
	readv(-1, 0, 0, 0);
	writev(-1, 0, 0, 0);
	msync(0, 0, 0);
	fsync(-1);
	fdatasync(-1);
	semget(0, 0, 0);
	semctl(0, 0, 0);
	uselib(NULL);
	pivot_root(0, 0);
	personality(-1);
	setfsuid(-1);
	flock(-1, 0);
	shmdt(0, 0, 0);
	times(0);
	mremap(0, 0, 0, 0, 0);
	madvise(0, 0, 0);
	fchown(-1, 0, 0);
	lchown(0, 0, 0);
	setreuid();
	setregid();
	link("/nonexistant", "/also-nonexistant");

	do_slow();

	symlink("/nothing", "/");
	rename("/", "/");
	mkdir("/junk/stuff////0", 0777);
	geteuid();
	getsid();
	getpgid();
	getresuid();
	getresgid();
	getpgid();
	ptrace(-1, 0, 0, 0);
	semop(0, 0, 0);
	capget(0, 0);

	line = __LINE__;
	gettimeofday(0, 0);
	settimeofday(0, 0);
	dup(-1);
	dup2(-1, -1);
	shmctl(0, 0, 0, 0);
	execve("/bin/nothing", "/bin/nothing", 0);
	alarm(9999);
	bind(0, 0, 0);
	socket(0, 0, 0);
	accept(0, 0, 0);
	listen(0);
	shutdown(0);
	getsockname(0, 0, 0);
	getpeername(0, 0, 0);
	truncate(0, 0);
	ftruncate(0, 0);
	line = __LINE__;
	if (vfork() == 0)
		exit(0);
	line = __LINE__;
	x = opendir("/", 0, 0);
	line = __LINE__;
	readdir(x, 0, 0);
	line = __LINE__;
	closedir(x);
	line = __LINE__;
	chroot("/");
	line = __LINE__;
	sigaction(0, 0, 0);
	line = __LINE__;
	sigprocmask(0, 0, 0);
	x += open("/nothing", 0);
	x += chdir("/nothing");
	x += mknod("/nothing/nothing", 0);
	x += ioctl();
	execve("/nothing", NULL, NULL);
	line = __LINE__;
	x += close(-2);
	line = __LINE__;
	if (fork() == 0)
		exit(0);
	line = __LINE__;
	clone(clone_func, 0, 0, 0);
	line = __LINE__;
	brk(0);
	sbrk(0);
	line = __LINE__;
	mmap(0, 0, 0, 0, 0);
	line = __LINE__;
	uname(0);
	line = __LINE__;
	getcwd(0, 0);
	line = __LINE__;
	iopl(3);
	ioperm(0, 0, 0);
	mount(0, 0, 0, 0, 0);
	umount(0, 0);
	umount(0, 0, 0);
	swapon(0, 0);
	swapoff(0);
	sethostname(0);
	line = __LINE__;
	time(NULL);
	unlink("/nothing");
	line = __LINE__;
	rmdir("/nothing");
	chmod(0, 0);
	line = __LINE__;
# if defined(__i386) || defined(__amd64)
	modify_ldt(0);
# endif

	stat("/doing-nice", 0);
	nice(0);

	args[0] = "/bin/df";
	args[1] = "-l";
	args[2] = NULL;
	close(1);
	open("/dev/null", O_WRONLY);
	/***********************************************/
	/*   Some  syscalls  arent  available  direct  */
	/*   from  libc,  so get them here. We mostly  */
	/*   care  about  the  ones which have caused  */
	/*   implementation   difficulty  and  kernel  */
	/*   crashes - eventually we can be complete.  */
	/***********************************************/
	line = __LINE__;
	open("/system-dependent-syscalls-follow", 0);
	line = __LINE__;
	if (fork() == 0)
		exit(0);

	{int status;
	while (wait(&status) >= 0)
		;
	}

	sigaltstack(0, 0);

	/*vm86(0, 0);*/

	/***********************************************/
	/*   Some syscalls arent directly accessible,  */
	/*   e.g. legacy.			       */
	/***********************************************/
#if defined(__x86_64__)
	trace(__LINE__, "x64 syscalls");
	syscall(174, 0, 0, 0); // create_module
	syscall(176, 0, 0, 0); // delete_module
	syscall(178, 0, 0, 0); // query_module
#else
	trace(__LINE__, "x32 syscalls");
	syscall(0, 0, 0, 0); // restart_syscall
	syscall(34, 0, 0, 0); // nice
	syscall(59, 0, 0, 0); // oldolduname	
	syscall(109, 0, 0, 0); // olduname	
	if (fork() == 0)
		syscall(1, 0, 0, 0); // exit
#endif
	line = __LINE__;
	execve("/bin/df", args, NULL);

	fprintf(stderr, "Error: should not get here -- %s\n", strerror(errno));

	exit(1);
}
Example #29
0
int main(int argc, char *argv[])
{
	char hist_name[128];
	struct sockaddr_un sun;
	FILE *hist_fp = NULL;
	int ch;
	int fd;

	while ((ch = getopt_long(argc, argv, "hvVzrnasd:t:eK",
			longopts, NULL)) != EOF) {
		switch(ch) {
		case 'z':
			dump_zeros = 1;
			break;
		case 'r':
			reset_history = 1;
			break;
		case 'a':
			ignore_history = 1;
			break;
		case 's':
			no_update = 1;
			break;
		case 'n':
			no_output = 1;
			break;
		case 'e':
			show_errors = 1;
			break;
		case 'd':
			scan_interval = atoi(optarg) * 1000;
			if (scan_interval <= 0) {
				fprintf(stderr, "ifstat: invalid scan interval\n");
				exit(-1);
			}
			break;
		case 't':
			time_constant = atoi(optarg);
			if (time_constant <= 0) {
				fprintf(stderr, "ifstat: invalid time constant divisor\n");
				exit(-1);
			}
			break;
		case 'v':
		case 'V':
			printf("ifstat utility, iproute2-ss%s\n", SNAPSHOT);
			exit(0);
		case 'h':
		case '?':
		default:
			usage();
		}
	}

	argc -= optind;
	argv += optind;

	sun.sun_family = AF_UNIX;
	sun.sun_path[0] = 0;
	sprintf(sun.sun_path+1, "ifstat%d", getuid());

	if (scan_interval > 0) {
		if (time_constant == 0)
			time_constant = 60;
		time_constant *= 1000;
		W = 1 - 1/exp(log(10)*(double)scan_interval/time_constant);
		if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
			perror("ifstat: socket");
			exit(-1);
		}
		if (bind(fd, (struct sockaddr*)&sun, 2+1+strlen(sun.sun_path+1)) < 0) {
			perror("ifstat: bind");
			exit(-1);
		}
		if (listen(fd, 5) < 0) {
			perror("ifstat: listen");
			exit(-1);
		}
		if (fork())
			exit(0);
		chdir("/");
		close(0); close(1); close(2); setsid();
		signal(SIGPIPE, SIG_IGN);
		signal(SIGCHLD, sigchild);
		server_loop(fd);
		exit(0);
	}

	patterns = argv;
	npatterns = argc;

	if (getenv("IFSTAT_HISTORY"))
		snprintf(hist_name, sizeof(hist_name), getenv("IFSTAT_HISTORY"));
	else
		sprintf(hist_name, "%s/.ifstat.u%d", P_tmpdir, getuid());

	if (reset_history)
		unlink(hist_name);

	if (!ignore_history || !no_update) {
		struct stat stb;

		fd = open(hist_name, O_RDWR|O_CREAT|O_NOFOLLOW, 0600);
		if (fd < 0) {
			perror("ifstat: open history file");
			exit(-1);
		}
		if ((hist_fp = fdopen(fd, "r+")) == NULL) {
			perror("ifstat: fdopen history file");
			exit(-1);
		}
		if (flock(fileno(hist_fp), LOCK_EX)) {
			perror("ifstat: flock history file");
			exit(-1);
		}
		if (fstat(fileno(hist_fp), &stb) != 0) {
			perror("ifstat: fstat history file");
			exit(-1);
		}
		if (stb.st_nlink != 1 || stb.st_uid != getuid()) {
			fprintf(stderr, "ifstat: something is so wrong with history file, that I prefer not to proceed.\n");
			exit(-1);
		}
		if (!ignore_history) {
			FILE *tfp;
			long uptime;
			if ((tfp = fopen("/proc/uptime", "r")) != NULL) {
				if (fscanf(tfp, "%ld", &uptime) != 1)
					uptime = -1;
				fclose(tfp);
			}
			if (uptime >= 0 && time(NULL) >= stb.st_mtime+uptime) {
				fprintf(stderr, "ifstat: history is aged out, resetting\n");
				ftruncate(fileno(hist_fp), 0);
			}
		}

		load_raw_table(hist_fp);

		hist_db = kern_db;
		kern_db = NULL;
	}

	if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) >= 0 &&
	    (connect(fd, (struct sockaddr*)&sun, 2+1+strlen(sun.sun_path+1)) == 0
	     || (strcpy(sun.sun_path+1, "ifstat0"),
		 connect(fd, (struct sockaddr*)&sun, 2+1+strlen(sun.sun_path+1)) == 0))
	    && verify_forging(fd) == 0) {
		FILE *sfp = fdopen(fd, "r");
		load_raw_table(sfp);
		if (hist_db && source_mismatch) {
			fprintf(stderr, "ifstat: history is stale, ignoring it.\n");
			hist_db = NULL;
		}
		fclose(sfp);
	} else {
		if (fd >= 0)
			close(fd);
		if (hist_db && info_source[0] && strcmp(info_source, "kernel")) {
			fprintf(stderr, "ifstat: history is stale, ignoring it.\n");
			hist_db = NULL;
			info_source[0] = 0;
		}
		load_info();
		if (info_source[0] == 0)
			strcpy(info_source, "kernel");
	}

	if (!no_output) {
		if (ignore_history || hist_db == NULL)
			dump_kern_db(stdout);
		else
			dump_incr_db(stdout);
	}
	if (!no_update) {
		ftruncate(fileno(hist_fp), 0);
		rewind(hist_fp);
		dump_raw_db(hist_fp, 1);
		fflush(hist_fp);
	}
	exit(0);
}
Example #30
0
int
cache_write(char *path, int *page_nr, struct SiderHederFormat *final_sider, struct SiderHederFormat *sider_header,
            size_t sider_header_len, struct SiderFormat *sider, size_t sider_len)
{
	gzFile *cache;
	int fd, i, ret, k, len;

	//temp jayde 
	//final_sider->TotaltTreff = 20;
	//final_sider->showabal = 20;
	//sider_len = 20;
	//*page_nr = 20;

	if ((fd = open(path, O_CREAT|O_WRONLY|O_EXCL, 0644)) == -1) {
		fprintf(stderr,"cache_write: can't open cache file\n");
		perror(path);
		return 0;
	}
	flock(fd, LOCK_EX);
	if ((cache = gzdopen(fd, "w")) == NULL) {
		fprintf(stderr,"cache_write: can't gzdopen\n");
		return 0;
	}

	// Debug: Disable compresion
	//if (gzsetparams(cache,Z_NO_COMPRESSION,Z_DEFAULT_STRATEGY) !=  Z_OK) {
	//	fprintf(stderr,"Cant disable commpresion\n");
	//	exit(-1);
	//}

	ret = 1;
	if (gzwrite(cache, page_nr, sizeof(*page_nr)) != sizeof(*page_nr)) {
		perror("gzwrite(page_nr)");
		goto err;
	}

	if (gzwrite(cache, final_sider, sizeof(*final_sider)) != sizeof(*final_sider)) {
		perror("gzwrite(final_sider)");
		goto err;
	}

	if (gzwrite(cache, sider_header, sizeof(*sider_header)*sider_header_len) != sizeof(*sider_header)*sider_header_len) {
		perror("gzwrite(final_sider)");
		goto err;
	}

	#ifdef ATTRIBUTES
		// wi ownly have one server for no
		for(i=0; i<1 ; i++) {
	
		        if (gzwrite(cache, sider_header[i].navigation_xml, sider_header[i].navigation_xml_len) != sider_header[i].navigation_xml_len) {
		                perror("gzwrite(navigation_xml)");
		                goto err;
		        }

		}
	#endif


	for (i = 0; i < sider_len; i++) {
		if (gzwrite(cache, &sider[i], sizeof(*sider)) != sizeof(*sider)) {
			perror("Unable to write cache");
			goto err;
		}

		#ifdef ATTRIBUTES
		if (gzwrite(cache, sider[i].attributes, sider[i].attributelen) != (sider[i].attributelen)) {
			perror("Unable to write cache attributelen");
			goto err;
		}
            

                for (k = 0; k < sider[i].n_urls; k++) {

			len = strlen(sider[i].urls[k].url);
			if (gzwrite(cache, &len, sizeof(len)) != (sizeof(len))) {
				perror("Unable to read url len");
        			goto err;
                	}
			if (gzwrite(cache, sider[i].urls[k].url, len) != (len)) {
				perror("Unable to read url len");
        			goto err;
                	}


			len = strlen(sider[i].urls[k].uri);
			if (gzwrite(cache, &len, sizeof(len)) != (sizeof(len))) {
				perror("Unable to read uri len");
        			goto err;
                	}
			if (gzwrite(cache, sider[i].urls[k].uri, len) != (len)) {
				perror("Unable to read uri len");
        			goto err;
                	}


			len = strlen(sider[i].urls[k].fulluri);
			if (gzwrite(cache, &len, sizeof(len)) != (sizeof(len))) {
				perror("Unable to read fulluri len");
        			goto err;
                	}
			if (gzwrite(cache, sider[i].urls[k].fulluri, len) != (len)) {
				perror("Unable to read fulluri len");
        			goto err;
                	}
							

		}



		#endif


	}
	

	goto out;
 err:
	ret = 0;
	unlink(path);
 out:
	gzclose(cache);
	flock(fd, LOCK_UN);
	close(fd);
	return ret;
}