Beispiel #1
0
static int
clustdiffer(cl_t cl, cl_t *cp1, cl_t *cp2, u_int fatnum)
{
	if (*cp1 == CLUST_FREE || *cp1 >= CLUST_RSRVD) {
		if (*cp2 == CLUST_FREE || *cp2 >= CLUST_RSRVD) {
			if ((*cp1 != CLUST_FREE && *cp1 < CLUST_BAD
			     && *cp2 != CLUST_FREE && *cp2 < CLUST_BAD)
			    || (*cp1 > CLUST_BAD && *cp2 > CLUST_BAD)) {
				pwarn("Cluster %u is marked %s with different indicators\n",
				      cl, rsrvdcltype(*cp1));
				if (ask(1, "Fix")) {
					*cp2 = *cp1;
					return FSFATMOD;
				}
				return FSFATAL;
			}
			pwarn("Cluster %u is marked %s in FAT 0, %s in FAT %u\n",
			      cl, rsrvdcltype(*cp1), rsrvdcltype(*cp2), fatnum);
			if (ask(0, "Use FAT 0's entry")) {
				*cp2 = *cp1;
				return FSFATMOD;
			}
			if (ask(0, "Use FAT %u's entry", fatnum)) {
				*cp1 = *cp2;
				return FSFATMOD;
			}
			return FSFATAL;
		}
		pwarn("Cluster %u is marked %s in FAT 0, but continues with cluster %u in FAT %d\n",
		      cl, rsrvdcltype(*cp1), *cp2, fatnum);
		if (ask(0, "Use continuation from FAT %u", fatnum)) {
			*cp1 = *cp2;
			return FSFATMOD;
		}
		if (ask(0, "Use mark from FAT 0")) {
			*cp2 = *cp1;
			return FSFATMOD;
		}
		return FSFATAL;
	}
	if (*cp2 == CLUST_FREE || *cp2 >= CLUST_RSRVD) {
		pwarn("Cluster %u continues with cluster %u in FAT 0, but is marked %s in FAT %u\n",
		      cl, *cp1, rsrvdcltype(*cp2), fatnum);
		if (ask(0, "Use continuation from FAT 0")) {
			*cp2 = *cp1;
			return FSFATMOD;
		}
		if (ask(0, "Use mark from FAT %d", fatnum)) {
			*cp1 = *cp2;
			return FSFATMOD;
		}
		return FSERROR;
	}
	pwarn("Cluster %u continues with cluster %u in FAT 0, but with cluster %u in FAT %u\n",
	      cl, *cp1, *cp2, fatnum);
	if (ask(0, "Use continuation from FAT 0")) {
		*cp2 = *cp1;
		return FSFATMOD;
	}
	if (ask(0, "Use continuation from FAT %u", fatnum)) {
		*cp1 = *cp2;
		return FSFATMOD;
	}
	return FSERROR;
}
Beispiel #2
0
int
checkfilesys(const char *filename)
{
	int dosfs;
	struct bootblock boot;
	struct fatEntry *fat = NULL;
	int i, finish_dosdirsection=0;
	int mod = 0;
	int ret = FSCK_EXIT_CHECK_FAILED;

	rdonly = alwaysno;
	if (!preen)
		printf("** %s", filename);

	dosfs = open(filename, rdonly ? O_RDONLY : O_RDWR, 0);
	if (dosfs < 0 && !rdonly) {
		dosfs = open(filename, O_RDONLY, 0);
		if (dosfs >= 0)
			pwarn(" (NO WRITE)\n");
		else if (!preen)
			printf("\n");
		rdonly = 1;
	} else if (!preen)
		printf("\n");

	if (dosfs < 0) {
		perr("Can't open `%s'", filename);
		return FSCK_EXIT_CHECK_FAILED;
	}

	if (readboot(dosfs, &boot) != FSOK) {
		close(dosfs);
		printf("\n");
		return FSCK_EXIT_CHECK_FAILED;
	}

	if (!preen)  {
		if (boot.ValidFat < 0)
			printf("** Phase 1 - Read and Compare FATs\n");
		else
			printf("** Phase 1 - Read FAT\n");
	}

	mod |= readfat(dosfs, &boot, boot.ValidFat >= 0 ? boot.ValidFat : 0, &fat);
	if (mod & FSFATAL) {
		close(dosfs);
		return FSCK_EXIT_CHECK_FAILED;
	}

	if (boot.ValidFat < 0)
		for (i = 1; i < boot.FATs; i++) {
			struct fatEntry *currentFat;

			mod |= readfat(dosfs, &boot, i, &currentFat);

			if (mod & FSFATAL)
				goto out;

			mod |= comparefat(&boot, fat, currentFat, i);
			free(currentFat);
			if (mod & FSFATAL)
				goto out;
		}

	if (!preen)
		printf("** Phase 2 - Check Cluster Chains\n");

	mod |= checkfat(&boot, fat);
	if (mod & FSFATAL)
		goto out;
	/* delay writing FATs */

	if (!preen)
		printf("** Phase 3 - Checking Directories\n");

	mod |= resetDosDirSection(&boot, fat);
	finish_dosdirsection = 1;
	if (mod & FSFATAL)
		goto out;
	/* delay writing FATs */

	mod |= handleDirTree(dosfs, &boot, fat);
	if (mod & FSFATAL)
		goto out;

	if (!preen)
		printf("** Phase 4 - Checking for Lost Files\n");

	mod |= checklost(dosfs, &boot, fat);
	if (mod & FSFATAL)
		goto out;

	/* now write the FATs */
	if (mod & FSFATMOD) {
		if (ask(1, "Update FATs")) {
			mod |= writefat(dosfs, &boot, fat, mod & FSFIXFAT);
			if (mod & FSFATAL)
				goto out;
		} else
			mod |= FSERROR;
	}

	if (boot.NumBad)
		pwarn("%d files, %d free (%d clusters), %d bad (%d clusters)\n",
		      boot.NumFiles,
		      boot.NumFree * boot.ClusterSize / 1024, boot.NumFree,
		      boot.NumBad * boot.ClusterSize / 1024, boot.NumBad);
	else
		pwarn("%d files, %d free (%d clusters)\n",
		      boot.NumFiles,
		      boot.NumFree * boot.ClusterSize / 1024, boot.NumFree);

	if (mod && (mod & FSERROR) == 0) {
		if (mod & FSDIRTY) {
			if (ask(1, "MARK FILE SYSTEM CLEAN") == 0)
				mod &= ~FSDIRTY;

			if (mod & FSDIRTY) {
				pwarn("MARKING FILE SYSTEM CLEAN\n");
				mod |= writefat(dosfs, &boot, fat, 1);
			} else {
				pwarn("\n***** FILE SYSTEM IS LEFT MARKED AS DIRTY *****\n");
				mod |= FSERROR; /* file system not clean */
			}
		}
	}

	if (mod & (FSFATAL | FSERROR))
		goto out;

	ret = FSCK_EXIT_OK;

    out:
	if (finish_dosdirsection)
		finishDosDirSection();
	free(fat);
	close(dosfs);

	if (mod & (FSFATMOD|FSDIRMOD))
		pwarn("\n***** FILE SYSTEM WAS MODIFIED *****\n");

	return ret;
}
Beispiel #3
0
/*
 * Read a FAT and decode it into internal format
 */
