Exemplo n.º 1
0
int main(int argc, char** argv) {

    int64 nside = 4096;
    double radius_arcsec = -1;
    int64 maxmatch=1;
    int print_dist=0;
    int verbose=0;

    const char* file = process_args(argc, argv, &nside, &radius_arcsec, 
                                    &maxmatch, &print_dist, &verbose);

    if (verbose) {
        if (radius_arcsec > 0)
            wlog("radius:    %0.1lf arcsec\n", radius_arcsec);
        wlog("nside:     %ld\n", nside);
        wlog("maxmatch:  %ld\n", maxmatch);
        wlog("file:      %s\n", file);
    }

    struct cat* cat = read_cat(file, nside, radius_arcsec, verbose);

    if (verbose) wlog("processing stream\n");

    struct matchstack* matches = matchstack_new();
    size_t index=0;
    double ra=0, dec=0;
    while (2 == fscanf(stdin,"%lf %lf", &ra, &dec)) {
        process_radec(cat, ra, dec, matches);
        print_matches(index, matches, maxmatch, print_dist);
        index++;
    }

    if (verbose) wlog("processed %lu from stream.\n", index);
}
Exemplo n.º 2
0
int dir_match(ToxWindow *self, Tox *m, const wchar_t *line, const wchar_t *cmd)
{
    char b_path[MAX_STR_SIZE];
    char b_name[MAX_STR_SIZE];
    char b_cmd[MAX_STR_SIZE];
    const wchar_t *tmpline = &line[wcslen(cmd) + 2];   /* start after "/command \"" */

    if (wcs_to_mbs_buf(b_path, tmpline, sizeof(b_path)) == -1)
        return -1;

    if (wcs_to_mbs_buf(b_cmd, cmd, sizeof(b_cmd)) == -1)
        return -1;

    if (b_path[0] == '~')
        complt_home_dir(self, b_path, sizeof(b_path), b_cmd, strlen(b_cmd) + 2);

    int si = char_rfind(b_path, '/', strlen(b_path));

    if (!b_path[0]) {    /* list everything in pwd */
        b_path[0] = '.';
        b_path[1] = '\0';
    } else if (!si && b_path[0] != '/') {    /* look for matches in pwd */
        char tmp[MAX_STR_SIZE];
        snprintf(tmp, sizeof(tmp), ".%s", b_path);
        snprintf(b_path, sizeof(b_path), "%s", tmp);
    }

    snprintf(b_name, sizeof(b_name), "%s", &b_path[si + 1]);
    b_path[si + 1] = '\0';
    int b_name_len = strlen(b_name);
    DIR *dp = opendir(b_path);

    if (dp == NULL)
        return -1;

    char dirnames[MAX_DIRS][NAME_MAX];
    struct dirent *entry;
    int dircount = 0;

    while ((entry = readdir(dp)) && dircount < MAX_DIRS) {
        if (strncmp(entry->d_name, b_name, b_name_len) == 0
                                && strcmp(".", entry->d_name) && strcmp("..", entry->d_name)) {
            snprintf(dirnames[dircount], sizeof(dirnames[dircount]), "%s", entry->d_name);
            ++dircount;
        }
    }

    closedir(dp);

    if (dircount == 0)
        return -1;

    if (dircount > 1) {
        qsort(dirnames, dircount, NAME_MAX, qsort_strcasecmp_hlpr);
        print_matches(self, m, dirnames, dircount, NAME_MAX);
    }

    return complete_line(self, dirnames, dircount, NAME_MAX);
}
Exemplo n.º 3
0
int
main(int argc, char **argv)
{
	char *p, *path;
	ssize_t pathlen;
	int opt, status;

	status = EXIT_SUCCESS;

	while ((opt = getopt(argc, argv, "as")) != -1) {
		switch (opt) {
		case 'a':
			allpaths = 1;
			break;
		case 's':
			silent = 1;
			break;
		default:
			usage();
			break;
		}
	}

	argv += optind;
	argc -= optind;

	if (argc == 0)
		usage();

	if ((p = getenv("PATH")) == NULL)
		exit(EXIT_FAILURE);
	pathlen = strlen(p) + 1;
	path = malloc(pathlen);
	if (path == NULL)
		err(EXIT_FAILURE, NULL);

	while (argc > 0) {
		memcpy(path, p, pathlen);
	
		if (strlen(*argv) >= FILENAME_MAX ||
		    print_matches(path, *argv) == -1)
			status = EXIT_FAILURE;

		argv++;
		argc--;
	}

	exit(status);
}
Exemplo n.º 4
0
int main(void)
{

    //char *input="$303,0,720P120\n";

    char *input = "$211,1.111,2.234234,+8.111\n";
if (initialize_message_validator() == 0){  //did everything initialize properly ?
    print_matches(input);
    terminate_message_validator();


}


}
Exemplo n.º 5
0
/* looks for all instances in list that begin with the last entered word in line according to pos,
   then fills line with the complete word. e.g. "Hello jo" would complete the line
   with "Hello john". If multiple matches, prints out all the matches and semi-completes line.

   list is a pointer to the list of strings being compared, n_items is the number of items
   in the list, and size is the size of each item in the list.

   Returns the difference between the old len and new len of line on success, -1 if error */