int
readfat(int fs, struct bootblock *boot, u_int no, struct fatEntry **fp)
{
	struct fatEntry *fat;
	u_char *buffer, *p;
	cl_t cl;
	int ret = FSOK;
	size_t len;

	boot->NumFree = boot->NumBad = 0;

	if (!_readfat(fs, boot, no, &buffer))
		return FSFATAL;

	fat = malloc(len = boot->NumClusters * sizeof(struct fatEntry));
	if (fat == NULL) {
		perr("No space for FAT clusters (%zu)", len);
		free(buffer);
		return FSFATAL;
	}
	(void)memset(fat, 0, len);

	if (buffer[0] != boot->bpbMedia
	    || buffer[1] != 0xff || buffer[2] != 0xff
	    || (boot->ClustMask == CLUST16_MASK && buffer[3] != 0xff)
	    || (boot->ClustMask == CLUST32_MASK
		&& ((buffer[3]&0x0f) != 0x0f
		    || buffer[4] != 0xff || buffer[5] != 0xff
		    || buffer[6] != 0xff || (buffer[7]&0x0f) != 0x0f))) {

		/* Windows 95 OSR2 (and possibly any later) changes
		 * the FAT signature to 0xXXffff7f for FAT16 and to
		 * 0xXXffff0fffffff07 for FAT32 upon boot, to know that the
		 * file system is dirty if it doesn't reboot cleanly.
		 * Check this special condition before errorring out.
		 */
		if (buffer[0] == boot->bpbMedia && buffer[1] == 0xff
		    && buffer[2] == 0xff
		    && ((boot->ClustMask == CLUST16_MASK && buffer[3] == 0x7f)
			|| (boot->ClustMask == CLUST32_MASK
			    && buffer[3] == 0x0f && buffer[4] == 0xff
			    && buffer[5] == 0xff && buffer[6] == 0xff
			    && buffer[7] == 0x07)))
			ret |= FSDIRTY;
		else {
			/* just some odd byte sequence in FAT */

			switch (boot->ClustMask) {
			case CLUST32_MASK:
				pwarn("%s (%02x%02x%02x%02x%02x%02x%02x%02x)\n",
				      "FAT starts with odd byte sequence",
				      buffer[0], buffer[1], buffer[2], buffer[3],
				      buffer[4], buffer[5], buffer[6], buffer[7]);
				break;
			case CLUST16_MASK:
				pwarn("%s (%02x%02x%02x%02x)\n",
				    "FAT starts with odd byte sequence",
				    buffer[0], buffer[1], buffer[2], buffer[3]);
				break;
			default:
				pwarn("%s (%02x%02x%02x)\n",
				    "FAT starts with odd byte sequence",
				    buffer[0], buffer[1], buffer[2]);
				break;
			}


			if (ask(1, "Correct"))
				ret |= FSFIXFAT;
		}
	}
	switch (boot->ClustMask) {
	case CLUST32_MASK:
		p = buffer + 8;
		break;
	case CLUST16_MASK:
		p = buffer + 4;
		break;
	default:
		p = buffer + 3;
		break;
	}
	for (cl = CLUST_FIRST; cl < boot->NumClusters;) {
		switch (boot->ClustMask) {
		case CLUST32_MASK:
			fat[cl].next = p[0] + (p[1] << 8)
				       + (p[2] << 16) + (p[3] << 24);
			fat[cl].next &= boot->ClustMask;
			ret |= checkclnum(boot, no, cl, &fat[cl].next);
			cl++;
			p += 4;
			break;
		case CLUST16_MASK:
			fat[cl].next = p[0] + (p[1] << 8);
			ret |= checkclnum(boot, no, cl, &fat[cl].next);
			cl++;
			p += 2;
			break;
		default:
			fat[cl].next = (p[0] + (p[1] << 8)) & 0x0fff;
			ret |= checkclnum(boot, no, cl, &fat[cl].next);
			cl++;
			if (cl >= boot->NumClusters)
				break;
			fat[cl].next = ((p[1] >> 4) + (p[2] << 4)) & 0x0fff;
			ret |= checkclnum(boot, no, cl, &fat[cl].next);
			cl++;
			p += 3;
			break;
		}
	}

	free(buffer);
	if (ret & FSFATAL) {
		free(fat);
		*fp = NULL;
	} else
		*fp = fat;
	return ret;
}
Beispiel #4
0
int
checkfilesys(const char *fname)
{
	int dosfs;
	struct bootblock boot;
	struct fatEntry *fat = NULL;
	int i;
	int mod = 0;
        int quiet = 0;
        int skip_fat_compare = 0;

	rdonly = alwaysno;
	if (!quiet)
		printf("** %s", fname);

	dosfs = open(fname, rdonly ? O_RDONLY : O_RDWR, 0);
	if (dosfs < 0 && !rdonly) {
		dosfs = open(fname, O_RDONLY, 0);
		if (dosfs >= 0)
			pwarn(" (NO WRITE)\n");
		else if (!quiet)
			printf("\n");
		rdonly = 1;
	} else if (!quiet)
		printf("\n");

	if (dosfs < 0) {
		perror("Can't open");
		return 8;
	}

	if (readboot(dosfs, &boot) == FSFATAL) {
		close(dosfs);
		printf("\n");
		return 8;
	}

	if (skipclean && preen && checkdirty(dosfs, &boot)) {
		printf("%s: ", fname);
		printf("FILESYSTEM CLEAN; SKIPPING CHECKS\n");
		close(dosfs);
		return 0;
	}

        if (((boot.FATsecs * boot.BytesPerSec) / 1024) > FAT_COMPARE_MAX_KB)
            skip_fat_compare = 1;

	if (!quiet)  {
                if (skip_fat_compare) 
                        printf("** Phase 1 - Read FAT (compare skipped)\n");
		else if (boot.ValidFat < 0)
			printf("** Phase 1 - Read and Compare FATs\n");
		else
			printf("** Phase 1 - Read FAT\n");
	}

	mod |= readfat(dosfs, &boot, boot.ValidFat >= 0 ? boot.ValidFat : 0, &fat);
	if (mod & FSERROR) {
		printf("FSERROR after readfat()\n");
	}
	if (mod & FSFATAL) {
		printf("\nFatal error during readfat()\n");
		close(dosfs);
		return 8;
	}

	if (!skip_fat_compare && boot.ValidFat < 0)
		for (i = 1; i < (int)boot.FATs; i++) {
			struct fatEntry *currentFat;

			mod |= readfat(dosfs, &boot, i, &currentFat);

			if (mod & FSFATAL) {
				printf("Fatal error during readfat() for comparison\n");
				free(fat);
				(void)close(dosfs);
				return 8;
			}

			mod |= comparefat(&boot, fat, currentFat, i);
			free(currentFat);
			if (mod & FSFATAL) {
				printf("Fatal error during FAT comparison\n");
				free(fat);
				(void)close(dosfs);
				return 8;
			}
		}

	if (!quiet)
		printf("** Phase 2 - Check Cluster Chains\n");

	mod |= checkfat(&boot, fat);
	if (mod & FSERROR) {
		printf("FSERROR after checkfat()\n");
	}
	if (mod & FSFATAL) {
		printf("Fatal error during FAT check\n");
		free(fat);
		(void)close(dosfs);
		return 8;
	}
	/* delay writing FATs */

	if (!quiet)
		printf("** Phase 3 - Checking Directories\n");

	mod |= resetDosDirSection(&boot, fat);
	if (mod & FSERROR) {
		printf("FSERROR after resetDosDirSection()\n");
	}
	if (mod & FSFATAL) {
		printf("Fatal error during resetDosDirSection()\n");
		free(fat);
		close(dosfs);
		return 8;
	}
	/* delay writing FATs */

	mod |= handleDirTree(dosfs, &boot, fat);
	if (mod & FSERROR) {
		printf("FSERROR after handleDirTree()\n");
		/* try to recovery again */
		mod &= ~FSERROR;
		mod |= handleDirTree(dosfs, &boot, fat);
	}
	if (mod & FSFATAL) {
		printf("Fatal error during handleDirTree()\n");
		finishDosDirSection();
		free(fat);
		close(dosfs);
		return 8;
	}

	if (!quiet)
		printf("** Phase 4 - Checking for Lost Files\n");

	mod |= checklost(dosfs, &boot, fat);
	if (mod & FSERROR) {
		printf("FSERROR after checklost()\n");
	}
	if (mod & FSFATAL) {
		printf("Fatal error during checklost()\n");
		finishDosDirSection();
		free(fat);
		(void)close(dosfs);
		return 8;
	}

	/* now write the FATs */
	if (mod & FSFATMOD) {
		if (ask(1, "Update FATs")) {
			mod |= writefat(dosfs, &boot, fat, mod & FSFIXFAT);
			if (mod & FSFATAL) {
				printf("Fatal error during writefat()\n");
				finishDosDirSection();
				free(fat);
				(void)close(dosfs);
				return 8;
			}
		} else
			mod |= FSERROR;
	}

	if (boot.NumBad)
		pwarn("%d files, %d free (%d clusters), %d bad (%d clusters)\n",
		      boot.NumFiles,
		      boot.NumFree * boot.ClusterSize / 1024, boot.NumFree,
		      boot.NumBad * boot.ClusterSize / 1024, boot.NumBad);
	else
		pwarn("%d files, %d free (%d clusters)\n",
		      boot.NumFiles,
		      boot.NumFree * boot.ClusterSize / 1024, boot.NumFree);

	if (mod && (mod & FSERROR) == 0) {
		if (mod & FSDIRTY) {
			if (ask(1, "MARK FILE SYSTEM CLEAN") == 0)
				mod &= ~FSDIRTY;

			if (mod & FSDIRTY) {
				pwarn("MARKING FILE SYSTEM CLEAN\n");
				mod |= writefat(dosfs, &boot, fat, 1);
			} else {
				pwarn("\n***** FILE SYSTEM IS LEFT MARKED AS DIRTY *****\n");
				mod |= FSERROR; /* file system not clean */
			}
		}
	}

	finishDosDirSection();
	free(fat);
	(void)close(dosfs);

	if (mod & FSFATAL) {
		pwarn("\n***** FSFATAL *****\n");
		return 8;
	}
	if (mod & FSERROR) {
		pwarn("\n***** FSERROR *****\n");
		return 8;
	}
	if (mod) {
		pwarn("\n***** FILE SYSTEM WAS MODIFIED *****\n");
		return 4; 
	}

	return 0;
}
 int sumRange(int i, int j) {
     return ask (j + 1) - ask (i);
 }
Beispiel #6
0
int write_cabrillo(void)
{
    extern char* cabrillo;
    extern char logfile[];
    extern char exchange[];
    extern char call[];

    char* cab_dfltfile;
    struct cabrillo_desc *cabdesc;
    char cabrillo_tmp_name[80];
    char buffer[4000] = "";

    FILE *fp1, *fp2;
    struct qso_t *qso;

    if (cabrillo == NULL) {
	info("Missing CABRILLO= keyword (see man page)");
	sleep(2);
    	return(1);
    }

    /* Try to read cabrillo format first from local directory.
     * Try also in default data dir if not found.
     */
    cabdesc = read_cabrillo_format("cabrillo.fmt", cabrillo);
    if (!cabdesc) {
	cab_dfltfile = g_strconcat(PACKAGE_DATA_DIR, G_DIR_SEPARATOR_S,
	    "cabrillo.fmt", NULL);
	cabdesc = read_cabrillo_format(cab_dfltfile, cabrillo);
	g_free(cab_dfltfile);
    }

    if (!cabdesc) {
    	info("Cabrillo format specification not found!");
	sleep(2);
	return(2);
    }

    /* open logfile and create a cabrillo file */
    strcpy(cabrillo_tmp_name, call);
    g_strstrip(cabrillo_tmp_name); /* drop \n */
    strcat(cabrillo_tmp_name, ".cbr");

    if ((fp1 = fopen(logfile, "r")) == NULL) {
	info("Can't open logfile.");
	sleep(2);
	free_cabfmt( cabdesc );
	return (1);
    }
    if ((fp2 = fopen(cabrillo_tmp_name, "w")) == NULL) {
	info("Can't create cabrillo file.");
	sleep(2);
	free_cabfmt( cabdesc );
	fclose(fp1);		//added by F8CFE
	return (2);
    }


    /* ask for exchange and header information */
    ask(buffer, "Your exchange (e.g. State, province, age etc... (# if serial number)): ");
    strncpy(exchange, buffer, 10);
    getsummary( fp2 );

    info("Writing cabrillo file");

    while ((qso = get_next_record(fp1))) {

	prepare_line(qso, cabdesc, buffer);

	if (strlen(buffer) > 5)
	    fputs(buffer, fp2);

	free_qso(qso);
    }

    fclose(fp1);

    fputs("END-OF-LOG:\n", fp2);
    fclose(fp2);

    free_cabfmt( cabdesc );

    return 0;
}
Beispiel #7
0
  /* Never should get here */
}

static int
match_process_uid(pid_t pid, uid_t uid)
{
	char buf[128];
	uid_t puid;
	FILE *f;
	int re = -1;
	
	snprintf (buf, sizeof buf, PROC_BASE "/%d/status", pid);
	if (!(f = fopen (buf, "r")))
		return 0;
	
	while (fgets(buf, sizeof buf, f))
	{
		if (sscanf (buf, "Uid:\t%d", &puid))
		{
			re = uid==puid;
			break;
		}
	}
	fclose(f);
	if (re==-1)
	{
		fprintf(stderr, _("Cannot get UID from process status\n"));
		exit(1);
	}
	return re;
}

static regex_t *
build_regexp_list(int names, char **namelist)
{
	int i;
	regex_t *reglist;
	int flag = REG_EXTENDED|REG_NOSUB;
	
	if (!(reglist = malloc (sizeof (regex_t) * names)))
	{
		perror ("malloc");
		exit (1);
	}

	if (ignore_case)
		flag |= REG_ICASE;
	
	for (i = 0; i < names; i++)
	{
		if (regcomp(&reglist[i], namelist[i], flag) != 0) 
		{
			fprintf(stderr, _("Bad regular expression: %s\n"), namelist[i]);
			exit (1);
		}
	}
	return reglist;
}

#ifdef WITH_SELINUX
static int
kill_all(int signal, int names, char **namelist, struct passwd *pwent, 
					regex_t *scontext )