int complete_line(ToxWindow *self, const void *list, int n_items, int size)
{
    ChatContext *ctx = self->chatwin;

    if (ctx->pos <= 0 || ctx->len <= 0 || ctx->len >= MAX_STR_SIZE || size > MAX_STR_SIZE)
        return -1;

    const char *L = (char *) list;
    const char *endchrs = " ";
    char ubuf[MAX_STR_SIZE];

    /* work with multibyte string copy of buf for simplicity */
    if (wcs_to_mbs_buf(ubuf, ctx->line, sizeof(ubuf)) == -1)
        return -1;

    bool dir_search = strncmp(ubuf, "/sendfile", strlen("/sendfile")) == 0;

    /* isolate substring from space behind pos to pos */
    char tmp[MAX_STR_SIZE];
    snprintf(tmp, sizeof(tmp), "%s", ubuf);
    tmp[ctx->pos] = '\0';

    const char *s = dir_search ? strchr(tmp, '\"') : strrchr(tmp, ' ');
    char *sub = malloc(strlen(ubuf) + 1);

    if (sub == NULL)
        exit_toxic_err("failed in complete_line", FATALERR_MEMORY);

    if (!s && !dir_search) {
        strcpy(sub, tmp);

        if (sub[0] != '/')
            endchrs = ": ";
    } else if (s) {
        strcpy(sub, &s[1]);

        if (dir_search) {
            int sub_len = strlen(sub);
            int si = char_rfind(sub, '/', sub_len);

            if (si || *sub == '/')
                memmove(sub, &sub[si + 1], sub_len - si);
        }
    }

    if (string_is_empty(sub)) {
        free(sub);
        return -1;
    }

    int s_len = strlen(sub);
    const char *str;
    int n_matches = 0;
    char matches[n_items][MAX_STR_SIZE];
    int i = 0;

    /* put all list matches in matches array */
    for (i = 0; i < n_items; ++i) {
        str = &L[i * size];

        if (strncasecmp(str, sub, s_len) == 0)
            strcpy(matches[n_matches++], str);
    }

    free(sub);

    if (!n_matches)
        return -1;

    if (!dir_search && n_matches > 1)
        print_matches(self, NULL, matches, n_matches, MAX_STR_SIZE);

    char match[MAX_STR_SIZE];
    get_str_match(self, match, matches, n_matches);

    if (dir_search) {
        if (n_matches == 1)
            endchrs = char_rfind(match, '.', strlen(match)) ? "\"" : "/";
        else
            endchrs = "";
    } else if (n_matches > 1) {
        endchrs = "";
    }

    /* put match in correct spot in buf and append endchars */
    int n_endchrs = strlen(endchrs);
    int m_len = strlen(match);
    int strt = ctx->pos - s_len;
    int diff = m_len - s_len + n_endchrs;

    if (ctx->len + diff >= MAX_STR_SIZE)
        return -1;

    char tmpend[MAX_STR_SIZE];
    strcpy(tmpend, &ubuf[ctx->pos]);
    strcpy(&ubuf[strt], match);
    strcpy(&ubuf[strt + m_len], endchrs);
    strcpy(&ubuf[strt + m_len + n_endchrs], tmpend);

    /* convert to widechar and copy back to original buf */
    wchar_t newbuf[MAX_STR_SIZE];

    if (mbs_to_wcs_buf(newbuf, ubuf, MAX_STR_SIZE) == -1)
        return -1;

    wcscpy(ctx->line, newbuf);

    ctx->len += diff;
    ctx->pos += diff;

    return diff;
}
Exemplo n.º 6
0
main()
{
	char *sieve;
	int* prime_list;
	int pc = 0;
	int start = 100;
	int end = 1000;
	int i, j, k;
	int pri;
	int dig = 3;
	char prim[256];
	char patt[256];
	int len;
	int mc;
	int fm;
	int mr = 0;
	int maxmatch;
	int minmatch;
	int mixed;
	int dc = 1;
	sieve = malloc(2000000);
	int start_offs[10];

	populate();

	for (i = 0; i < 256; ++i) {
		patt[i] = 0;
		if (i < 10)
			start_offs[i] = 0;
	}

	prime_list = malloc(2000000 * sizeof(int));

	if (!sieve) {
		printf("malloc fail\n");
		exit(1);
	}

	fill_sieve(sieve, 2000000);

	for (i = 0; i < 2000000; ++i) {
		if (sieve[i]) {
			prime_list[pc++] = i;
			if (i > maxnum[dc]) {
				dc++;
				printf("%d is the first %d-digit prime\n", i, dc);
				start_offs[dc] = pc - 1;
			}
		}
	}

	printf("----------\n");

	++*patt;
	while (patt[7] == 0) {
		for (i = 0; i <= 7; ++i) {
			if (patt[i] > 11) {
				patt[i] = 1;
				++patt[i+1];
				if (patt[i+1] == 1)
					patt[i+1] = 2;
			}
		}

		if (*patt < 11 && *patt % 2 == 1)
			++*patt;
		if (*patt < 11 && *patt - 1 == 5)
			++*patt;

		len = 0;
		mixed = 0;
		for (i = 0; i <= 7; ++i) {
			if (patt[i] != 0)
				++len;
			if (patt[i] == 11)
				mixed = 1;
		}

		if (len && mixed) {
			mc = 0;
			fm = -1;
			maxmatch = biggest_match(patt, len);
			minmatch = smallest_match(patt, len);

			if (minmatch < minnum[len])
				minmatch = minnum[len];

			for (pri = start_offs[len]; pri < start_offs[len + 1]; ++pri) {
				if (prime_list[pri] > minmatch) {
					--pri;
					break;
				}
			}

			for (i = pri; prime_list[i] <= maxmatch; ++i) {
				if (match(patt, prime_list[i], len)) {
					if (fm == -1)
						fm = prime_list[i];
					++mc;
				}
			}
			if (mc && mc > mr) {
				mr = mc;
				printf("%d: %d matches ", fm, mc);
			
				if (mc == 8) {
					printf("\nThe matches are: ");
					print_matches(patt, sieve, len);
					printf("\n");
					printf("The pattern is: ");
					print_patt(patt, len);
					printf("\n");
					goto done;
				}
				printf("\n");
			}
		}
	
		++*patt;
	}		
		
	done:
	free(sieve);
}
Exemplo n.º 7
0
/*
 * Looks for all instances in list that begin with the last entered word in line according to pos,
 * then fills line with the complete word. e.g. "Hello jo" would complete the line
 * with "Hello john". If multiple matches, prints out all the matches and semi-completes line.
 *
 * list is a pointer to the list of strings being compared, n_items is the number of items
 * in the list, and size is the size of each item in the list.
 *
 * dir_search should be true if the line being completed is a file path.
 *
 * Returns the difference between the old len and new len of line on success.
 * Returns -1 on error.
 *
 * Note: This function should not be called directly. Use complete_line() and complete_path() instead.
 */
static int complete_line_helper(ToxWindow *self, const void *list, size_t n_items, size_t size, bool dir_search)
{
    ChatContext *ctx = self->chatwin;

    if (ctx->pos <= 0 || ctx->len <= 0 || ctx->pos > ctx->len) {
        return -1;
    }

    if (ctx->len >= MAX_STR_SIZE || size > MAX_STR_SIZE) {
        return -1;
    }

    const char *L = (const char *) list;
    const char *endchrs = " ";
    char ubuf[MAX_STR_SIZE] = {0};

    /* work with multibyte string copy of buf for simplicity */
    if (wcs_to_mbs_buf(ubuf, ctx->line, sizeof(ubuf)) == -1) {
        return -1;
    }

    /* isolate substring from space behind pos to pos */
    char tmp[MAX_STR_SIZE];
    snprintf(tmp, sizeof(tmp), "%s", ubuf);
    tmp[ctx->pos] = '\0';

    const char *s = dir_search ? strchr(tmp, ' ') : strrchr(tmp, ' ');
    char *sub = calloc(1, strlen(ubuf) + 1);

    if (sub == NULL) {
        exit_toxic_err("failed in complete_line_helper", FATALERR_MEMORY);
    }

    if (!s && !dir_search) {
        strcpy(sub, tmp);

        if (sub[0] != '/') {
            endchrs = ": ";
        }
    } else if (s) {
        strcpy(sub, &s[1]);

        if (dir_search) {
            int sub_len = strlen(sub);
            int si = char_rfind(sub, '/', sub_len);

            if (si || *sub == '/') {
                memmove(sub, &sub[si + 1], sub_len - si);
            }
        }
    }

    if (!sub[0]) {
        free(sub);
        return 0;
    }

    int s_len = strlen(sub);
    size_t n_matches = 0;
    char matches[n_items][MAX_STR_SIZE];
    int i = 0;

    /* put all list matches in matches array */
    for (i = 0; i < n_items; ++i) {
        char str[MAX_CMDNAME_SIZE + 1];
        snprintf(str, sizeof(str), "%s", &L[i * size]);

        if (strncasecmp(str, sub, s_len) == 0) {
            strcpy(matches[n_matches++], str);
        }
    }

    free(sub);

    if (!n_matches) {
        return -1;
    }

    if (!dir_search && n_matches > 1) {
        print_matches(self, NULL, matches, n_matches, MAX_STR_SIZE);
    }

    char match[MAX_STR_SIZE];
    size_t match_len = get_str_match(self, match, sizeof(match), matches, n_matches);

    if (match_len == 0) {
        return 0;
    }

    if (dir_search) {
        if (n_matches == 1) {
            endchrs = char_rfind(match, '.', match_len) ? "" : "/";
        } else {
            endchrs = "";
        }
    } else if (n_matches > 1) {
        endchrs = "";
    }

    /* put match in correct spot in buf and append endchars */
    int n_endchrs = strlen(endchrs);
    int strt = ctx->pos - s_len;
    int diff = match_len - s_len + n_endchrs;

    if (ctx->len + diff >= MAX_STR_SIZE) {
        return -1;
    }

    char tmpend[MAX_STR_SIZE];
    snprintf(tmpend, sizeof(tmpend), "%s", &ubuf[ctx->pos]);

    if (match_len + n_endchrs + strlen(tmpend) >= sizeof(ubuf)) {
        return -1;
    }

    strcpy(&ubuf[strt], match);

    /* If path points to a file with no extension don't append a forward slash */
    if (dir_search && *endchrs == '/') {
        const char *path_start = strchr(ubuf+1, '/');

        if (!path_start) {
            path_start = strchr(ubuf+1, ' ');

            if (!path_start) {
                return -1;
            }
        }

        if (strlen(path_start) < 2) {
            return -1;
        }

        ++path_start;

        if (file_type(path_start) == FILE_TYPE_REGULAR) {
            endchrs = "";
            diff -= n_endchrs;
        }
    }

    strcpy(&ubuf[strt + match_len], endchrs);
    strcpy(&ubuf[strt + match_len + n_endchrs], tmpend);

    /* convert to widechar and copy back to original buf */
    wchar_t newbuf[MAX_STR_SIZE];

    if (mbs_to_wcs_buf(newbuf, ubuf, sizeof(newbuf) / sizeof(wchar_t)) == -1) {
        return -1;
    }

    wcscpy(ctx->line, newbuf);

    ctx->len += diff;
    ctx->pos += diff;

    return diff;
}
Exemplo n.º 8
0
int fftMatch_gridded(char *inFile1, char *inFile2, char *gridFile,
                     float *avgLocX, float *avgLocY, float *certainty,
                     int size, double tol, int overlap)
{
  meta_parameters *meta1 = meta_read(inFile1);
  meta_parameters *meta2 = meta_read(inFile2);

  int nl = mini(meta1->general->line_count, meta2->general->line_count);
  int ns = mini(meta1->general->sample_count, meta2->general->sample_count);

  if (size<0) size = 512;
  if (overlap<0) overlap = 256;
  if (tol<0) tol = .28;

  asfPrintStatus("Tile size is %dx%d pixels\n", size, size);
  asfPrintStatus("Tile overlap is %d pixels\n", overlap);
  asfPrintStatus("Match tolerance is %.2f\n", tol);

  long long lsz = (long long)size;

  int num_x = (ns - size) / (size - overlap);
  int num_y = (nl - size) / (size - overlap);
  int len = num_x*num_y;

  asfPrintStatus("Number of tiles is %dx%d\n", num_x, num_y);

  offset_point_t *matches = MALLOC(sizeof(offset_point_t)*len); 

  int ii, jj, kk=0, nvalid=0;
  for (ii=0; ii<num_y; ++ii) {
    int tile_y = ii*(size - overlap);
    if (tile_y + size > nl) {
      if (ii != num_y - 1)
        asfPrintError("Bad tile_y: %d %d %d %d %d\n", ii, num_y, tile_y, size, nl);
      tile_y = nl - size;
    }
    for (jj=0; jj<num_x; ++jj) {
      int tile_x = jj*(size - overlap);
      if (tile_x + size > ns) {
        if (jj != num_x - 1)
          asfPrintError("Bad tile_x: %d %d %d %d %d\n", jj, num_x, tile_x, size, ns);
        tile_x = ns - size;
      }
      //asfPrintStatus("Matching tile starting at (L,S) (%d,%d)\n", tile_y, tile_x);
      char trim_append[64];
      sprintf(trim_append, "_chip_%05d_%05d", tile_y, tile_x);
      char *trim_chip1 = appendToBasename(inFile1, trim_append);
      char *trim_chip2 = appendToBasename(inFile2, trim_append);
      trim(inFile1, trim_chip1, (long long)tile_x, (long long)tile_y, lsz, lsz);
      trim(inFile2, trim_chip2, (long long)tile_x, (long long)tile_y, lsz, lsz);
      //char smooth_append[64];
      //sprintf(smooth_append, "_smooth_chip_%05d_%05d", tile_x, tile_y);
      //char *smooth_chip1 = appendToBasename(inFile1, smooth_append);
      //smooth(trim_chip1, smooth_chip1, 3, EDGE_TRUNCATE);
      float dx, dy, cert;
      int ok = fftMatchBF(trim_chip1, trim_chip2, &dx, &dy, &cert, tol);
      matches[kk].x_pos = tile_x;
      matches[kk].y_pos = tile_y;
      matches[kk].cert = cert;
      matches[kk].x_offset = dx;
      matches[kk].y_offset = dy;
      matches[kk].valid = ok && cert>tol;
      asfPrintStatus("%s: %5d %5d dx=%7.3f, dy=%7.3f, cert=%5.3f\n",
                     matches[kk].valid?"GOOD":"BAD ", tile_y, tile_x, dx, dy, cert);
      if (matches[kk].valid) ++nvalid;
      ++kk;
      //printf("%4.1f ", dx);
      removeImgAndMeta(trim_chip1);
      FREE(trim_chip1);
      removeImgAndMeta(trim_chip2);
      FREE(trim_chip2);
      //unlink(smooth_chip1);
      //FREE(smooth_chip1);
    }
    //printf("\n");
  }

  //print_matches(matches, num_x, num_y, stdout);

  asfPrintStatus("Removing grid offset outliers.\n");
  asfPrintStatus("Starting with %d offsets.\n", nvalid);

  int removed, iter=0;
  do {
    removed = remove_outliers(matches, len);
    if (removed > 0)
      asfPrintStatus("Iteration %d: Removed %d outliers\n", ++iter, removed);
  }
  while (removed > 0);
  asfPrintStatus("Finished removing outliers.\n");

  if (gridFile) {
    FILE *offset_fp = FOPEN(gridFile,"w");
    print_matches(matches, num_x, num_y, offset_fp);
    FCLOSE(offset_fp);
  }

  char *name = appendExt(inFile1, ".offsets.txt");
  FILE *fp = FOPEN(name, "w");

  int valid_points = 0;
  for (ii=0; ii<len; ++ii) {
    if (matches[ii].valid) {
      ++valid_points;
      if (fp) {
        fprintf(fp, "%5d %5d %14.5f %14.5f %14.5f\n",
                matches[ii].x_pos, matches[ii].y_pos,
                matches[ii].x_pos + matches[ii].x_offset,
                matches[ii].y_pos + matches[ii].y_offset,
                matches[ii].cert);
      }
    }
  }

  if (valid_points < 1) {
     asfPrintStatus("Too few points for a good match.\n");
  
     *avgLocX = 0;
     *avgLocY = 0;
     *certainty = 0;
  }
  else {
    *avgLocX = 0;
    *avgLocY = 0;
    *certainty = 0;
    int n = 0;
    for (ii=0; ii<len; ++ii) {
      if (matches[ii].valid) {
        *avgLocX += matches[ii].x_offset;
        *avgLocY += matches[ii].y_offset;
        *certainty += matches[ii].cert;
        ++n;
      }
    }

    *avgLocX /= (float)n;
    *avgLocY /= (float)n;
    //*certainty = (float)n / (float)len;
    *certainty /= (float)n;
  }

  asfPrintStatus("Found %d offsets.\n", valid_points);
  asfPrintStatus("Average tile offset: dx=%f, dy=%f, cert=%f\n",
                 *avgLocX, *avgLocY, *certainty);

  meta_free(meta1);
  meta_free(meta2);

  FCLOSE(fp);
  asfPrintStatus("Generated grid match file: %s\n", name);

  FREE(matches);
  FREE(name);

  return (0);
}
/*
 * complete command line
 */