#else  /*WITH_SELINUX*/
static int
kill_all (int signal, int names, char **namelist, struct passwd *pwent)
#endif /*WITH_SELINUX*/
{
  DIR *dir;
  struct dirent *de;
  FILE *file;
  struct stat st, sts[MAX_NAMES];
  int *name_len = NULL;
  char *path, comm[COMM_LEN];
  char *command_buf;
  char *command;
  pid_t *pid_table, pid, self, *pid_killed;
  pid_t *pgids;
  int i, j, okay, length, got_long, error;
  int pids, max_pids, pids_killed;
  unsigned long found;
  regex_t *reglist = NULL;;
#ifdef WITH_SELINUX
  security_context_t lcontext=NULL;
#endif /*WITH_SELINUX*/

  if (names && reg) 
      reglist = build_regexp_list(names, namelist);
  else if (names)
   {
      if (!(name_len = malloc (sizeof (int) * names)))
        {
          perror ("malloc");
          exit (1);
        }
      for (i = 0; i < names; i++) 
        {
          if (!strchr (namelist[i], '/'))
            {
	      sts[i].st_dev = 0;
	      name_len[i] = strlen (namelist[i]);
            }
          else if (stat (namelist[i], &sts[i]) < 0)
            {
	      perror (namelist[i]);
	      exit (1);
            }
        }
    } 
  self = getpid ();
  found = 0;
  if (!(dir = opendir (PROC_BASE)))
    {
      perror (PROC_BASE);
      exit (1);
    }
  max_pids = 256;
  pid_table = malloc (max_pids * sizeof (pid_t));
  if (!pid_table)
    {
      perror ("malloc");
      exit (1);
    }
  pids = 0;
  while ( (de = readdir (dir)) != NULL)
    {
      if (!(pid = (pid_t) atoi (de->d_name)) || pid == self)
	continue;
      if (pids == max_pids)
	{
	  if (!(pid_table = realloc (pid_table, 2 * pids * sizeof (pid_t))))
	    {
	      perror ("realloc");
	      exit (1);
	    }
	  max_pids *= 2;
	}
      pid_table[pids++] = pid;
    }
  (void) closedir (dir);
  pids_killed = 0;
  pid_killed = malloc (max_pids * sizeof (pid_t));
  if (!pid_killed)
    {
      perror ("malloc");
      exit (1);
    }
  if (!process_group)
    pgids = NULL;		/* silence gcc */
  else
    {
      pgids = malloc (pids * sizeof (pid_t));
      if (!pgids)
	{
	  perror ("malloc");
	  exit (1);
	}
    }
  for (i = 0; i < pids; i++)
    {
      pid_t id;
      int found_name = -1;

      /* match by UID */
      if (pwent && match_process_uid(pid_table[i], pwent->pw_uid)==0)
	continue;
#ifdef WITH_SELINUX
      /* match by SELinux context */
      if (scontext) 
        {
          if (getpidcon(pid_table[i], &lcontext) < 0)
            continue;
	  if (regexec(scontext, lcontext, 0, NULL, 0) != 0) {
            freecon(lcontext);
            continue;
          }
          freecon(lcontext);
        }
#endif /*WITH_SELINUX*/
      /* load process name */
      if (asprintf (&path, PROC_BASE "/%d/stat", pid_table[i]) < 0)
	continue;
      if (!(file = fopen (path, "r"))) 
	{
	  free (path);
	  continue;
	}
      free (path);
      okay = fscanf (file, "%*d (%15[^)]", comm) == 1;
      (void) fclose (file);
      if (!okay)
	continue;
      got_long = 0;
      command = NULL;		/* make gcc happy */
      length = strlen (comm);
      if (length == COMM_LEN - 1)
	{
	  if (asprintf (&path, PROC_BASE "/%d/cmdline", pid_table[i]) < 0)
	    continue;
	  if (!(file = fopen (path, "r"))) {
	    free (path);
	    continue;
	  }
	  free (path);
          while (1) {
            /* look for actual command so we skip over initial "sh" if any */
            char *p;
	    int cmd_size = 128;
	    command_buf = (char *)malloc (cmd_size);
	    if (!command_buf)
	      exit (1);

            /* 'cmdline' has arguments separated by nulls */
            for (p=command_buf; ; p++) {
              int c;
	      if (p == (command_buf + cmd_size)) 
		{
		  int cur_size = cmd_size;
		  cmd_size *= 2;
		  command_buf = (char *)realloc(command_buf, cmd_size);
		  if (!command_buf)
		    exit (1);
		  p = command_buf + cur_size;
		}
              c = fgetc(file);
              if (c == EOF || c == '\0') {
                *p = '\0';
                break;
              } else {
                *p = c;
              }
            }
            if (strlen(command_buf) == 0) {
              okay = 0;
              break;
            }
            p = strrchr(command_buf,'/');
            p = p ? p+1 : command_buf;
            if (strncmp(p, comm, COMM_LEN-1) == 0) {
              okay = 1;
              command = p;
              break;
            }
          }
          (void) fclose(file);
	  if (exact && !okay)
	    {
	      if (verbose)
		fprintf (stderr, _("skipping partial match %s(%d)\n"), comm,
			 pid_table[i]);
	      continue;
	    }
	  got_long = okay;
	}
      /* mach by process name */
      for (j = 0; j < names; j++)
	{
	  if (reg)
	    {
	      if (regexec (&reglist[j], got_long ? command : comm, 0, NULL, 0) != 0)
		      continue;
	    }
	  else /* non-regex */
	    {
 	      if (!sts[j].st_dev)
	        {
	          if (length != COMM_LEN - 1 || name_len[j] < COMM_LEN - 1)
	  	    {
		      if (ignore_case == 1)
		        {
		          if (strcasecmp (namelist[j], comm))
		             continue;
		        }
		      else
		        {
		          if (strcmp(namelist[j], comm))
		             continue;
		        }
		    }
	          else if (got_long ? strcmp (namelist[j], command) :
		                      strncmp (namelist[j], comm, COMM_LEN - 1))
		    continue;
	        }
	      else
	        {
		  int ok = 1;

	          if (asprintf (&path, PROC_BASE "/%d/exe", pid_table[i]) < 0)
		    continue;

	          if (stat (path, &st) < 0) 
		      ok = 0;

		  else if (sts[j].st_dev != st.st_dev ||
			   sts[j].st_ino != st.st_ino)
		    {
		      /* maybe the binary has been modified and std[j].st_ino
		       * is not reliable anymore. We need to compare paths.
		       */
		      char linkbuf[PATH_MAX];

		      if (readlink(path, linkbuf, sizeof(linkbuf)) <= 0 ||
					  strcmp(namelist[j], linkbuf))
			ok = 0;
		    }

		  free(path);
		  if (!ok)
		    continue;
	        }
	    } /* non-regex */
	  found_name = j;
	  break;
	}  
        
        if (names && found_name==-1)
	  continue;  /* match by process name faild */
	
        /* check for process group */
	if (!process_group)
	  id = pid_table[i];
	else
	  {
	    int j;

	    id = getpgid (pid_table[i]);
	    pgids[i] = id;
	    if (id < 0)
	      {
	        fprintf (stderr, "getpgid(%d): %s\n", pid_table[i],
		   strerror (errno));
	      }
	    for (j = 0; j < i; j++)
	      if (pgids[j] == id)
	        break;
	    if (j < i)
	      continue;
	  }	
	if (interactive && !ask (comm, id, signal))
	  continue;
	if (pidof)
	  {
	    if (found)
	       putchar (' ');
	    printf ("%d", id);
	    found |= 1 << (found_name >= 0 ? found_name : 0);
	  }
	else if (kill (process_group ? -id : id, signal) >= 0)
	  {
	    if (verbose)
	      fprintf (stderr, _("Killed %s(%s%d) with signal %d\n"), got_long ? command :
			 comm, process_group ? "pgid " : "", id, signal);
	    if (found_name >= 0)
		    /* mark item of namelist */
		    found |= 1 << found_name;
	    pid_killed[pids_killed++] = id;
	  }
	else if (errno != ESRCH || interactive)
	  fprintf (stderr, "%s(%d): %s\n", got_long ? command :
	    	comm, id, strerror (errno));
    }
  if (!quiet && !pidof)
    for (i = 0; i < names; i++)
      if (!(found & (1 << i)))
	fprintf (stderr, _("%s: no process killed\n"), namelist[i]);
  if (pidof)
    putchar ('\n');
  if (names)
    /* killall returns a zero return code if at least one process has 
     * been killed for each listed command. */
    error = found == ((1 << (names - 1)) | ((1 << (names - 1)) - 1)) ? 0 : 1;
  else
    /* in nameless mode killall returns a zero return code if at least 
     * one process has killed */
    error = pids_killed ? 0 : 1;
  /*
   * We scan all (supposedly) killed processes every second to detect dead
   * processes as soon as possible in order to limit problems of race with
   * PID re-use.
   */
  while (pids_killed && wait_until_dead)
    {
      for (i = 0; i < pids_killed;)
	{
	  if (kill (process_group ? -pid_killed[i] : pid_killed[i], 0) < 0 &&
	      errno == ESRCH)
	    {
	      pid_killed[i] = pid_killed[--pids_killed];
	      continue;
	    }
	  i++;
	}
      sleep (1);		/* wait a bit longer */
    }
  return error;
}
Beispiel #8
0
uval
test_os(uval argc, uval argv[])
{
	uval ret[1];
	sval rc;
	uval r3 = argv[0];
	uval r4 = argv[1];
	uval ofd;
	const uval slot = 0x1;
	uval schedvals[3];
	sval rot;
	uval nchunks = 0;
	uval ofd_size;
	uval i = 0;

	argc = argc;

	rrupts_off();

        /* Setting up the IPC structures */
#ifndef RELOADER
	ret[0] = aipc_config(msgHandler);
	if (ret[0] != H_Success) {
		hprintf("Failed create: %ld\n", ret[0]);
	}
#endif
	if (r3 == ~0UL) {
		/* we../src/bin/mambo-sti -n have cloned ourselves */
		hputs("hello world.. this is slave\n");
		rc = hcall_get_lpid(ret);
		assert(rc == H_Success, "hcall_get_lpid() failed\n");
		hprintf("I am partition ID %ld\n", ret[0]);
		yield(0);
	}

	hputs("hello world.. this is controller\n");
	rc = hcall_get_lpid(ret);
	assert(rc == H_Success, "hcall_get_lpid() failed\n");

	ofd = ofd_devtree_init(r4, &ofd_size);
	ofd_bootargs(ofd, default_bootargs, sizeof (default_bootargs));

	pgalloc_init(&pa, (uval)_end,  0, pinfo[1].mem[0].size, LOG_PGSIZE);

	if (ofd) {
		set_pages_used(&pa, (uval)ofd, ofd_size);
	}

	init_allocator(&pa);

	rrupts_on();

	struct mem_range *mem = &pinfo[1].mem[0];
	uval max_addr = mem[0].size;

	while (i < MAX_MEM_RANGES &&
	       mem[i].size != INVALID_MEM_RANGE) {
		nchunks += mem[i].size / CHUNK_SIZE;
		max_addr = mem[i].addr + mem[i].size;
		++i;
	}

	pgalloc_init(&logical_pa, ~((uval)0), 0, max_addr, LOG_PGSIZE);
	set_pages_used(&logical_pa, 0, CHUNK_SIZE);

	uval curr = CHUNK_SIZE;
	i = 0;
	while (i < MAX_MEM_RANGES &&
	       mem[i].size != INVALID_MEM_RANGE) {
		if (curr < mem[i].addr) {
			set_pages_used(&logical_pa, curr,
				       mem[i].addr - curr);
			curr = mem[i].addr;
		}
		if (curr < mem[i].addr + mem[i].size) {
			free_pages(&logical_pa, curr,
				   mem[i].addr + mem[i].size - curr);
			curr = mem[i].addr + mem[i].size;
		}
		
		if (curr == mem[i].addr + mem[i].size) {
			++i;
		}
	}

	assert(nchunks >= 1, "not enough chunks to create an LPAR\n");

	hprintf("setting my sched slot to 0x%0lx\n", slot);
	rot = hcall_set_sched_params(schedvals, H_SELF_LPID,
				     THIS_CPU, slot, 0);
	assert(rot >= 0, "set sched failed\n");
	hprintf("Scheduler controller: rot: "
		"%ld (0x%016lx, 0x%016lx 0x%016lx)\n",
		rot, schedvals[0], schedvals[1], schedvals[2]);

	curslots = schedvals[0];

#ifdef RELOADER
	reload_image(image_names[0], ofd);
#endif

	for (i = 0; i < MAX_MANAGED_PARTITIONS; ++i) {
		curslots &= ~partitions[i].slot;
		partitions[i].active = 0;

		partitions[i].init_mem = 0;
		partitions[i].init_mem_size = 0;

		partitions[i].lpid = -1;
		partitions[i].vterm = 0;

		partitions[i].slot = 0;
		partitions[i].msgrcv = 0;
		partitions[i].name = NULL;
	}


	ask(r3, ofd);

	assert(0, "controller: Should never get here\n");

	return 0;
}
Beispiel #9
0
void auto_create_bookmark(void)
{
	listitem *li;
	int a;
	bool auto_create, had_passwd = false;
	bool update = false;

	if(gvAutoBookmark == 0 && gvAutoBookmarkUpdate == 0)
		return;

	if(!ftp_loggedin() || gvSighupReceived)
		return;

	auto_create = (gvAutoBookmark == 1);

	/* check if bookmark already exists */
	li = list_search(gvBookmarks, (listsearchfunc)urlcmp, ftp->url);
	if(li) {
		if(!should_update_bookmark((url_t *)li->data))
			return;

		/* bookmark already exist, update it */
		if(gvAutoBookmarkUpdate == 2) {
			a = ask(ASKYES|ASKNO, ASKYES,
					_("Do you want to update the bookmark for this site?"));
			if(a == ASKNO)
				return;
		}

		update = true;
		auto_create = true;
		had_passwd = (((url_t *)li->data)->password != 0);
	}

	if(gvAutoBookmark == 2 && !auto_create) {
		a = ask(ASKYES|ASKNO, ASKYES,
				_("Do you want to create a bookmark for this site?"));
		if(a == ASKNO)
			return;
		create_bookmark(0);
	} else { /* auto autobookmark... */
		url_t *url;
		char *a;

		url = url_clone(ftp->url);
		a = guess_alias(ftp->url);
		url_setalias(url, a);
		free(a);

		li = list_search(gvBookmarks, (listsearchfunc)urlcmp, url);
		if(li) {
			/* bookmark already exist, overwrite it */
			while(true) {
				url_t *xurl = (url_t *)li->data;

				if(xurl->alias && (strcmp(xurl->alias, url->alias) == 0)
				   && (strcmp(xurl->hostname, url->hostname) != 0))
				{
					/* create a new version of the alias, since guessed alias
					 * already exists but for another host
					 */

					char *par;
					update = false;
					par = strrchr(url->alias, '(');
					if(par == 0)
						asprintf(&a, "%s(2)", url->alias);
					else {
						int ver;
						*par = 0;
						ver = atoi(par + 1);
						asprintf(&a, "%s(%d)", url->alias, ver + 1);
					}
					url_setalias(url, a);
					free(a);
				} else {
					update = true;
					had_passwd = (xurl->password != 0);
					break;
				}
				li = list_search(gvBookmarks, (listsearchfunc)urlcmp, url);
				if(li == 0)
					break;
			}
			if(li) /* overwrite bookmark (ie, delete old and create a new) */
				list_delitem(gvBookmarks, li);
			if(!url_isanon(url) && gvAutoBookmarkSavePasswd == false
			   && !had_passwd)
				url_setpassword(url, 0);
		} else {
			if(!url_isanon(url) && gvAutoBookmarkSavePasswd == false)
				url_setpassword(url, 0);
		}
		create_the_bookmark(url);
		if(!gvAutoBookmarkSilent) {
			if(update)
				printf(_("updated bookmark %s\n"), url->alias);
			else
				printf(_("created bookmark %s\n"), url->alias);
		}
	}
}
Beispiel #10
0
int
main(int argc, char *argv[])
{
	bool newrc, already;
	int rcfirst = 0;		/* first message to print (from .rc) */
	int rcback = 0;			/* amount to back off of rcfirst */
	int firstmsg = 0, nextmsg = 0, lastmsg = 0;
	int blast = 0;
	struct stat buf;		/* stat to check access of bounds */
	FILE *bounds;
	char *cp;

#ifdef UNBUFFERED
	setbuf(stdout, NULL);
#endif
	setlocale(LC_ALL, "");

	time(&t);
	if (setuid(uid = getuid()) != 0)
		err(1, "setuid failed");
	ruptible = (signal(SIGINT, SIG_IGN) == SIG_DFL);
	if (ruptible)
		signal(SIGINT, SIG_DFL);

	argc--, argv++;
	while (argc > 0) {
		if (isdigit(argv[0][0])) {	/* starting message # */
			rcfirst = atoi(argv[0]);
		}
		else if (isdigit(argv[0][1])) {	/* backward offset */
			rcback = atoi( &( argv[0][1] ) );
		}
		else {
			ptr = *argv;
			while (*ptr) switch (*ptr++) {

			case '-':
				break;

			case 'c':
				if (uid != SUPERUSER && uid != DAEMON)
					errx(1,
				"only the super-user can use the c flag");
				clean = YES;
				break;

			case 'f':		/* silently */
				hush = YES;
				break;

			case 'h':		/* headers only */
				hdrs = YES;
				break;

			case 'l':		/* local msgs only */
				locomode = YES;
				break;

			case 'o':		/* option to save last message */
				lastcmd = YES;
				break;

			case 'p':		/* pipe thru 'more' during long msgs */
				use_pager = YES;
				break;

			case 'q':		/* query only */
				qopt = YES;
				break;

			case 's':		/* sending TO msgs */
				send_msg = YES;
				break;

			default:
				usage();
			}
		}
		argc--, argv++;
	}

	/*
	 * determine current message bounds
	 */
	snprintf(fname, sizeof(fname), "%s/%s", _PATH_MSGS, BOUNDS);

	/*
	 * Test access rights to the bounds file
	 * This can be a little tricky.  if(send_msg), then
	 * we will create it.  We assume that if(send_msg),	
	 * then you have write permission there.
	 * Else, it better be there, or we bail.
	 */
	if (send_msg != YES) {
		if (stat(fname, &buf) < 0) {
			if (hush != YES) {
				err(errno, "%s", fname);
			} else {
				exit(1);
			}
		}
	}
	bounds = fopen(fname, "r");

	if (bounds != NULL) {
		fscanf(bounds, "%d %d\n", &firstmsg, &lastmsg);
		fclose(bounds);
		blast = lastmsg;	/* save upper bound */
	}

	if (clean)
		keep = t - (rcback? rcback : NDAYS) DAYS;

	if (clean || bounds == NULL) {	/* relocate message bounds */
		struct dirent *dp;
		struct stat stbuf;
		bool seenany = NO;
		DIR	*dirp;

		dirp = opendir(_PATH_MSGS);
		if (dirp == NULL)
			err(errno, "%s", _PATH_MSGS);

		firstmsg = 32767;
		lastmsg = 0;

		for (dp = readdir(dirp); dp != NULL; dp = readdir(dirp)){
			cp = dp->d_name;
			int i = 0;

			if (dp->d_ino == 0)
				continue;
			if (dp->d_namlen == 0)
				continue;

			if (clean)
				snprintf(inbuf, sizeof(inbuf), "%s/%s", _PATH_MSGS, cp);

			while (isdigit(*cp))
				i = i * 10 + *cp++ - '0';
			if (*cp)
				continue;	/* not a message! */

			if (clean) {
				if (stat(inbuf, &stbuf) != 0)
					continue;
				if (stbuf.st_mtime < keep
				    && stbuf.st_mode&S_IWRITE) {
					unlink(inbuf);
					continue;
				}
			}

			if (i > lastmsg)
				lastmsg = i;
			if (i < firstmsg)
				firstmsg = i;
			seenany = YES;
		}
		closedir(dirp);

		if (!seenany) {
			if (blast != 0)	/* never lower the upper bound! */
				lastmsg = blast;
			firstmsg = lastmsg + 1;
		}
		else if (blast > lastmsg)
			lastmsg = blast;

		if (!send_msg) {
			bounds = fopen(fname, "w");
			if (bounds == NULL)
				err(errno, "%s", fname);
			chmod(fname, CMODE);
			fprintf(bounds, "%d %d\n", firstmsg, lastmsg);
			fclose(bounds);
		}
	}

	if (send_msg) {
		/*
		 * Send mode - place msgs in _PATH_MSGS
		 */
		bounds = fopen(fname, "w");
		if (bounds == NULL)
			err(errno, "%s", fname);

		nextmsg = lastmsg + 1;
		snprintf(fname, sizeof(fname), "%s/%d", _PATH_MSGS, nextmsg);
		newmsg = fopen(fname, "w");
		if (newmsg == NULL)
			err(errno, "%s", fname);
		chmod(fname, CMODE);

		fprintf(bounds, "%d %d\n", firstmsg, nextmsg);
		fclose(bounds);

		sending = YES;
		if (ruptible)
			signal(SIGINT, onintr);

		if (isatty(fileno(stdin))) {
			ptr = getpwuid(uid)->pw_name;
			printf("Message %d:\nFrom %s %sSubject: ",
				nextmsg, ptr, ctime(&t));
			fflush(stdout);
			fgets(inbuf, sizeof inbuf, stdin);
			putchar('\n');
			fflush(stdout);
			fprintf(newmsg, "From %s %sSubject: %s\n",
				ptr, ctime(&t), inbuf);
			blankline = seensubj = YES;
		}
		else
			blankline = seensubj = NO;
		for (;;) {
			fgets(inbuf, sizeof inbuf, stdin);
			if (feof(stdin) || ferror(stdin))
				break;
			blankline = (blankline || (inbuf[0] == '\n'));
			seensubj = (seensubj || (!blankline && (strncmp(inbuf, "Subj", 4) == 0)));
			fputs(inbuf, newmsg);
		}
#ifdef OBJECT
		if (!seensubj) {
			printf("NOTICE: Messages should have a Subject field!\n");
#ifdef REJECT
			unlink(fname);
#endif
			exit(1);
		}
#endif
		exit(ferror(stdin));
	}
	if (clean)
		exit(0);

	/*
	 * prepare to display messages
	 */
	totty = (isatty(fileno(stdout)) != 0);
	use_pager = use_pager && totty;

	if ((cp = getenv("HOME")) == NULL || *cp == '\0') {
		fprintf(stderr, "Error, no home directory!\n");
		exit(1);
	}
	snprintf(fname, sizeof(fname), "%s/%s", cp, MSGSRC);
	msgsrc = fopen(fname, "r");
	if (msgsrc) {
		newrc = NO;
		fscanf(msgsrc, "%d\n", &nextmsg);
		fclose(msgsrc);
		if (nextmsg > lastmsg+1) {
			printf("Warning: bounds have been reset (%d, %d)\n",
				firstmsg, lastmsg);
			truncate(fname, (off_t)0);
			newrc = YES;
		}
		else if (!rcfirst)
			rcfirst = nextmsg - rcback;
	}
	else
		newrc = YES;
	msgsrc = fopen(fname, "r+");
	if (msgsrc == NULL)
		msgsrc = fopen(fname, "w");
	if (msgsrc == NULL)
		err(errno, "%s", fname);
	if (rcfirst) {
		if (rcfirst > lastmsg+1) {
			printf("Warning: the last message is number %d.\n",
				lastmsg);
			rcfirst = nextmsg;
		}
		if (rcfirst > firstmsg)
			firstmsg = rcfirst;	/* don't set below first msg */
	}
	if (newrc) {
		nextmsg = firstmsg;
		rewind(msgsrc);
		fprintf(msgsrc, "%d\n", nextmsg);
		fflush(msgsrc);
	}

#ifdef V7
	if (totty) {
		struct winsize win;
		if (ioctl(fileno(stdout), TIOCGWINSZ, &win) != -1)
			Lpp = win.ws_row;
		if (Lpp <= 0) {
			if (tgetent(inbuf, getenv("TERM")) <= 0
			    || (Lpp = tgetnum("li")) <= 0) {
				Lpp = NLINES;
			}
		}
	}
#endif
	Lpp -= 6;	/* for headers, etc. */

	already = NO;
	prevmsg = firstmsg;
	printing = YES;
	if (ruptible)
		signal(SIGINT, onintr);

	/*
	 * Main program loop
	 */
	for (msg = firstmsg; msg <= lastmsg; msg++) {

		snprintf(fname, sizeof(fname), "%s/%d", _PATH_MSGS, msg);
		newmsg = fopen(fname, "r");
		if (newmsg == NULL)
			continue;

		gfrsub(newmsg);		/* get From and Subject fields */
		if (locomode && !local) {
			fclose(newmsg);
			continue;
		}

		if (qopt) {	/* This has to be located here */
			printf("There are new messages.\n");
			exit(0);
		}

		if (already && !hdrs)
			putchar('\n');

		/*
		 * Print header
		 */
		if (totty)
			signal(SIGTSTP, onsusp);
		(void) setjmp(tstpbuf);
		already = YES;
		nlines = 2;
		if (seenfrom) {
			printf("Message %d:\nFrom %s %s", msg, from, date);
			nlines++;
		}
		if (seensubj) {
			printf("Subject: %s", subj);
			nlines++;
		}
		else {
			if (seenfrom) {
				putchar('\n');
				nlines++;
			}
			while (nlines < 6
			    && fgets(inbuf, sizeof inbuf, newmsg)
			    && inbuf[0] != '\n') {
				fputs(inbuf, stdout);
				nlines++;
			}
		}

		lct = linecnt(newmsg);
		if (lct)
			printf("(%d%sline%s) ", lct, seensubj? " " : " more ",
			    (lct == 1) ? "" : "s");

		if (hdrs) {
			printf("\n-----\n");
			fclose(newmsg);
			continue;
		}

		/*
		 * Ask user for command
		 */
		if (totty)
			ask(lct? MORE : (msg==lastmsg? NOMORE : NEXT));
		else
			inbuf[0] = 'y';
		if (totty)
			signal(SIGTSTP, SIG_DFL);
cmnd:
		in = inbuf;
		switch (*in) {
			case 'x':
				/* FALLTHROUGH */
			case 'X':
				exit(0);
				/* NOTREACHED */

			case 'q':
				/* FALLTHROUGH */
			case 'Q':
				quitit = YES;
				printf("--Postponed--\n");
				exit(0);
				/* NOTREACHED */

			case 'n':
				/* FALLTHROUGH */
			case 'N':
				if (msg >= nextmsg) sep = "Flushed";
				prevmsg = msg;
				break;

			case 'p':
				/* FALLTHROUGH */
			case 'P':
				use_pager = (*in++ == 'p');
				/* FALLTHROUGH */
			case '\n':
				/* FALLTHROUGH */
			case 'y':
			default:
				if (*in == '-') {
					msg = prevmsg-1;
					sep = "replay";
					break;
				}
				if (isdigit(*in)) {
					msg = next(in);
					sep = in;
					break;
				}

				prmesg(nlines + lct + (seensubj? 1 : 0));
				prevmsg = msg;

		}

		printf("--%s--\n", sep);
		sep = "-";
		if (msg >= nextmsg) {
			nextmsg = msg + 1;
			rewind(msgsrc);
			fprintf(msgsrc, "%d\n", nextmsg);
			fflush(msgsrc);
		}
		if (newmsg)
			fclose(newmsg);
		if (quitit)
			break;
	}

	/*
	 * Make sure .rc file gets updated
	 */
	if (--msg >= nextmsg) {
		nextmsg = msg + 1;
		rewind(msgsrc);
		fprintf(msgsrc, "%d\n", nextmsg);
		fflush(msgsrc);
	}
	if (already && !quitit && lastcmd && totty) {
		/*
		 * save or reply to last message?
		 */
		msg = prevmsg;
		ask(NOMORE);
		if (inbuf[0] == '-' || isdigit(inbuf[0]))
			goto cmnd;
	}
	if (!(already || hush || qopt))
		printf("No new messages.\n");
	exit(0);
	/* NOTREACHED */
}
Beispiel #11
0
static void
ask(const char *prompt)
{
	char	inch;
	int	n, cmsg, fd;
	off_t	oldpos;
	FILE	*cpfrom, *cpto;

	printf("%s ", prompt);
	fflush(stdout);
	intrpflg = NO;
	(void) fgets(inbuf, sizeof inbuf, stdin);
	if ((n = strlen(inbuf)) > 0 && inbuf[n - 1] == '\n')
		inbuf[n - 1] = '\0';
	if (intrpflg)
		inbuf[0] = 'x';

	/*
	 * Handle 'mail' and 'save' here.
	 */
	if ((inch = inbuf[0]) == 's' || inch == 'm') {
		if (inbuf[1] == '-')
			cmsg = prevmsg;
		else if (isdigit(inbuf[1]))
			cmsg = atoi(&inbuf[1]);
		else
			cmsg = msg;
		snprintf(fname, sizeof(fname), "%s/%d", _PATH_MSGS, cmsg);

		oldpos = ftello(newmsg);

		cpfrom = fopen(fname, "r");
		if (!cpfrom) {
			printf("Message %d not found\n", cmsg);
			ask (prompt);
			return;
		}

		if (inch == 's') {
			in = nxtfld(inbuf);
			if (*in) {
				for (n=0; in[n] > ' '; n++) { /* sizeof fname? */
					fname[n] = in[n];
				}
				fname[n] = '\0';
			}
			else
				strcpy(fname, "Messages");
			fd = open(fname, O_RDWR|O_EXCL|O_CREAT|O_APPEND);
		}
		else {
			strcpy(fname, _PATH_TMP);
			fd = mkstemp(fname);
			if (fd != -1) {
				snprintf(cmdbuf, sizeof(cmdbuf), _PATH_MAIL,
				    fname);
				mailing = YES;
			}
		}
		if (fd == -1 || (cpto = fdopen(fd, "a")) == NULL) {
			if (fd != -1)
				close(fd);
			warn("%s", fname);
			mailing = NO;
			fseeko(newmsg, oldpos, SEEK_SET);
			ask(prompt);
			return;
		}

		while ((n = fread(inbuf, 1, sizeof inbuf, cpfrom)))
			fwrite(inbuf, 1, n, cpto);

		fclose(cpfrom);
		fclose(cpto);
		fseeko(newmsg, oldpos, SEEK_SET);/* reposition current message */
		if (inch == 's')
			printf("Message %d saved in \"%s\"\n", cmsg, fname);
		else {
			system(cmdbuf);
			unlink(fname);
			mailing = NO;
		}
		ask(prompt);
	}
}
Beispiel #12
0
void load_ltaglist(bool showerr, bool always_autoload,
				   const char *alt_filename)
{
	FILE *fp;
	char *f, *e = 0;
	unsigned n = 0;
	int c;
	char tmp[4096];

	if(gvLoadTaglist == 0 && !always_autoload)
		return;

	if(alt_filename == 0)
		if (asprintf(&e, "%s/taglist.local", gvWorkingDirectory) == -1)
    {
      fprintf(stderr, _("Failed to allocate memory.\n"));
      return;
    }
  f = tilde_expand_home(alt_filename ? alt_filename : e, gvLocalHomeDir);
	free(e);
	fp = fopen(f, "r");
	if(!fp) {
		if(showerr) {
			if(alt_filename)
				perror(alt_filename);
			else
				fprintf(stderr, _("No saved local taglist\n"));
		}
		free(f);
		return;
	}

	if(gvLoadTaglist == 2 && !always_autoload) {
		c = ask(ASKYES|ASKNO, ASKYES,
				_("Found saved local taglist, load it now?"));
		if(c == ASKNO) {
			fclose(fp);
			return;
		}
	} /* else gvLoadTaglist == 1 == yes */

	if(fgets(tmp, 4096, fp) != 0) {
		strip_trailing_chars(tmp, "\n\r");
		if(strcasecmp(tmp, "[yafc taglist]") != 0) {
			fprintf(stderr, "Not a Yafc taglist file: %s\n", f);
			fclose(fp);
			return;
		}
	}

	while(true) {
		if(fgets(tmp, 4096, fp) == 0)
			break;
		strip_trailing_chars(tmp, "\r\n");
		if(tmp[0] == 0)
			continue;
		list_additem(gvLocalTagList, xstrdup(tmp));
		n++;
	}
	if(n)
		fprintf(stderr, "Loaded %u files from saved local taglist %s\n", n, f);
	fclose(fp);
	if(alt_filename == 0)
		unlink(f);
	free(f);
}
Beispiel #13
0
void Game::the_game()
{
	
	for (int i = 0; i < 13 * players; i++)
	{

		cout << "\nGRACZ " << current_player << endl << endl;

		dice_cup.throw_dice();
		score_sheet++; //sumowanie punktow
		show_score_sheet();

		//ponowne rzuty 

		int additional_throws = 0;

		do {

			if (ask() == 49)
			{

				if (score_sheet.save_points(false))
					break;

				else
					continue;

			}

			else
			{

				if (dice_cup.re_throw_dice())
				{

					additional_throws++;
					show_score_sheet();

					if (additional_throws == 2)
					{

						score_sheet.save_points(true);
						break;

					}
				}

				else
				{

					score_sheet.draw();

				}

			}

		} while (1);

		if (current_player == players)
			current_player = 1;

		else
			current_player++;

	}

	score_sheet++;
	cout << endl;
	show_score_sheet();
	score_sheet.who_win();
}
Beispiel #14
0
int ask(int x,int a,int b,int c){
  if(a==b)return v[x];
  int mid=(a+b)>>1;
  return c<=mid?ask(l[x],a,mid,c):ask(r[x],mid+1,b,c);
}
Beispiel #15
0
/*
 * Check a complete FAT in-memory for crosslinks
 */