static void tab_completion(struct command_completion_args *args)
{
	const char *name = args->typed;
	const int len = strlen(name);
	int i;
	int j;
	char prefix[128] = {0};
	int prefix_len = 0;
	int count = 0;
	const char *enum_name;

	for (i = 0; NULL != (enum_name = args->func(args->user, i)); ++i) {
		/* prefix does not match */
		if (strncmp(enum_name, name, len) != 0)
			continue;

		/* prefix matches first time */
		if (count++ == 0) {
			strcpy(prefix, enum_name);
			prefix_len = strlen(prefix);
			continue;
		}

		/*
		 * Prefix matches next time
		 * reduce prefix to common part
		 */
		for (j = 0; prefix[j] != 0
			&& prefix[j] == enum_name[j];)
			++j;
		prefix_len = j;
		prefix[j] = 0;
	}

	if (count == 0) {
		/* no matches */
		if (args->help != NULL)
			args->help(args);
		tab_hit_count = 0;
		return;
	}

	/* len == prefix_len => nothing new was added */
	if (len == prefix_len) {
		if (count != 1) {
			if (tab_hit_count == 1) {
				putchar('\a');
			} else if (tab_hit_count == 2 ||
					args->help == NULL) {
				print_matches(args->func,
						args->user, name, len);
			} else {
				args->help(args);
				tab_hit_count = 1;
			}
		} else if (count == 1) {
			/* nothing to add, exact match add space */
			terminal_insert_into_command_line(" ");
		}
	} else {
		/* new chars can be added from some interface name(s) */
		if (count == 1) {
			/* exact match, add space */
			prefix[prefix_len++] = ' ';
			prefix[prefix_len] = '\0';
		}

		terminal_insert_into_command_line(prefix + len);
		tab_hit_count = 0;
	}
}
Exemplo n.º 10
0
int main(int argc, char *argv[])
{
	opt_type opts;
	int sig_number;
#ifdef WITH_IPV6
	int ipv4_only, ipv6_only;
#endif
	unsigned char default_namespace = NAMESPACE_FILE;
	struct device_list *match_devices = NULL;
	struct unixsocket_list *unixsockets = NULL;
	struct mount_list *mounts = NULL;

	dev_t netdev;
	struct ip_connections *tcp_connection_list = NULL;
	struct ip_connections *udp_connection_list = NULL;
#ifdef WITH_IPV6
	struct ip6_connections *tcp6_connection_list = NULL;
	struct ip6_connections *udp6_connection_list = NULL;
#endif
	struct inode_list *match_inodes = NULL;
	struct names *names_head, *this_name, *names_tail;
	int argc_cnt;
    char *current_argv, *option;
    char option_buf[3];
    struct option *optr;
	char *nsptr;
  int skip_argv;

	struct option options[] = {
		{"all", 0, NULL, 'a'},
		{"kill", 0, NULL, 'k'},
		{"interactive", 0, NULL, 'i'},
		{"list-signals", 0, NULL, 'l'},
		{"mount", 0, NULL, 'm'},
		{"ismountpoint", 0, NULL, 'M'},
		{"namespace", 1, NULL, 'n'},
		{"silent", 0, NULL, 's'},
		{"user", 0, NULL, 'u'},
		{"verbose", 0, NULL, 'v'},
		{"version", 0, NULL, 'V'},
#ifdef WITH_IPV6
		{"ipv4", 0, NULL, '4'},
		{"ipv6", 0, NULL, '6'},
#endif
		{ 0, 0, 0, 0 }
	};

#ifdef WITH_IPV6
	ipv4_only = ipv6_only = 0;
#endif
	names_head = this_name = names_tail = NULL;
	opts = 0;
	sig_number = SIGKILL;

#ifdef ENABLE_NLS
	/* Set up the i18n */
	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);
#endif

	netdev = find_net_dev();
	fill_unix_cache(&unixsockets);

    for (argc_cnt = 1; argc_cnt < argc; argc_cnt++) {
      current_argv = argv[argc_cnt];
      if (current_argv[0] == '-') { /* its an option */
        if (current_argv[1] == '-') { /* its a long option */
          if (current_argv[2] == '\0')  /* -- */
            break;
          /* Parse the long options */
          option = option_buf;
          for (optr = options; optr->name != NULL; optr++) {
            if (strcmp(current_argv+2,optr->name) == 0) {
              sprintf(option_buf, "-%c", (char)optr->val);
              break;
            }
          }
          if (optr->name == NULL) {
			fprintf(stderr, _("%s: Invalid option %s\n"), argv[0],
				current_argv);
			usage(NULL);
          }
        } else {
          option = current_argv;
        }
        skip_argv=0;
        while (*(++option) != '\0' && !skip_argv) { /* skips over the - */
		  switch (*option) {
#ifdef WITH_IPV6
		  case '4':
			ipv4_only = 1;
			break;
		  case '6':
			ipv6_only = 1;
			break;
#endif /* WITH_IPV6 */
		  case 'a':
			opts |= OPT_ALLFILES;
			break;
		  case 'c':
			opts |= OPT_MOUNTS;
			break;
		  case 'f':
			/* ignored */
			break;
		  case 'h':
			usage(NULL);
			break;
		  case 'i':
			opts |= OPT_INTERACTIVE;
			break;
		  case 'k':
			opts |= OPT_KILL;
			break;
		  case 'l':
			list_signals();
			return 0;
		  case 'm':
			opts |= OPT_MOUNTS;
			break;
		  case 'M':
			opts |= OPT_ISMOUNTPOINT;
		    read_proc_mounts(&mounts);
			break;
		  case 'n':
            argc_cnt++;
            if (argc_cnt >= argc) {
              usage(_ ("Namespace option requires an argument."));
              exit(1);;
            }
            skip_argv=1;
            //while(option != '\0') option++;
			if (strcmp(argv[argc_cnt], "tcp") == 0)
				default_namespace = NAMESPACE_TCP;
			else if (strcmp(argv[argc_cnt], "udp") == 0)
				default_namespace = NAMESPACE_UDP;
			else if (strcmp(argv[argc_cnt], "file") == 0)
				default_namespace = NAMESPACE_FILE;
			else
				usage(_("Invalid namespace name"));
			break;
		  case 's':
			opts |= OPT_SILENT;
			break;
		  case 'u':
			opts |= OPT_USER;
			break;
		  case 'v':
			opts |= OPT_VERBOSE;
			break;
		  case 'V':
			print_version();
			return 0;
          default:
            if (isupper(*option) || isdigit(*option)) {
              sig_number = get_signal(current_argv+1, argv[0]);
            skip_argv=1;
              break;
            }
			fprintf(stderr, "%s: Invalid option %c\n", argv[0],
				*option);
			usage(NULL);
			exit(1);
			break;
		  }		/* switch */
	    }			/* while option */
        continue;
      } /* an option */
      /* Not an option, must be a file specification */

		if ((this_name = malloc(sizeof(struct names))) == NULL)
			continue;
		this_name->next = NULL;
		/* try to find namespace spec */
		this_name->name_space = default_namespace;
		if (((nsptr = strchr(current_argv, '/')) != NULL)
		    && (nsptr != current_argv)) {
			if (strcmp(nsptr + 1, "tcp") == 0) {
				this_name->name_space = NAMESPACE_TCP;
				*nsptr = '\0';
			} else if (strcmp(nsptr + 1, "udp") == 0) {
				this_name->name_space = NAMESPACE_UDP;
				*nsptr = '\0';
			} else if (strcmp(nsptr + 1, "file") == 0) {
				this_name->name_space = NAMESPACE_FILE;
				*nsptr = '\0';
			}
		}
		this_name->matched_procs = NULL;
		if (opts & (OPT_MOUNTS|OPT_ISMOUNTPOINT)
		    && this_name->name_space != NAMESPACE_FILE)
			usage(_
			      ("You can only use files with mountpoint options"));
		if (opts & OPT_ISMOUNTPOINT &&
		    !is_mountpoint(&mounts, current_argv)) {
			free(this_name);
			continue;
		}
		switch (this_name->name_space) {
		case NAMESPACE_TCP:
			if (asprintf(&(this_name->filename), "%s/tcp", current_argv) > 0) {
#ifdef WITH_IPV6
			  parse_inet(this_name, ipv4_only, ipv6_only,
				   &tcp_connection_list, &tcp6_connection_list);
#else
			  parse_inet(this_name, &tcp_connection_list);
#endif
			}
			break;
		case NAMESPACE_UDP:
			if (asprintf(&(this_name->filename), "%s/udp", current_argv) > 0) {
#ifdef WITH_IPV6
			  parse_inet(this_name, ipv4_only, ipv6_only,
				   &udp_connection_list, &udp6_connection_list);
#else
			  parse_inet(this_name, &udp_connection_list);
#endif
			}
			break;
		default:	/* FILE */
			this_name->filename = strdup(current_argv);
			if (parse_file(this_name, &match_inodes) == 0) {
              parse_unixsockets(this_name, &match_inodes, unixsockets);
			  if (opts & OPT_MOUNTS)
				parse_mounts(this_name, &match_devices, opts);
            }
			break;
		}

		if (names_head == NULL)
			names_head = this_name;
		if (names_tail != NULL)
			names_tail->next = this_name;
		names_tail = this_name;
    } /* for across the argvs */
	if (names_head == NULL)
		usage(_("No process specification given"));

	if (opts & OPT_SILENT) {
		opts &= ~OPT_VERBOSE;
		opts &= ~OPT_USER;
		if (opts & OPT_ALLFILES)
			usage(_
			      ("all option cannot be used with silent option."));
	}