int
checkfat(struct bootblock *boot, struct fatEntry *fat)
{
	cl_t head, p, h, n;
	u_int len;
	int ret = 0;
	int conf;

	/*
	 * pass 1: figure out the cluster chains.
	 */
	for (head = CLUST_FIRST; head < boot->NumClusters; head++) {
		/* find next untravelled chain */
		if (fat[head].head != 0		/* cluster already belongs to some chain */
		    || fat[head].next == CLUST_FREE
		    || fat[head].next == CLUST_BAD)
			continue;		/* skip it. */

		/* follow the chain and mark all clusters on the way */
		for (len = 0, p = head;
		     p >= CLUST_FIRST && p < boot->NumClusters &&
		     fat[p].head != head;
		     p = fat[p].next) {
			fat[p].head = head;
			len++;
		}

		/* the head record gets the length */
		fat[head].length = fat[head].next == CLUST_FREE ? 0 : len;
	}

	/*
	 * pass 2: check for crosslinked chains (we couldn't do this in pass 1 because
	 * we didn't know the real start of the chain then - would have treated partial
	 * chains as interlinked with their main chain)
	 */
	for (head = CLUST_FIRST; head < boot->NumClusters; head++) {
		/* find next untravelled chain */
		if (fat[head].head != head)
			continue;

		/* follow the chain to its end (hopefully) */
		for (len = fat[head].length, p = head;
		     (n = fat[p].next) >= CLUST_FIRST && n < boot->NumClusters;
		     p = n)
			if (fat[n].head != head || len-- < 2)
				break;
		if (n >= CLUST_EOFS)
			continue;

		if (n == CLUST_FREE || n >= CLUST_RSRVD) {
			pwarn("Cluster chain starting at %u ends with cluster marked %s\n",
			      head, rsrvdcltype(n));
clear:
			ret |= tryclear(boot, fat, head, &fat[p].next);
			continue;
		}
		if (n < CLUST_FIRST || n >= boot->NumClusters) {
			pwarn("Cluster chain starting at %u ends with cluster out of range (%u)\n",
			    head, n);
			goto clear;
		}
		if (head == fat[n].head) {
			pwarn("Cluster chain starting at %u loops at cluster %u\n",
			
			    head, p);
			goto clear;
		}
		pwarn("Cluster chains starting at %u and %u are linked at cluster %u\n",
		      head, fat[n].head, n);
		conf = tryclear(boot, fat, head, &fat[p].next);
		if (ask(0, "Clear chain starting at %u", h = fat[n].head)) {
			if (conf == FSERROR) {
				/*
				 * Transfer the common chain to the one not cleared above.
				 */
				for (p = n;
				     p >= CLUST_FIRST && p < boot->NumClusters;
				     p = fat[p].next) {
					if (h != fat[p].head) {
						/*
						 * Have to reexamine this chain.
						 */
						head--;
						break;
					}
					fat[p].head = head;
				}
			}
			clearchain(boot, fat, h);
			conf |= FSFATMOD;
		}
		ret |= conf;
	}

	return ret;
}
Beispiel #16
0
static bool zwritefile(char *fname)
{
	char bakname[PATHMAX + 1];
	struct mark smark;
	struct stat sbuf;
	int nlink = 1, rc;
	bool bak = false;

	/* If the file existed, check to see if it has been modified. */
	if (Curbuff->mtime && stat(fname, &sbuf) == 0) {
		if (sbuf.st_mtime > Curbuff->mtime) {
			strconcat(PawStr, PAWSTRLEN,
					  "WARNING: ", lastpart(fname),
					  " has been modified. Overwrite? ", NULL);
			if (ask(PawStr) != YES)
				return false;
		}
#ifndef __QNXNTO__
		nlink = sbuf.st_nlink;
#endif
	}

#if HUGE_FILES
	if (Bbuff->fd != -1) {
		strconcat(PawStr, PAWSTRLEN,
				  "WARNING: huge file ", lastpart(fname),
				  " not yet read. Are you sure? ", NULL);
		if (ask(PawStr) != YES)
			return false;
	}
#endif

	/* check for links and handle backup file */
	make_bakname(bakname, sizeof(bakname), fname);
	if (nlink > 1) {
		strconcat(PawStr, PAWSTRLEN, "WARNING: ", lastpart(fname),
				  " is linked. Preserve? ", NULL);
		switch (ask(PawStr)) {
		case YES:
			if (VAR(VBACKUP))
				bak = cp(fname, bakname);
			break;
		case NO:
			if (VAR(VBACKUP))
				bak = rename(fname, bakname);
			else
				unlink(fname);	/* break link */
			break;
		case ABORT:
			return false;
		}
	} else if (VAR(VBACKUP))
		bak = rename(fname, bakname);

	bmrktopnt(Bbuff, &smark);
	rc = bwritefile(Bbuff, fname, file_mode());
	bpnttomrk(Bbuff, &smark);
	if (rc) {
		if (stat(fname, &sbuf) == 0)
			Curbuff->mtime = sbuf.st_mtime;
		else
			Curbuff->mtime = -1;
		clrpaw();
	} else {
		if (errno == EACCES)
			error("File is read only.");
		else
			error("Unable to write file.");
		if (bak) {
			if (sbuf.st_nlink) {
				cp(bakname, fname);
				unlink(bakname);
			} else
				rename(bakname, fname);
		}
	}

	return rc;
}
Beispiel #17
0
int main(int argc, char * argv[])
{
#ifdef DEBUG
  open_debug();
#endif
  init_static_control_simple();
  void ask(addr_t addr)
    {
      char str[DEFAULT_TRANSFER];
      struct args args = { .log_addr = addr, .log_len = DEFAULT_TRANSFER, .phys_addr = (unsigned long)str, .direction = direct_read };
      root_strategy->ops[0][opcode_trans]((void*)root_strategy, &args, "");
      if(args.success) {
	 printf("%s", str);
      }
    }
  bool cmd(addr_t addr, char * str, char * param)
    {
      struct args args = { .log_addr = addr, .log_len = strlen(str), .phys_addr = (unsigned long)str, .direction = direct_write };
      root_strategy->ops[0][opcode_trans]((void*)root_strategy, &args, param);
      return args.success;
    }
  addr_t boot(char * str, char * param)
    {
      struct args args = { .log_len = DEFAULT_TRANSFER, .reader = FALSE, .exclu = TRUE, .action = action_wait, .melt = TRUE, .try_len = DEFAULT_TRANSFER, .op_code = opcode_gadr };
      root_strategy->ops[0][opcode_gadr]((void*)root_strategy, &args, param);
      if(!args.success) {
        printf("!!!!! gadrcreateget failed\n");
	exit(-1);
      }
      args.log_len = strlen(str);
      args.phys_addr = (unsigned long)str;
      args.direction = direct_write;
      args.op_code = opcode_trans;
      root_strategy->ops[0][opcode_trans]((void*)root_strategy, &args, param);
      if(!args.success) {
        printf("!!!!! trans '%s' failed\n", str);
	exit(-1);
      }
      return args.log_addr;
    }
  char str[256];
  addr_t control = DEFAULT_TRANSFER;
  cmd(control, "output:=control\n", "");
  // basic level
#if 0
  addr_t dev = boot("brick:=device_dummy_linux\n output:=out", "testfile");
  sprintf(str, "brick:=buffer_dummy_linux\n \n connect dev:=%llx:out\n output:=out {\n", dev);
  addr_t buffer = boot(str, "");
  sprintf(str, "brick:=map_simple\n connect in:=%llx:out\noutput:=out", buffer);
#else
  sprintf(str, "brick:=map_dummy\n output:=out{\n");
#endif
  addr_t map = boot(str, "");
  sprintf(str, "brick:=adapt_meta\n connect in:=%llx:out\n output:=out\n", map);
  addr_t meta = boot(str, "");
#if 0
  sprintf(str, "brick:=spy_trace\n connect in:=%llx:out\n output:=out\n", meta);
  meta = boot(str, "spylog");
#endif
  // create root hook
  cmd(0, "output:=_root", "");
  cmd(meta, "connect hook:=0:_root", "");
  // strategy level
  sprintf(str, "brick:=fs_simple\n connect strat:=%llx:control\n output:=control{\n", control);
  addr_t fs = boot(str, "_root");
  // testing
  sprintf(str, "brick:=bench_fs\n connect strat:=%llx:control\n", fs);
  addr_t bench = boot(str, "");
#if 1
  ask(0);
  ask(DEFAULT_TRANSFER);
  ask(0x3000);
#endif
  printf("================== STARTING BENCH ================\n");
  cmd(bench, "output:=dummy", "1000");
  printf("================== END BENCH ================\n");
#ifdef MOVE_COUNT
  extern void print_counts(void);
  print_counts();
  printf("------------------------------------\n");
  printf("_makespace: shortcuts: %d count1: %d count2: %d\n", count_0, count_1, count_2);
  printf("creates (count_c1) = %d, triggering creates (count_c2) = %d\n", count_c1, count_c2);
#endif
  cmd(meta, "brick/=adapt_meta", "");
  cmd(map, "brick/=map_dummy", "");
#ifdef DEBUG
  close_debug();
#endif
  return 0;
}
Beispiel #18
0
/*main function*/
int main()
{
	int a = 0, b = 0,  c = 0;
	char input[length], color[length], correct = 'F', Q = 'T';
	char player[50];
	char victory,ans;
	int x = 0;
	
	do{	 
		print_score();  
		num++;
		if(x>0)/*only after one trial, then ask.*/
		{
			ans = ask();
			if(ans == 'N')
			{ 
				return 0;
			}
			else if( ans == 'Y')
			{
				printf("\tEnjoy the game. :)\n\n");
				system ("pause");
				system ("cls");
			}
			else
			{
				return 0;
			}
		}
		
		x=0;
		welcome();
		Info();
		
		printf("\n\n");
	
		RandGen(color);
	
		printf("\n");
		
		options();
		
		do
		{
			options1(x);
		
			for( a=0; a<length; a++)
			{
			
				ans = scan(input,a, color);
			
				if(ans == 'Q')
				{
					return 0;
				}
				else if(ans == 'I')
				{
					x--;
					break;
				}
			}
			
			x++;	
			
			victory = check1(input, color);
			check2(input, color);
		
			if(victory == 'T')
			{
				part[num].score = x;
				congrat();
				break;	  
			}
		
			c++;
			
			if(c == 20)
			{
				part[num].score = 9999;
				break;
			}
		}while(c < 21);
	}while(b = 1);
}	 
Beispiel #19
0
/*
    The ADIF function has been written according ADIF v1.00 specifications
    as shown on http://www.adif.org
    LZ3NY
*/
int write_adif(void)
{

    extern char logfile[];
    extern char exchange[];
    extern char whichcontest[];
    extern int exchange_serial;
    extern char modem_mode[];

    char buf[181] = "";
    char buffer[181] = "";
    char standardexchange[70] = "";
    char adif_tmp_name[40] = "";
    char adif_tmp_call[13] = "";
    char adif_tmp_str[2] = "";
    char adif_year_check[3] = "";
    char adif_rcvd_num[16] = "";
    char resultat[16];
    char adif_tmp_rr[5] = "";
    double freq;
    char freq_buf[16];

    int adif_mode_dep = 0;

    FILE *fp1, *fp2;

    if ((fp1 = fopen(logfile, "r")) == NULL) {
	info("Opening logfile not possible.");
	sleep(2);
	return (1);
    }
    strcpy(adif_tmp_name, whichcontest);
    strcat(adif_tmp_name, ".adi");

    if ((fp2 = fopen(adif_tmp_name, "w")) == NULL) {
	info("Opening ADIF file not possible.");
	sleep(2);
	fclose(fp1);		//added by F8CFE
	return (2);
    } 

    if (strlen(exchange) > 0)
	strcpy(standardexchange, exchange);

    /* in case using write_adif() without write_cabrillo() before
     * just ask for the needed information */
    if ((strlen(standardexchange) == 0) && (exchange_serial != 1)) {
	ask(buffer, "Your exchange (e.g. State, province, age etc... (# if serial number)): ");
	strncpy(standardexchange, buffer, 10);
    }

    info("Writing ADIF file");

    /* write header */
    fputs
	("################################################################################\n",
	 fp2);
    fputs
	("#                     ADIF v1.00 data file exported by TLF\n",
	 fp2);
    fputs
	("#              according to specifications on http://www.adif.org\n",
	 fp2);
    fputs("#\n", fp2);
    fputs
	("################################################################################\n",
	 fp2);
    fputs("<adif_ver:4>1.00\n<eoh>\n", fp2);

    while (fgets(buf, sizeof(buf), fp1)) {

	buffer[0] = '\0';

	if ((buf[0] != ';') && ((buf[0] != ' ') || (buf[1] != ' '))
	    && (buf[0] != '#') && (buf[0] != '\n') && (buf[0] != '\r')) {

/* CALLSIGN */
	    strcat(buffer, "<CALL:");
	    strncpy(adif_tmp_call, buf + 29, 12);
	    strcpy(adif_tmp_call, g_strstrip(adif_tmp_call));
	    snprintf(resultat, sizeof(resultat), "%zd",
		     strlen(adif_tmp_call));
	    strcat(buffer, resultat);
	    strcat(buffer, ">");
	    strcat(buffer, adif_tmp_call);

/* BAND */
	    if (buf[1] == '6')
		strcat(buffer, "<BAND:4>160M");
	    else if (buf[1] == '8')
		strcat(buffer, "<BAND:3>80M");
	    else if (buf[1] == '4')
		strcat(buffer, "<BAND:3>40M");
	    else if (buf[1] == '3')
		strcat(buffer, "<BAND:3>30M");
	    else if (buf[1] == '2')
		strcat(buffer, "<BAND:3>20M");
	    else if (buf[1] == '1' && buf[2] == '5')
		strcat(buffer, "<BAND:3>15M");
	    else if (buf[1] == '1' && buf[2] == '7')
		strcat(buffer, "<BAND:3>17M");
	    else if (buf[1] == '1' && buf[2] == '2')
		strcat(buffer, "<BAND:3>12M");
	    else if (buf[1] == '1' && buf[2] == '0')
		strcat(buffer, "<BAND:3>10M");

/* FREQ if available */
	    if (strlen(buf) > 81) {
		freq = atof(buf+80);
		freq_buf[0] = '\0';
		if ((freq > 1799.) && (freq < 10000.)) {
		    sprintf(freq_buf, "<FREQ:6>%.4f", freq/1000.);
		} else if (freq >= 10000.) {
		    sprintf(freq_buf, "<FREQ:7>%.4f", freq/1000.);
		}
		strcat(buffer, freq_buf);
	    }

/* QSO MODE */
	    if (buf[3] == 'C')
		strcat(buffer, "<MODE:2>CW");
	    else if (buf[3] == 'S')
		strcat(buffer, "<MODE:3>SSB");
	    else if (strcmp(modem_mode, "RTTY") == 0)
		strcat(buffer, "<MODE:4>RTTY");
	    else
		/* \todo DIGI is no allowed mode */
		strcat(buffer, "<MODE:4>DIGI");

/* QSO_DATE */
	    /* Y2K :) */
	    adif_year_check[0] = '\0';
	    strncpy(adif_year_check, buf + 14, 2);
	    if (atoi(adif_year_check) <= 70)
		strcat(buffer, "<QSO_DATE:8>20");
	    else
		strcat(buffer, "<QSO_DATE:8>19");

	    /* year */
	    strncat(buffer, buf + 14, 2);

	    /*month */
	    if (buf[10] == 'J' && buf[11] == 'a')
		strcat(buffer, "01");
	    if (buf[10] == 'F')
		strcat(buffer, "02");
	    if (buf[10] == 'M' && buf[12] == 'r')
		strcat(buffer, "03");
	    if (buf[10] == 'A' && buf[12] == 'r')
		strcat(buffer, "04");
	    if (buf[10] == 'M' && buf[12] == 'y')
		strcat(buffer, "05");
	    if (buf[10] == 'J' && buf[11] == 'u' && buf[12] == 'n')
		strcat(buffer, "06");
	    if (buf[10] == 'J' && buf[12] == 'l')
		strcat(buffer, "07");
	    if (buf[10] == 'A' && buf[12] == 'g')
		strcat(buffer, "08");
	    if (buf[10] == 'S')
		strcat(buffer, "09");
	    if (buf[10] == 'O')
		strcat(buffer, "10");
	    if (buf[10] == 'N')
		strcat(buffer, "11");
	    if (buf[10] == 'D')
		strcat(buffer, "12");

	    /*date */
	    strncat(buffer, buf + 7, 2);

/* TIME_ON */
	    strcat(buffer, "<TIME_ON:4>");
	    strncat(buffer, buf + 17, 2);
	    strncat(buffer, buf + 20, 2);

	    /* RS(T) flag */
	    if (buf[3] == 'S')		/* check for SSB */
		adif_mode_dep = 2;
	    else
		adif_mode_dep = 3;

/* RST_SENT */
	    strcat(buffer, "<RST_SENT:");
	    adif_tmp_str[1] = '\0';	/*       PA0R 02/10/2003  */
	    adif_tmp_str[0] = adif_mode_dep + 48;
	    strcat(buffer, adif_tmp_str);
	    strcat(buffer, ">");
	    strncat(buffer, buf + 44, adif_mode_dep);

/* STX - sent contest number */
	    strcat(buffer, "<STX:");

	    if ((exchange_serial == 1) || (standardexchange[0] == '#')) {
		strcat(buffer, "4>");
		strncat(buffer, buf + 23, 4);
	    } else {
		snprintf(resultat, sizeof(resultat), "%zd",
			 strlen(standardexchange));
		strcat(buffer, resultat);
		strcat(buffer, ">");
		strcat(buffer, g_strstrip(standardexchange));
	    }

/* RST_RCVD */
	    strncpy(adif_tmp_rr, buf + 49, 4);
	    strcpy(adif_tmp_rr, g_strstrip(adif_tmp_rr));
	    strcat(buffer, "<RST_RCVD:");
	    snprintf(resultat, sizeof(resultat), "%zd",
		     strlen(adif_tmp_rr));
	    strcat(buffer, resultat);
	    strcat(buffer, ">");
	    strncat(buffer, buf + 49, adif_mode_dep);

/* SRX - received contest number */
	    strncpy(adif_rcvd_num, buf + 54, 14);
	    strcpy(adif_rcvd_num, g_strstrip(adif_rcvd_num));
	    snprintf(resultat, sizeof(resultat), "%zd",
		     strlen(adif_rcvd_num));
	    strcat(buffer, "<SRX:");
	    strcat(buffer, resultat);
	    strcat(buffer, ">");
	    if (strcmp(buf + 54, " ") != 0)
		strcat(buffer, adif_rcvd_num);

/* <EOR> */
	    strcat(buffer, "<eor>\n");	//end of ADIF row

	    fputs(buffer, fp2);
	}
    }				// end fgets() loop

    fclose(fp1);
    fclose(fp2);

    return (0);
}				// end write_adif
Beispiel #20
0
static bool
plan_a(const char *filename)
{
	int		ifd, statfailed;
	char		*p, *s;
	struct stat	filestat;
	ptrdiff_t	sz;
	size_t		i;
	size_t		iline, lines_allocated;

#ifdef DEBUGGING
	if (debug & 8)
		return false;
#endif

	if (filename == NULL || *filename == '\0')
		return false;

	statfailed = stat(filename, &filestat);
	if (statfailed && ok_to_create_file) {
		if (verbose)
			say("(Creating file %s...)\n", filename);

		/*
		 * in check_patch case, we still display `Creating file' even
		 * though we're not. The rule is that -C should be as similar
		 * to normal patch behavior as possible
		 */
		if (check_only)
			return true;
		makedirs(filename, true);
		close(creat(filename, 0666));
		statfailed = stat(filename, &filestat);
	}
	if (statfailed)
		fatal("can't find %s\n", filename);
	filemode = filestat.st_mode;
	if (!S_ISREG(filemode))
		fatal("%s is not a normal file--can't patch\n", filename);
	if ((uint64_t)filestat.st_size > SIZE_MAX) {
		say("block too large to mmap\n");
		return false;
	}
	i_size = (size_t)filestat.st_size;
	if (out_of_mem) {
		set_hunkmax();	/* make sure dynamic arrays are allocated */
		out_of_mem = false;
		return false;	/* force plan b because plan a bombed */
	}
	if ((ifd = open(filename, O_RDONLY)) < 0)
		pfatal("can't open file %s", filename);

	if (i_size) {
		i_womp = mmap(NULL, i_size, PROT_READ, MAP_PRIVATE, ifd, 0);
		if (i_womp == MAP_FAILED) {
			perror("mmap failed");
			i_womp = NULL;
			close(ifd);
			return false;
		}
	} else {
		i_womp = NULL;
	}

	close(ifd);
	if (i_size)
		madvise(i_womp, i_size, MADV_SEQUENTIAL);

	/* estimate the number of lines */
	lines_allocated = i_size / 25;
	if (lines_allocated < 100)
		lines_allocated = 100;

	if (!reallocate_lines(&lines_allocated))
		return false;

	/* now scan the buffer and build pointer array */
	iline = 1;
	i_ptr[iline] = i_womp;
	/* test for NUL too, to maintain the behavior of the original code */
	for (s = i_womp, i = 0; i < i_size && *s != '\0'; s++, i++) {
		if (*s == '\n') {
			if (iline == lines_allocated) {
				if (!reallocate_lines(&lines_allocated))
					return false;
			}
			/* these are NOT NUL terminated */
			i_ptr[++iline] = s + 1;
		}
	}
	/* if the last line contains no EOL, append one */
	if (i_size > 0 && i_womp[i_size - 1] != '\n') {
		last_line_missing_eol = true;
		/* fix last line */
		sz = s - i_ptr[iline];
		p = malloc(sz + 1);
		if (p == NULL) {
			free(i_ptr);
			i_ptr = NULL;
			munmap(i_womp, i_size);
			i_womp = NULL;
			return false;
		}

		memcpy(p, i_ptr[iline], sz);
		p[sz] = '\n';
		i_ptr[iline] = p;
		/* count the extra line and make it point to some valid mem */
		i_ptr[++iline] = empty_line;
	} else
		last_line_missing_eol = false;

	input_lines = iline - 1;

	/* now check for revision, if any */

	if (revision != NULL) {
		if (i_womp == NULL || !rev_in_string(i_womp)) {
			if (force) {
				if (verbose)
					say("Warning: this file doesn't appear "
					    "to be the %s version--patching anyway.\n",
					    revision);
			} else if (batch) {
				fatal("this file doesn't appear to be the "
				    "%s version--aborting.\n",
				    revision);
			} else {
				ask("This file doesn't appear to be the "
				    "%s version--patch anyway? [n] ",
				    revision);
				if (*buf != 'y')
					fatal("aborted\n");
			}
		} else if (verbose)
			say("Good.  This file appears to be the %s version.\n",
			    revision);
	}
	return true;		/* plan a will work */
}
Beispiel #21
0
int main(int argc, char** argv)
{
  // in case generate shared memory to pointer area_addr
  // address work area
  char *area_addr = NULL; 

  // work area
  register int area_id=0;

  // ptr to current state entry
  register struct state *pState=NULL;

  // SIGSEGV state hold area func ptr
  void (*savefunc) ();

  // action to be performed
  register int action=0;
  while(0 != (action = ask())){
    if(0 < nap){
      fprintf(stderr, "currently attached segments");
      fprintf(stderr, " shm_id address\n");
      fprintf(stderr, "------- ---------\n");
      pState = &attached_segments[nap+1];
      while(--pState != attached_segments){
	fprintf(stderr, "%6d", pState->shm_id);
	fprintf(stderr, "%#11x", (unsigned int) pState->shm_addr);
	fprintf(stderr, " Read%s\n", (pState->shm_flag & SHM_RDONLY) ? "-Only" : "/Write");	
      }
      fprintf(stderr, "\n");

    }else{
      fprintf(stderr, "no segments are currently attached\n");      
      switch(action){
      case 1:
	// 1 - verify that there is space for another attach
	if(nap == MAXnap){
	  fprintf(stderr, "this simple example will only allow %d attached segments\n", MAXnap);
	  break;
	}
	// get the arguments, make the call, report the result and update the current state array
	pState = &attached_segments[++nap];

	readnumber(&pState->shm_id, ID_DIGITS, "enter shm_id of segment to attach:");
	readstring(pState->shm_addr, ADDR_DIGITS, "enter shm_addr");
	fprintf(stderr, "meaningful shm_flag vlaues are:\n");
	fprintf(stderr, "1\tSHM_RDONLY (%d)\n", SHM_RDONLY);
	fprintf(stderr, "2\tSHM_RND (%d)\n", SHM_RND);
	unsigned int select=0;
	unsigned int askagain=0;
	do{
	  askagain=0;
	  readdigit(&select, "select a shm_flag");
	  switch(select){
	  case 1:
	    puts("SHM_RDONLY");
	    pState->shm_flag = SHM_RDONLY;
	    break;

	  case 2:
	    puts("SHM_RND");
	    pState->shm_flag = SHM_RND;
	    break;

	  default:
	    puts("wrong input - try again");
	    askagain = 1;
	    break;
	  }
	}while(askagain);
	fprintf(stderr, "now attach the segment - shmat(%d, %#x, %#o)\n"
		, pState->shm_id, (unsigned int) pState->shm_addr, pState->shm_flag);

	if(0 > (pState->shm_addr = shmat(pState->shm_id, pState->shm_addr, pState->shm_flag))){
	  perror("shmat() failed");
	  --nap; // decrement, because already incremented above, for new pointer element!
	}else{
	  fprintf(stderr, "shmat returned %#8.8x\n", (unsigned int) pState->shm_addr);
	}
	break;
	
      case 2:
	// 2 - shmdt requested
	/*
	  get the address, make the call, report the results and make the 
	  internal state match
	//*/
	readstring(area_addr, ADDR_DIGITS, "enter detach shm_addr");
     	if(-1 == (area_id = shmdt(area_addr))){
	  perror("shmdt failed");
	}else{
	  fprintf(stderr, "shmdt returned %d\n", area_id);
	  for(pState = attached_segments, area_id = nap; --area_id; ++pState){
	    if(0 != (pState->shm_addr = area_addr)) 
	      *pState = attached_segments[--nap];
	  }
	}	
	break;
	
      case 3:
	if(nap == 0) break;
	
	readstring(area_addr, ADDR_DIGITS, "enter address of an attached segment");
	if(good_addr(area_addr))
	  fprintf(stderr, "string @ %#x is '%s'\n",(unsigned int) area_addr, area_addr);
	break;

      case 4:
	if(nap == 0) break;
	readstring(area_addr, ADDR_DIGITS, "enter address of an attached segment");
	
	/*
	  set up SIGSEGV signal handler to trap attempts to write into a read-only 
	  attached segment
	//*/
	savefunc = signal(SIGSEGV, signalhandler);

	if(setjmp(segvbuf)){
	  fprintf(stderr, "SIGSEGV signal caught: write aborted\n");
	  fflush(stdin); 
	  signal(SIGSEGV, savefunc);
	}else{
	  if(good_addr(area_addr)){
	    fflush(stdin);
	    readstring(area_addr, AREA_DIGITS, "enter one line to e copied to the shared segment attached");
	    // TODO: check
	    if(NULL == strncpy(pState->shm_addr, (char*) -1, sizeof(char*))){
	      perror("strncpy to shared memory failed");
	      break;
	    }
	  }
	}
	break;
      }
    }
  }

  // not reached
  puts("READY.");
  exit(EXIT_SUCCESS);
}
Beispiel #22
0
static void
plan_b(const char *filename)
{
	FILE	*ifp;
	size_t	i = 0, j, len, maxlen = 1;
	char	*lbuf = NULL, *p;
	bool	found_revision = (revision == NULL);

	using_plan_a = false;
	if ((ifp = fopen(filename, "r")) == NULL)
		pfatal("can't open file %s", filename);
	unlink(TMPINNAME);
	if ((tifd = open(TMPINNAME, O_EXCL | O_CREAT | O_WRONLY, 0666)) < 0)
		pfatal("can't open file %s", TMPINNAME);
	while ((p = fgetln(ifp, &len)) != NULL) {
		if (p[len - 1] == '\n')
			p[len - 1] = '\0';
		else {
			/* EOF without EOL, copy and add the NUL */
			if ((lbuf = malloc(len + 1)) == NULL)
				fatal("out of memory\n");
			memcpy(lbuf, p, len);
			lbuf[len] = '\0';
			p = lbuf;

			last_line_missing_eol = true;
			len++;
		}
		if (revision != NULL && !found_revision && rev_in_string(p))
			found_revision = true;
		if (len > maxlen)
			maxlen = len;   /* find longest line */
	}
	free(lbuf);
	if (ferror(ifp))
		pfatal("can't read file %s", filename);

	if (revision != NULL) {
		if (!found_revision) {
			if (force) {
				if (verbose)
					say("Warning: this file doesn't appear "
					    "to be the %s version--patching anyway.\n",
					    revision);
			} else if (batch) {
				fatal("this file doesn't appear to be the "
				    "%s version--aborting.\n",
				    revision);
			} else {
				ask("This file doesn't appear to be the %s "
				    "version--patch anyway? [n] ",
				    revision);
				if (*buf != 'y')
					fatal("aborted\n");
			}
		} else if (verbose)
			say("Good.  This file appears to be the %s version.\n",
			    revision);
	}
	fseek(ifp, 0L, SEEK_SET);	/* rewind file */
	tireclen = maxlen;
	tibuflen = maxlen > BUFFERSIZE ? maxlen : BUFFERSIZE;
	lines_per_buf = tibuflen / maxlen;
	tibuf[0] = malloc(tibuflen + 1);
	if (tibuf[0] == NULL)
		fatal("out of memory\n");
	tibuf[1] = malloc(tibuflen + 1);
	if (tibuf[1] == NULL)
		fatal("out of memory\n");
	for (i = 1;; i++) {
		p = tibuf[0] + maxlen * (i % lines_per_buf);
		if (i % lines_per_buf == 0)	/* new block */
			if (write(tifd, tibuf[0], tibuflen) !=
			    (ssize_t) tibuflen)
				pfatal("can't write temp file");
		if (fgets(p, maxlen + 1, ifp) == NULL) {
			input_lines = i - 1;
			if (i % lines_per_buf != 0)
				if (write(tifd, tibuf[0], tibuflen) !=
				    (ssize_t) tibuflen)
					pfatal("can't write temp file");
			break;
		}
		j = strlen(p);
		/* These are '\n' terminated strings, so no need to add a NUL */
		if (j == 0 || p[j - 1] != '\n')
			p[j] = '\n';
	}
	fclose(ifp);
	close(tifd);
	if ((tifd = open(TMPINNAME, O_RDONLY)) < 0)
		pfatal("can't reopen file %s", TMPINNAME);
}
Beispiel #23
0
int
readboot(int dosfs, struct bootblock *boot)
{
	u_char block[DOSBOOTBLOCKSIZE];
	u_char fsinfo[2 * DOSBOOTBLOCKSIZE];
	u_char backup[DOSBOOTBLOCKSIZE];
	int ret = FSOK;
	int i;
	
	if ((size_t)read(dosfs, block, sizeof block) != sizeof block) {
		perr("could not read boot block");
		return FSFATAL;
	}

	if (block[510] != 0x55 || block[511] != 0xaa) {
		pfatal("Invalid signature in boot block: %02x%02x",
		    block[511], block[510]);
		return FSFATAL;
	}

	memset(boot, 0, sizeof *boot);
	boot->ValidFat = -1;

	/* decode bios parameter block */
	boot->bpbBytesPerSec = block[11] + (block[12] << 8);
	boot->bpbSecPerClust = block[13];
	boot->bpbResSectors = block[14] + (block[15] << 8);
	boot->bpbFATs = block[16];
	boot->bpbRootDirEnts = block[17] + (block[18] << 8);
	boot->bpbSectors = block[19] + (block[20] << 8);
	boot->bpbMedia = block[21];
	boot->bpbFATsmall = block[22] + (block[23] << 8);
	boot->SecPerTrack = block[24] + (block[25] << 8);
	boot->bpbHeads = block[26] + (block[27] << 8);
	boot->bpbHiddenSecs = block[28] + (block[29] << 8) +
	    (block[30] << 16) + (block[31] << 24);
	boot->bpbHugeSectors = block[32] + (block[33] << 8) +
	    (block[34] << 16) + (block[35] << 24);

	boot->FATsecs = boot->bpbFATsmall;

	if (!boot->bpbRootDirEnts)
		boot->flags |= FAT32;
	if (boot->flags & FAT32) {
		boot->FATsecs = block[36] + (block[37] << 8)
				+ (block[38] << 16) + (block[39] << 24);
		if (block[40] & 0x80)
			boot->ValidFat = block[40] & 0x0f;

		/* check version number: */
		if (block[42] || block[43]) {
			/* Correct?				XXX */
			pfatal("Unknown file system version: %x.%x",
			       block[43], block[42]);
			return FSFATAL;
		}
		boot->bpbRootClust = block[44] + (block[45] << 8)
			       + (block[46] << 16) + (block[47] << 24);
		boot->bpbFSInfo = block[48] + (block[49] << 8);
		boot->bpbBackup = block[50] + (block[51] << 8);

		if (lseek(dosfs, boot->bpbFSInfo * boot->bpbBytesPerSec,
		    SEEK_SET) != boot->bpbFSInfo * boot->bpbBytesPerSec
		    || read(dosfs, fsinfo, sizeof fsinfo) != sizeof fsinfo) {
			perr("could not read fsinfo block");
			return FSFATAL;
		}
		if (memcmp(fsinfo, "RRaA", 4)
		    || memcmp(fsinfo + 0x1e4, "rrAa", 4)
		    || fsinfo[0x1fc]
		    || fsinfo[0x1fd]
		    || fsinfo[0x1fe] != 0x55
		    || fsinfo[0x1ff] != 0xaa
		    || fsinfo[0x3fc]
		    || fsinfo[0x3fd]
		    || fsinfo[0x3fe] != 0x55
		    || fsinfo[0x3ff] != 0xaa) {
			pwarn("Invalid signature in fsinfo block\n");
			if (ask(0, "Fix")) {
				memcpy(fsinfo, "RRaA", 4);
				memcpy(fsinfo + 0x1e4, "rrAa", 4);
				fsinfo[0x1fc] = fsinfo[0x1fd] = 0;
				fsinfo[0x1fe] = 0x55;
				fsinfo[0x1ff] = 0xaa;
				fsinfo[0x3fc] = fsinfo[0x3fd] = 0;
				fsinfo[0x3fe] = 0x55;
				fsinfo[0x3ff] = 0xaa;
				if (lseek(dosfs, boot->bpbFSInfo *
				    boot->bpbBytesPerSec, SEEK_SET)
				    != boot->bpbFSInfo * boot->bpbBytesPerSec
				    || write(dosfs, fsinfo, sizeof fsinfo)
				    != sizeof fsinfo) {
					perr("Unable to write bpbFSInfo");
					return FSFATAL;
				}
				ret = FSBOOTMOD;
			} else
				boot->bpbFSInfo = 0;
		}
		if (boot->bpbFSInfo) {
			boot->FSFree = fsinfo[0x1e8] + (fsinfo[0x1e9] << 8)
				       + (fsinfo[0x1ea] << 16)
				       + (fsinfo[0x1eb] << 24);
			boot->FSNext = fsinfo[0x1ec] + (fsinfo[0x1ed] << 8)
				       + (fsinfo[0x1ee] << 16)
				       + (fsinfo[0x1ef] << 24);
		}

		if (lseek(dosfs, boot->bpbBackup * boot->bpbBytesPerSec,
		    SEEK_SET)
		    != boot->bpbBackup * boot->bpbBytesPerSec
		    || read(dosfs, backup, sizeof backup) != sizeof  backup) {
			perr("could not read backup bootblock");
			return FSFATAL;
		}
		backup[65] = block[65];				/* XXX */
		if (memcmp(block + 11, backup + 11, 79)) {
			/*
			 * XXX We require a reference that explains
			 * that these bytes need to match, or should
			 * drop the check.  gdt@NetBSD has observed
			 * filesystems that work fine under Windows XP
			 * and NetBSD that do not match, so the
			 * requirement is suspect.  For now, just
			 * print out useful information and continue.
			 */
			pfatal("backup (block %d) mismatch with primary bootblock:\n",
			        boot->bpbBackup);
			for (i = 11; i < 11 + 90; i++) {
				if (block[i] != backup[i])
					pfatal("\ti=%d\tprimary 0x%02x\tbackup 0x%02x\n",
					       i, block[i], backup[i]);
			}
		}
		/* Check backup bpbFSInfo?					XXX */
	}

	boot->ClusterOffset = (boot->bpbRootDirEnts * 32 +
	    boot->bpbBytesPerSec - 1) / boot->bpbBytesPerSec +
	    boot->bpbResSectors + boot->bpbFATs * boot->FATsecs -
	    CLUST_FIRST * boot->bpbSecPerClust;

	if (boot->bpbBytesPerSec % DOSBOOTBLOCKSIZE != 0) {
		pfatal("Invalid sector size: %u", boot->bpbBytesPerSec);
		return FSFATAL;
	}
	if (boot->bpbSecPerClust == 0) {
		pfatal("Invalid cluster size: %u", boot->bpbSecPerClust);
		return FSFATAL;
	}
	if (boot->bpbSectors) {
		boot->bpbHugeSectors = 0;
		boot->NumSectors = boot->bpbSectors;
	} else
		boot->NumSectors = boot->bpbHugeSectors;
	boot->NumClusters = (boot->NumSectors - boot->ClusterOffset) /
	    boot->bpbSecPerClust;

	if (boot->flags&FAT32)
		boot->ClustMask = CLUST32_MASK;
	else if (boot->NumClusters < (CLUST_RSRVD&CLUST12_MASK))
		boot->ClustMask = CLUST12_MASK;
	else if (boot->NumClusters < (CLUST_RSRVD&CLUST16_MASK))
		boot->ClustMask = CLUST16_MASK;
	else {
		pfatal("Filesystem too big (%u clusters) for non-FAT32 partition",
		       boot->NumClusters);
		return FSFATAL;
	}

	switch (boot->ClustMask) {
	case CLUST32_MASK:
		boot->NumFatEntries = (boot->FATsecs * boot->bpbBytesPerSec) / 4;
		break;
	case CLUST16_MASK:
		boot->NumFatEntries = (boot->FATsecs * boot->bpbBytesPerSec) / 2;
		break;
	default:
		boot->NumFatEntries = (boot->FATsecs * boot->bpbBytesPerSec * 2) / 3;
		break;
	}

	if (boot->NumFatEntries < boot->NumClusters) {
		pfatal("FAT size too small, %u entries won't fit into %u sectors\n",
		       boot->NumClusters, boot->FATsecs);
		return FSFATAL;
	}
	boot->ClusterSize = boot->bpbBytesPerSec * boot->bpbSecPerClust;

	boot->NumFiles = 1;
	boot->NumFree = 0;

	return ret;
}
Beispiel #24
0
void CLineEdit::sNew()
{
  QString uiName="customer";
  ParameterList params;
  QMessageBox ask(this);
  ask.setIcon(QMessageBox::Question);
  QPushButton *pbutton = ask.addButton(tr("Prospect"), QMessageBox::YesRole);
  QPushButton *cbutton = ask.addButton(tr("Customer"), QMessageBox::YesRole);
  ask.setDefaultButton(cbutton);
  ask.setWindowTitle(tr("Customer or Prospect?"));

  if (_subtype == CRMAcctLineEdit::Prospect ||
      (_subtype == CRMAcctLineEdit::CustAndProspect &&
       !_x_privileges->check("MaintainCustomerMasters")))
  {
    params.append("mode", "new");
    uiName="prospect";
  }
  if (_subtype == CRMAcctLineEdit::CustAndProspect &&
       !_x_privileges->check("MaintainProspectMasters"))
    params.append("mode", "new");
  else
  {
    if (_subtype == CRMAcctLineEdit::Cust)
      ask.setText(tr("<p>Would you like to create a new Customer or convert "
                     "an existing Prospect?"));
    else
      ask.setText(tr("<p>Would you like to create a new Customer or "
                     "a new Prospect?"));

    ask.exec();

    if (ask.clickedButton() == pbutton &&
        _subtype == CRMAcctLineEdit::Cust)  // converting prospect
    {
      int prospectid = -1;
      if (_x_preferences->value("DefaultEllipsesAction") == "search")
      {
        CRMAcctSearch* search = new CRMAcctSearch(this);
        search->setSubtype(CRMAcctLineEdit::Prospect);
        prospectid = search->exec();
      }
      else
      {
        CRMAcctList* list = new CRMAcctList(this);
        list->setSubtype(CRMAcctLineEdit::Prospect);
        prospectid = list->exec();
      }

      if (prospectid > 0)
      {
        XSqlQuery convertq;
        convertq.prepare("SELECT convertProspectToCustomer(:id) AS result;");
        convertq.bindValue(":id", prospectid);
        convertq.exec();
        if (convertq.first())
        {
          int result = convertq.value("result").toInt();
          if (result < 0)
          {
            QMessageBox::critical(this, tr("Processing Error"),
                                  storedProcErrorLookup("convertProspectToCustomer", result));
            return;
          }
          params.append("cust_id", prospectid);
          params.append("mode", "edit");
        }
      }
      else
        return;
    }
    else
    {
      params.append("mode", "new");
      if (ask.clickedButton() == pbutton)
        uiName = "prospect";
    }
  }

  sOpenWindow(uiName, params);
}