#ifdef WITH_IPV6
	if (ipv4_only && ipv6_only)
		usage(_
		      ("You cannot search for only IPv4 and only IPv6 sockets at the same time"));
	if (!ipv6_only) {
#endif
		if (tcp_connection_list != NULL)
			find_net_sockets(&match_inodes, tcp_connection_list,
					 "tcp", netdev);
		if (udp_connection_list != NULL)
			find_net_sockets(&match_inodes, udp_connection_list,
					 "udp", netdev);
#ifdef WITH_IPV6
	}
	if (!ipv4_only) {
		if (tcp6_connection_list != NULL)
			find_net6_sockets(&match_inodes, tcp6_connection_list,
					  "tcp", netdev);
		if (udp6_connection_list != NULL)
			find_net6_sockets(&match_inodes, udp6_connection_list,
					  "udp", netdev);
	}
#endif
#ifdef DEBUG
	debug_match_lists(names_head, match_inodes, match_devices);
#endif
	scan_procs(names_head, match_inodes, match_devices, unixsockets,
		   netdev);
	scan_knfsd(names_head, match_inodes, match_devices);
	scan_mounts(names_head, match_inodes, match_devices);
	scan_swaps(names_head, match_inodes, match_devices);
	return print_matches(names_head, opts, sig_number);
}
Exemplo n.º 11
0
Arquivo: main.c Projeto: zayac/eq
int
main (int argc, char *argv[])
{
  int c, ret = 0;
  char *subopts;
  char *value;
  char *src_name = NULL;
  extern char *optarg;
  extern int optind;

  struct eq_lexer *lex = (struct eq_lexer *) malloc (sizeof (struct eq_lexer));
  struct eq_parser *parser = (struct eq_parser *) malloc (sizeof (struct eq_parser));

  init_global ();
  init_global_tree ();
  init_options ();

  progname = strrchr (argv[0], '/');
  if (NULL == progname)
    progname = argv[0];
  else
    progname++;

  while (-1 != (c = getopt (argc, argv, "B:P:V")))
    switch (c)
      {
      case 'P':
	subopts = optarg;
	while (*subopts != '\0')
	  switch (getsubopt (&subopts, p_opts, &value))
	    {
	    case OPT_PRINT_PROGRAM:
	      options.print_program = true;
	      break;
	    case OPT_PRINT_MATCHES:
	      options.print_matches = true;
	      break;
	    case OPT_PRINT_TYPES:
	      options.print_types = true;
	      break;
	    default:
	      fprintf (stderr, "unknown -P suboption `%s'\n", value);
	      goto cleanup;
	      break;
	    }
	break;
      case 'B':
	subopts = optarg;
	while (*subopts != '\0')
	  switch (getsubopt (&subopts, b_opts, &value))
	    {
	    case OPT_BREAK_PARSER:
	      options.break_option = break_parser;
	      break;
	    case OPT_BREAK_TYPECHECK:
	      options.break_option = break_typecheck;
	      break;
	    case OPT_BREAK_CONTROLFLOW:
	      options.break_option = break_controlflow;
	    case OPT_BREAK_DATAFLOW:
	      options.break_option = break_dataflow;
	      break;
	    default:
	      fprintf (stderr, "unknown -B suboption `%s'\n", value);
	      goto cleanup;
	      break;
	    }
	break;
      case 'V':
	version ();
	goto cleanup;
      default:
	usage ();
	goto cleanup;
      }

  if (options.print_types
      && !(options.print_program || options.print_matches))
    fprintf (stderr, "warning: 'types' flag is useless without either "
	     "'program' flag or 'matches' flag\n");

  argv += optind;

  /* FIXME: What if we have multiple files?  */
  if (NULL == *argv)
    {
      fprintf (stderr, "%s:error: filename argument required\n", progname);
      usage ();
      ret = -1;
      goto cleanup;
    }

  /* Initialize the lexer.  */
  if (!eq_lexer_init (lex, *argv))
    {
      fprintf (stderr, "%s cannot create a lexer for file `%s'\n", progname,
	       *argv);
      ret = -2;
      goto cleanup;
    }
  else
    {
      /* Discard extension from file to compile.  */
      char* start = strrchr (*argv, '/');
      char* ext = strrchr (*argv, '.');
      int size = 0;
      
      if (start == NULL)
	start = *argv;
      else
	start += 1;
      if (ext == NULL)
	size = strlen(start);
      else
	size = ext - start;
      src_name = strndup (start, size);
    }


  /* Initialize the parser.  */
  eq_parser_init (parser, lex);

  if ((ret += eq_parse (parser)) == 0 && options.break_option != break_parser)
    ret += typecheck ();

  /* printing debug routine.  */
  if (options.print_program)
    {
      xfile *  xf = xfile_init_file_stdout ();

      printf ("\n######### Output ########\n");

      print_program (xf);

      xfile_finalize (xf);
    }

  if (options.print_matches)
    {
      printf ("\n####### Transforms ########\n");
      print_matches ();
    }
 
  if (options.break_option != break_typecheck
   && options.break_option != break_parser && !ret)
    controlflow ();

  if (options.break_option != break_controlflow
   && options.break_option != break_typecheck
   && options.break_option != break_parser && !ret)
    dataflow ();

  if (options.break_option != break_dataflow
   && options.break_option != break_controlflow
   && options.break_option != break_typecheck
   && options.break_option != break_parser && !ret)
    codegen (src_name);
  printf ("note: finished compiling.\n");

  free (src_name);
cleanup:
  eq_parser_finalize (parser);
  finalize_global_tree ();
  finalize_global ();

  /* That should be called at the very end.  */
  free_atomic_trees ();

  if (parser)
    free (parser);
  if (lex)
    free (lex);

  return ret == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
}
Exemplo n.º 12
0
int
main(int argc, char **argv)
{
        register int ch;
        char **dbv = NULL;
#ifdef MMAP
        f_mmap = 1;		/* mmap is default */
#endif
	(void) setlocale(LC_ALL, "");

        while ((ch = getopt(argc, argv, "Scd:il:ms")) != -1)
                switch(ch) {
                case 'S':	/* statistic lines */   
                        f_statistic = 1;
                        break;
                case 'l': /* limit number of output lines, 0 == infinite */
                        f_limit = atoi(optarg);
                        break;
                case 'd':	/* database */
                        dbv = colon(dbv, optarg, _PATH_FCODES);
                        break;
                case 'i':	/* ignore case */
                        f_icase = 1;
                        break;
                case 'm':	/* mmap */
#ifdef MMAP
                        f_mmap = 1;
#else
						warnx("mmap(2) not implemented");
#endif
                        break;
                case 's':	/* stdio lib */
                        f_mmap = 0;
                        break;
                case 'c': /* suppress output, show only count of matches */
                        f_silent = 1;
                        break;
                default:
                        usage();
                }
        argv += optind;
        argc -= optind;

        /* to few arguments */
        if (argc < 1 && !(f_statistic))
                usage();

        /* no (valid) database as argument */
        if (dbv == NULL || *dbv == NULL) {
                /* try to read database from environment */
                if ((path_fcodes = getenv("LOCATE_PATH")) == NULL ||
		     *path_fcodes == '\0')
                        /* use default database */
                        dbv = colon(dbv, _PATH_FCODES, _PATH_FCODES);
                else		/* $LOCATE_PATH */
                        dbv = colon(dbv, path_fcodes, _PATH_FCODES);
        }

        if (f_icase && UCHAR_MAX < 4096) /* init tolower lookup table */
                for (ch = 0; ch < UCHAR_MAX + 1; ch++)
                        myctype[ch] = tolower(ch);

        /* foreach database ... */
        while((path_fcodes = *dbv) != NULL) {
                dbv++;

                if (!strcmp(path_fcodes, "-"))
                        f_stdin = 1;
		else
			f_stdin = 0;

#ifndef MMAP
		f_mmap = 0;	/* be paranoid */
#endif
                if (!f_mmap || f_stdin || f_statistic) 
			search_fopen(path_fcodes, argv);
                else 
			search_mmap(path_fcodes, argv);
        }

        if (f_silent)
                print_matches(counter);
        exit(0);
}