示例#1
0
文件: isakmpd.c 项目: ebichu/dd-wrt
/* Report internal state on SIGUSR1.  */
static void
report (void)
{
  FILE *rfp, *old;
  mode_t old_umask;

  old_umask = umask (S_IRWXG | S_IRWXO);
  rfp = monitor_fopen (report_file, "w");
  umask (old_umask);

  if (!rfp)
    {
      log_error ("fopen (\"%s\", \"w\") failed", report_file);
      return;
    }

  /* Divert the log channel to the report file during the report.  */
  old = log_current ();
  log_to (rfp);
  ui_report ("r");
  log_to (old);
  fclose (rfp);

  sigusr1ed = 0;
}
示例#2
0
//---------------------------------------------------------------------------
void PortsOpenAll()
{
#ifndef ONEGAME
  Str ErrorText,ErrorTitle;
  log_to(LOGSECTION_INIT,"STARTUP: Opening MIDIPort");
  MIDIPort.Create(ErrorText,ErrorTitle,true);
  log_to(LOGSECTION_INIT,"STARTUP: Opening ParallelPort");
  ParallelPort.Create(ErrorText,ErrorTitle,true);
  log_to(LOGSECTION_INIT,"STARTUP: Opening SerialPort");
  SerialPort.Create(ErrorText,ErrorTitle,true);
  log_to(LOGSECTION_INIT,"STARTUP: SerialPort opened");
#ifdef UNIX
	UNIX_ONLY( XGUIUpdatePortDisplay(); )
#endif
#endif
}
示例#3
0
/* This function is where the privileged process waits(loops) indefinitely.  */
void
monitor_loop(int debug)
{
	int	 msgcode;

	if (!debug)
		log_to(0);

	for (;;) {
		must_read(&msgcode, sizeof msgcode);

		switch (msgcode) {
		case MONITOR_GET_FD:
			m_priv_getfd();
			break;

		case MONITOR_PFKEY_OPEN:
			LOG_DBG((LOG_MISC, 80,
			    "monitor_loop: MONITOR_PFKEY_OPEN"));
			m_priv_pfkey_open();
			break;

		case MONITOR_SETSOCKOPT:
			LOG_DBG((LOG_MISC, 80,
			    "monitor_loop: MONITOR_SETSOCKOPT"));
			m_priv_setsockopt();
			break;

		case MONITOR_BIND:
			LOG_DBG((LOG_MISC, 80,
			    "monitor_loop: MONITOR_BIND"));
			m_priv_bind();
			break;

		case MONITOR_REQ_READDIR:
			LOG_DBG((LOG_MISC, 80,
			    "monitor_loop: MONITOR_REQ_READDIR"));
			m_priv_req_readdir();
			break;

		case MONITOR_INIT_DONE:
			LOG_DBG((LOG_MISC, 80,
			    "monitor_loop: MONITOR_INIT_DONE"));
			break;

		case MONITOR_SHUTDOWN:
			LOG_DBG((LOG_MISC, 80,
			    "monitor_loop: MONITOR_SHUTDOWN"));
			break;

		default:
			log_print("monitor_loop: got unknown code %d",
			    msgcode);
		}
	}

	exit(0);
}
示例#4
0
void test_log_func(CuTest* tc) {
    log_init(LOG_VERB);

    teststruc_t ts;
    ts.magic = 42;
    log_use_function(logfunc, &ts);
    log_to(NULL);

    logmsg("Testing 1 2 3\n");
    logdebug("Testing 1 2 3\n");

    log_use_function(NULL, NULL);
    log_to(stdout);

    logmsg("Testing 1 2 3 4\n");
    logdebug("Testing 1 2 3 4\n");

}
示例#5
0
void* thread2(void* v) {
    FILE* flog = v;
    logmsg("I'm thread 2.\n");
    log_set_level(LOG_VERB);
    log_to(flog);
    logmsg("%s\n", STRING2A);
    logverb("%s\n", STRING2B);
    return NULL;
}
示例#6
0
void* thread1(void* v) {
    FILE* flog = v;
    logmsg("I'm thread 1.\n");
    log_set_level(LOG_MSG);
    log_to(flog);
    logmsg("%s\n", STRING1A);
    sleep(1);
    logverb("%s\n", STRING1B);
    return NULL;
}
示例#7
0
int
main (int argc, char **argv, char **envp)
{
  set_identity (argv[0]);
  log_to (LOGTO_STDERR);

  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

  parse_options (argc, argv, envp);

  if (show_version)
    {
      printf (_("%s version %s (built %s %s, protocol version %d.%d)\n"), get_identity (),
              VERSION, __DATE__, __TIME__, PROTOCOL_MAJOR, PROTOCOL_MINOR);
      printf (_("Built with kernel interface %s/%s.\n"), IFTYPE, IFSUBTYPE);
      printf (_
              ("Copyright (C) 2003-2008 Marc Lehmann <*****@*****.**> and others.\n"
               "See the AUTHORS file for a complete list.\n\n"
               "vpe comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
               "and you are welcome to redistribute it under certain conditions;\n"
               "see the file COPYING for details.\n"));

      return 0;
    }

  if (show_help)
    usage (0);

  {
    configuration_parser (conf, false, 0, 0);
  }

  if (generate_keys)
    {
      RAND_load_file ("/dev/urandom", 1024);
      exit (keygen (generate_keys));
    }

  if (kill_gvpe)
    exit (kill_other (kill_gvpe));

  if (show_config)
    {
      conf.print ();
      exit (EXIT_SUCCESS);
    }

  usage (1);
}
示例#8
0
文件: tc.c 项目: copton/ocram
void receive_run(const char* channel, const char* file)
{
    int socket = os_listen(channel);
    int log = os_flash_open(file, WRITE);
    while (true) {
        uint8_t buffer[10];
        size_t len;

		while(tc_receive(socket, buffer, sizeof(buffer), &len) != SUCCESS);
        len -= len % sizeof(int32_t);

		log_to(log, buffer, len);
    }
}
示例#9
0
void receive_run(const char* channel, const char* file)
{
    void* receive_handle = receive_wire(channel);
    void* logw_handle = logw_wire(file);
    while (true) {
        net_message_t msg;
        void* payload;
        uint8_t len;

		error_t res = receive_receive(receive_handle, &msg, &payload, &len);
		assert (res == SUCCESS);

		log_to(logw_handle, payload, len);
    }
}
示例#10
0
文件: tc.c 项目: copton/ocram
void collect_run(const char* device, const char* file, unsigned dt)
{
    int sensor = os_sensor_open(device);
    int log = os_flash_open(file, WRITE);

    uint32_t now = os_now();
    while (true) {
        tc_sleep(now + dt);
        now += dt;

        sensor_val_t val;
		while (tc_sensor_read(sensor, &val) != SUCCESS);

        log_to(log, (uint8_t*)&val, sizeof(sensor_val_t));
    }
}
示例#11
0
文件: main.cpp 项目: Ryuuke/desperion
int main(int argc, const char ** argv)
{
    std::cout << "starting desperion" << std::endl;
    logger::create();
#ifndef DEBUG
    statistics_center::create(LOGIN_VERSION_MAJOR, LOGIN_VERSION_MINOR, LOGIN_VERSION_RELEASE);
#endif
    try {
        while (application::create().run(argc, argv) == shutdown_type::REBOOT)
            application::kill();
    } catch (const std::exception & e) {
        utils::color<utils::TRED>(std::cout) << "an error occured, please see log files"
            << utils::cendl;
        log_to("error") << "unhandled exception: " << e.what() << "\n";
    }
    return 0;
}
示例#12
0
/*---------------------------------------------------------------------------*/
void dma_sound_set_control(BYTE io_src_b)
{
  if ((dma_sound_control & BIT_0) && (io_src_b & BIT_0)==0){  //Stopping
    dma_sound_start=next_dma_sound_start;
    dma_sound_end=next_dma_sound_end;
    dma_sound_fetch_address=dma_sound_start;
  }else if ((dma_sound_control & BIT_0)==0 && (io_src_b & BIT_0)){ //Start playing
    dma_sound_start=next_dma_sound_start;
    dma_sound_end=next_dma_sound_end;
    dma_sound_fetch_address=dma_sound_start;
    if (dma_sound_on_this_screen==0){
      // Pad buffer with last byte from VBL to current position
      bool Mono=bool(dma_sound_mode & BIT_7);
      int freq_idx=0;
      if (shifter_freq_at_start_of_vbl==60) freq_idx=1;
      if (shifter_freq_at_start_of_vbl==MONO_HZ) freq_idx=2;
      WORD w1,w2;
      dma_sound_get_last_sample(&w1,&w2);
      for (int y=-scanlines_above_screen[freq_idx];y<scan_y;y++){
        if (Mono){  //play half as many words
          dma_sound_samples_countdown+=dma_sound_freq*scanline_time_in_cpu_cycles_at_start_of_vbl/2;
        }else{ //stereo, 1 word per sample
          dma_sound_samples_countdown+=dma_sound_freq*scanline_time_in_cpu_cycles_at_start_of_vbl;
        }
        int loop=int(Mono ? 2:1);
        while (dma_sound_samples_countdown>=0){
          for (int i=0;i<loop;i++){
            dma_sound_output_countdown+=sound_freq;
            while (dma_sound_output_countdown>=0){
              if (dma_sound_channel_buf_last_write_t>=DMA_SOUND_BUFFER_LENGTH) break;
              dma_sound_channel_buf[dma_sound_channel_buf_last_write_t++]=w1;
              dma_sound_channel_buf[dma_sound_channel_buf_last_write_t++]=w2;
              dma_sound_output_countdown-=dma_sound_freq;
            }
          }
          dma_sound_samples_countdown-=n_cpu_cycles_per_second;
        }
      }
      dma_sound_on_this_screen=1;
    }
  }
  log_to(LOGSECTION_SOUND,EasyStr("SOUND: ")+HEXSl(old_pc,6)+" - DMA sound control set to "+(io_src_b & 3)+" from "+(dma_sound_control & 3));
  dma_sound_control=io_src_b;
  if (tos_version>=0x106) mfp_gpip_set_bit(MFP_GPIP_MONO_BIT,bool(COLOUR_MONITOR)^bool(dma_sound_control & BIT_0));
}
示例#13
0
void collect_run(const char* sensor, const char* file, unsigned dt)
{
    void* sensor_handle = sensor_wire(sensor);
    void* logw_handle = logw_wire(file);
	void* timer_handle = timer_wire();

    uint32_t now = timer_getNow(timer_handle);
    while (true) {
        timer_sleep(timer_handle, now + dt);
        now += dt;

        sensor_val_t val;
		error_t res = sensor_read(sensor_handle, &val);
		assert (res == SUCCESS);

        log_to(logw_handle, &val, sizeof(sensor_val_t));
    }
}
示例#14
0
/**
 * 2015-08-10
 * see: http://www.gnu.org/software/libc/manual/html_node/Termination-in-Handler.html#Termination-in-Handler 
 */
void sig_handler(int sig)
{ 
    /* Since this handler is established for more than one kind of signal, it might still 
     * get invoked recursively by delivery of some other kind of signal.  Use a static 
     * variable to keep track of that. 
     */
    if (fatal_error_in_progress != 0) {
	(void)raise(sig);
    }

    fatal_error_in_progress = 1;
    psignal(sig, "Auto shutdown invoked.");
    log_bug("Critical signal received %d", sig);
    log_to(LOG_SINK_LASTCMD, "%s", globalSystemState.last_command);
    auto_shutdown();

    /* Now reraise the signal. We reactivate the signal’s default handling, which is to 
     * terminate the process. We could just call exit or abort,  but reraising the signal 
     * sets the return status from the process correctly, and, more importantly, gives us
     * a core dump.
     */
    (void)signal(sig, SIG_DFL);
    (void)raise(sig);
}
示例#15
0
int main(int argc, char** args) {
    int c;
    char* wcsfn = NULL;
    char* outfn = NULL;
    char* infn = NULL;
    sip_t sip;
    double scale = 1.0;
    anbool pngformat = TRUE;

    char* hdpath = NULL;
    anbool HD = FALSE;

    cairos_t thecairos;
    cairos_t* cairos = &thecairos;

    cairo_surface_t* target = NULL;
    cairo_t* cairot = NULL;

    cairo_surface_t* surfbg = NULL;
    cairo_t* cairobg = NULL;

    cairo_surface_t* surfshapes = NULL;
    cairo_t* cairoshapes = NULL;

    cairo_surface_t* surfshapesmask = NULL;
    cairo_t* cairoshapesmask = NULL;

    cairo_surface_t* surffg = NULL;
    cairo_t* cairo = NULL;

    double lw = 2.0;
    // circle linewidth.
    double cw = 2.0;

    double ngc_fraction = 0.02;

    // NGC linewidth
    double nw = 2.0;

    // leave a gap short of connecting the points.
    double endgap = 5.0;
    // circle radius.
    double crad = endgap;

    double fontsize = 14.0;

    double label_offset = 15.0;

    int W = 0, H = 0;
    unsigned char* img = NULL;

    anbool NGC = FALSE, constell = FALSE;
    anbool bright = FALSE;
    anbool common_only = FALSE;
    anbool print_common_only = FALSE;
    int Nbright = 0;
    double ra, dec, px, py;
    int i, N;
    anbool justlist = FALSE;
    anbool only_messier = FALSE;

    anbool grid = FALSE;
    double gridspacing = 0.0;
    double gridcolor[3] = { 0.2, 0.2, 0.2 };

    int loglvl = LOG_MSG;

	char halign = 'L';
	char valign = 'C';
    sl* json = NULL;

    anbool whitetext = FALSE;

    while ((c = getopt(argc, args, OPTIONS)) != -1) {
        switch (c) {
		case 'V':
			valign = optarg[0];
			break;
		case 'O':
			halign = optarg[0];
			break;
        case 'F':
            ngc_fraction = atof(optarg);
            break;
        case 'h':
            print_help(args[0]);
            exit(0);
        case 'J':
            json = sl_new(4);
            break;
        case 'G':
            gridspacing = atof(optarg);
            break;
        case 'g':
            {
            char *tail = NULL;
            gridcolor[0] = strtod(optarg,&tail);
            if (*tail) { tail++; gridcolor[1] = strtod(tail,&tail); }
            if (*tail) { tail++; gridcolor[2] = strtod(tail,&tail); }
            }
            break;
        case 'D':
            HD = TRUE;
            break;
        case 'd':
            hdpath = optarg;
            break;
        case 'M':
            only_messier = TRUE;
            break;
        case 'n':
            nw = atof(optarg);
            break;
        case 'f':
            fontsize = atof(optarg);
            break;
        case 'L':
            justlist = TRUE;
            outfn = NULL;
            break;
        case 'x':
        	whitetext = TRUE;
        	break;
        case 'v':
            loglvl++;
            break;
            break;
        case 'j':
            print_common_only = TRUE;
            break;
        case 'c':
            common_only = TRUE;
            break;
        case 'b':
            Nbright = atoi(optarg);
            break;
        case 'B':
            bright = TRUE;
            break;
        case 'N':
            NGC = TRUE;
            break;
        case 'C':
            constell = TRUE;
            break;
        case 'p':
            pngformat = FALSE;
            break;
        case 's':
            scale = atof(optarg);
            break;
        case 'o':
            outfn = optarg;
            break;
        case 'i':
            infn = optarg;
            break;
        case 'w':
            wcsfn = optarg;
            break;
        case 'W':
            W = atoi(optarg);
            break;
        case 'H':
            H = atoi(optarg);
            break;
        }
    }

    log_init(loglvl);
    log_to(stderr);
    fits_use_error_system();

    if (optind != argc) {
        print_help(args[0]);
        exit(-1);
    }

    if (!(outfn || justlist) || !wcsfn) {
        logerr("Need (-o or -L) and -w args.\n");
        print_help(args[0]);
        exit(-1);
    }

    // read WCS.
    logverb("Trying to parse SIP/TAN header from %s...\n", wcsfn);
    if (!file_exists(wcsfn)) {
        ERROR("No such file: \"%s\"", wcsfn);
        exit(-1);
    }
    if (sip_read_header_file(wcsfn, &sip)) {
        logverb("Got SIP header.\n");
    } else {
        ERROR("Failed to parse SIP/TAN header from %s", wcsfn);
        exit(-1);
    }

    if (!(NGC || constell || bright || HD || grid)) {
        logerr("Neither constellations, bright stars, HD nor NGC/IC overlays selected!\n");
        print_help(args[0]);
        exit(-1);
    }

    if (gridspacing > 0.0)
        grid = TRUE;

    // adjust for scaling...
    lw /= scale;
    cw /= scale;
    nw /= scale;
    crad /= scale;
    endgap /= scale;
    fontsize /= scale;
    label_offset /= scale;

    if (!W || !H) {
        W = sip.wcstan.imagew;
        H = sip.wcstan.imageh;
    }
    if (!(infn || (W && H))) {
        logerr("Image width/height unspecified, and no input image given.\n");
        exit(-1);
    }


    if (infn) {
		cairoutils_fake_ppm_init();
        img = cairoutils_read_ppm(infn, &W, &H);
        if (!img) {
            ERROR("Failed to read input image %s", infn);
            exit(-1);
        }
        cairoutils_rgba_to_argb32(img, W, H);
    } else if (!justlist) {
        // Allocate a black image.
        img = calloc(4 * W * H, 1);
        if (!img) {
            SYSERROR("Failed to allocate a blank image on which to plot!");
            exit(-1);
        }
    }

    if (HD && !hdpath) {
        logerr("If you specify -D (plot Henry Draper objs), you also have to give -d (path to Henry Draper catalog)\n");
        exit(-1);
    }

    if (!justlist) {
        /*
         Cairo layers:

         -background: surfbg / cairobg
         --> gets drawn first, in black, masked by surfshapesmask

         -shapes: surfshapes / cairoshapes
         --> gets drawn second, masked by surfshapesmask

         -foreground/text: surffg / cairo
         --> gets drawn last.
         */
        surffg = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, W, H);
        cairo = cairo_create(surffg);
        cairo_set_line_join(cairo, CAIRO_LINE_JOIN_BEVEL);
        cairo_set_antialias(cairo, CAIRO_ANTIALIAS_GRAY);
        cairo_set_source_rgba(cairo, 1.0, 1.0, 1.0, 1.0);
        cairo_scale(cairo, scale, scale);
        //cairo_select_font_face(cairo, "helvetica", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
        cairo_select_font_face(cairo, "DejaVu Sans Mono Book", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
        cairo_set_font_size(cairo, fontsize);

        surfshapes = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, W, H);
        cairoshapes = cairo_create(surfshapes);
        cairo_set_line_join(cairoshapes, CAIRO_LINE_JOIN_BEVEL);
        cairo_set_antialias(cairoshapes, CAIRO_ANTIALIAS_GRAY);
        cairo_set_source_rgba(cairoshapes, 1.0, 1.0, 1.0, 1.0);
        cairo_scale(cairoshapes, scale, scale);
        cairo_select_font_face(cairoshapes, "DejaVu Sans Mono Book", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
        cairo_set_font_size(cairoshapes, fontsize);

        surfshapesmask = cairo_image_surface_create(CAIRO_FORMAT_A8, W, H);
        cairoshapesmask = cairo_create(surfshapesmask);
        cairo_set_line_join(cairoshapesmask, CAIRO_LINE_JOIN_BEVEL);
        cairo_set_antialias(cairoshapesmask, CAIRO_ANTIALIAS_GRAY);
        cairo_set_source_rgba(cairoshapesmask, 1.0, 1.0, 1.0, 1.0);
        cairo_scale(cairoshapesmask, scale, scale);
        cairo_select_font_face(cairoshapesmask, "DejaVu Sans Mono Book", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
        cairo_set_font_size(cairoshapesmask, fontsize);
        cairo_paint(cairoshapesmask);
        cairo_stroke(cairoshapesmask);

        surfbg = cairo_image_surface_create(CAIRO_FORMAT_A8, W, H);
        cairobg = cairo_create(surfbg);
        cairo_set_line_join(cairobg, CAIRO_LINE_JOIN_BEVEL);
        cairo_set_antialias(cairobg, CAIRO_ANTIALIAS_GRAY);
        cairo_set_source_rgba(cairobg, 0, 0, 0, 1);
        cairo_scale(cairobg, scale, scale);
        cairo_select_font_face(cairobg, "DejaVu Sans Mono Book", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
        cairo_set_font_size(cairobg, fontsize);

        cairos->bg = cairobg;
        cairos->fg = cairo;
        cairos->shapes = cairoshapes;
        cairos->shapesmask = cairoshapesmask;
        cairos->imgW = (float)W/scale;
        cairos->imgH = (float)H/scale;
//    }

    if (grid) {
        double ramin, ramax, decmin, decmax;
        double ra, dec;
        double rastep = gridspacing / 60.0;
        double decstep = gridspacing / 60.0;
        // how many line segments
        int N = 10;
        double px, py;
        int i;

        cairo_set_source_rgba(cairo, gridcolor[0], gridcolor[1], gridcolor[2], 1.0);

        sip_get_radec_bounds(&sip, 100, &ramin, &ramax, &decmin, &decmax);
		logverb("Plotting grid lines from RA=%g to %g in steps of %g; Dec=%g to %g in steps of %g\n",
				ramin, ramax, rastep, decmin, decmax, decstep);
        for (dec = decstep * floor(decmin / decstep); dec<=decmax; dec+=decstep) {
			logverb("  dec=%g\n", dec);
            for (i=0; i<=N; i++) {
                ra = ramin + ((double)i / (double)N) * (ramax - ramin);
                if (!sip_radec2pixelxy(&sip, ra, dec, &px, &py))
                    continue;
                // first time, move_to; else line_to
                ((ra == ramin) ? cairo_move_to : cairo_line_to)(cairo, px, py);
            }
            cairo_stroke(cairo);
        }
        for (ra = rastep * floor(ramin / rastep); ra <= ramax; ra += rastep) {
            //for (dec=decmin; dec<=decmax; dec += (decmax - decmin)/(double)N) {
			logverb("  ra=%g\n", ra);
            for (i=0; i<=N; i++) {
                dec = decmin + ((double)i / (double)N) * (decmax - decmin);
                if (!sip_radec2pixelxy(&sip, ra, dec, &px, &py))
                    continue;
                // first time, move_to; else line_to
                ((dec == decmin) ? cairo_move_to : cairo_line_to)(cairo, px, py);
            }
            cairo_stroke(cairo);
        }

        cairo_set_source_rgba(cairo, 1.0, 1.0, 1.0, 1.0);
    }
  }

    if (constell) {
        N = constellations_n();

        logverb("Checking %i constellations.\n", N);
        for (c=0; c<N; c++) {
            const char* shortname = NULL;
            const char* longname;
            il* lines;
            il* uniqstars;
            il* inboundstars;
            float r,g,b;
            int Ninbounds;
            int Nunique;
            cairo_text_extents_t textents;
            double cmass[3];

            uniqstars = constellations_get_unique_stars(c);
            inboundstars = il_new(16);

            Nunique = il_size(uniqstars);
            debug("%s: %zu unique stars.\n", shortname, il_size(uniqstars));

            // Count the number of unique stars belonging to this contellation
            // that are within the image bounds
            Ninbounds = 0;
            for (i=0; i<il_size(uniqstars); i++) {
                int star;
                star = il_get(uniqstars, i);
                constellations_get_star_radec(star, &ra, &dec);
                debug("star %i: ra,dec (%g,%g)\n", il_get(uniqstars, i), ra, dec);
                if (!sip_radec2pixelxy(&sip, ra, dec, &px, &py))
                    continue;
                if (px < 0 || py < 0 || px*scale > W || py*scale > H)
                    continue;
                Ninbounds++;
                il_append(inboundstars, star);
            }
            il_free(uniqstars);
            debug("%i are in-bounds.\n", Ninbounds);
            // Only draw this constellation if at least 2 of its stars
            // are within the image bounds.
            if (Ninbounds < 2) {
                il_free(inboundstars);
                continue;
            }

            // Set the color based on the location of the first in-bounds star.
            // This is a hack -- we have two different constellation
            // definitions with different numbering schemes!
            if (!justlist && (il_size(inboundstars) > 0)) {
                // This is helpful for videos: ensuring that the same
                // color is chosen for a constellation in each frame.
                int star = il_get(inboundstars, 0);
                constellations_get_star_radec(star, &ra, &dec);
                if (whitetext) {
                	r = g = b = 1;
                } else {
                	color_for_radec(ra, dec, &r, &g, &b);
                }
                cairo_set_source_rgba(cairoshapes, r,g,b,0.8);
                cairo_set_line_width(cairoshapes, cw);
                cairo_set_source_rgba(cairo, r,g,b,0.8);
                cairo_set_line_width(cairo, cw);
            }

            // Draw circles around each star.
            // Find center of mass (of the in-bounds stars)
            cmass[0] = cmass[1] = cmass[2] = 0.0;
            for (i=0; i<il_size(inboundstars); i++) {
                double xyz[3];
                int star = il_get(inboundstars, i);
                constellations_get_star_radec(star, &ra, &dec);
                if (!sip_radec2pixelxy(&sip, ra, dec, &px, &py))
                    continue;
                if (px < 0 || py < 0 || px*scale > W || py*scale > H)
                    continue;
                if (!justlist) {
                    cairo_arc(cairobg, px, py, crad+1.0, 0.0, 2.0*M_PI);
                    cairo_stroke(cairobg);
                    cairo_arc(cairoshapes, px, py, crad, 0.0, 2.0*M_PI);
                    cairo_stroke(cairoshapes);
                }
                radecdeg2xyzarr(ra, dec, xyz);
                cmass[0] += xyz[0];
                cmass[1] += xyz[1];
                cmass[2] += xyz[2];
            }
            cmass[0] /= il_size(inboundstars);
            cmass[1] /= il_size(inboundstars);
            cmass[2] /= il_size(inboundstars);
            xyzarr2radecdeg(cmass, &ra, &dec);

            il_free(inboundstars);

            if (!sip_radec2pixelxy(&sip, ra, dec, &px, &py))
                continue;

            shortname = constellations_get_shortname(c);
            longname = constellations_get_longname(c);
            assert(shortname && longname);

            logverb("%s at (%g, %g)\n", longname, px, py);

            if (Ninbounds == Nunique) {
                printf("The constellation %s (%s)\n", longname, shortname);
            } else {
                printf("Part of the constellation %s (%s)\n", longname, shortname);
            }

            if (justlist)
                continue;

            // If the label will be off-screen, move it back on.
            cairo_text_extents(cairo, shortname, &textents);
			
            if (px < 0)
                px = 0;
            if (py < textents.height)
                py = textents.height;
            if ((px + textents.width)*scale > W)
                px = W/scale - textents.width;
            if ((py+textents.height)*scale > H)
                py = H/scale - textents.height;
            logverb("%s at (%g, %g)\n", shortname, px, py);

            add_text(cairos, longname, px, py, halign, valign);

            // Draw the lines.
            cairo_set_line_width(cairo, lw);
            lines = constellations_get_lines(c);
            for (i=0; i<il_size(lines)/2; i++) {
                int star1, star2;
                double ra1, dec1, ra2, dec2;
                double px1, px2, py1, py2;
                double dx, dy;
                double dist;
                double gapfrac;
                star1 = il_get(lines, i*2+0);
                star2 = il_get(lines, i*2+1);
                constellations_get_star_radec(star1, &ra1, &dec1);
                constellations_get_star_radec(star2, &ra2, &dec2);
                if (!sip_radec2pixelxy(&sip, ra1, dec1, &px1, &py1) ||
                    !sip_radec2pixelxy(&sip, ra2, dec2, &px2, &py2))
                    continue;
                dx = px2 - px1;
                dy = py2 - py1;
                dist = hypot(dx, dy);
                gapfrac = endgap / dist;
                cairo_move_to(cairoshapes, px1 + dx*gapfrac, py1 + dy*gapfrac);
                cairo_line_to(cairoshapes, px1 + dx*(1.0-gapfrac), py1 + dy*(1.0-gapfrac));
                cairo_stroke(cairoshapes);
            }
            il_free(lines);
        }
        logverb("done constellations.\n");
    }

    if (bright) {
        double dy = 0;
        cairo_font_extents_t extents;
        pl* brightstars = pl_new(16);

        if (!justlist) {
            cairo_set_source_rgba(cairoshapes, 0.75, 0.75, 0.75, 0.8);
            cairo_font_extents(cairo, &extents);
            dy = extents.ascent * 0.5;
            cairo_set_line_width(cairoshapes, cw);
        }

        N = bright_stars_n();
        logverb("Checking %i bright stars.\n", N);

        for (i=0; i<N; i++) {
            const brightstar_t* bs = bright_stars_get(i);

            if (!sip_radec2pixelxy(&sip, bs->ra, bs->dec, &px, &py))
                continue;
            if (px < 0 || py < 0 || px*scale > W || py*scale > H)
                continue;
            if (!(bs->name && strlen(bs->name)))
                continue;
            if (common_only && !(bs->common_name && strlen(bs->common_name)))
                continue;

            if (strcmp(bs->common_name, "Maia") == 0)
                continue;

            pl_append(brightstars, bs);
        }

        // keep only the Nbright brightest?
        if (Nbright && (pl_size(brightstars) > Nbright)) {
            pl_sort(brightstars, sort_by_mag);
            pl_remove_index_range(brightstars, Nbright, pl_size(brightstars)-Nbright);
        }

        for (i=0; i<pl_size(brightstars); i++) {
            char* text;
            const brightstar_t* bs = pl_get(brightstars, i);

            if (!sip_radec2pixelxy(&sip, bs->ra, bs->dec, &px, &py))
                continue;
            if (bs->common_name && strlen(bs->common_name))
                if (print_common_only || common_only)
                    text = strdup(bs->common_name);
                else
                    asprintf_safe(&text, "%s (%s)", bs->common_name, bs->name);
            else
                text = strdup(bs->name);

            logverb("%s at (%g, %g)\n", text, px, py);

            if (json) {
                sl* names = sl_new(4);
                char* namearr;
                if (bs->common_name && strlen(bs->common_name))
                    sl_append(names, bs->common_name);
                if (bs->name)
					sl_append(names, bs->name);
				
                namearr = sl_join(names, "\", \"");

                sl_appendf(json,
                           "{ \"type\"  : \"star\", "
                           "  \"pixelx\": %g,       "
                           "  \"pixely\": %g,       "
                           "  \"name\"  : \"%s\",   "
                           "  \"names\" : [ \"%s\" ] } "
                           , px, py,
                           (bs->common_name && strlen(bs->common_name)) ? bs->common_name : bs->name,
                           namearr);
                free(namearr);
                sl_free2(names);
            }

            if (bs->common_name && strlen(bs->common_name))
                printf("The star %s (%s)\n", bs->common_name, bs->name);
            else
                printf("The star %s\n", bs->name);

            if (!justlist) {
                float r,g,b;
                // set color based on RA,Dec to match constellations above.
                if (whitetext) {
                	r = g = b = 1;
                } else {
                	color_for_radec(bs->ra, bs->dec, &r, &g, &b);
                }
                cairo_set_source_rgba(cairoshapes, r,g,b,0.8);
                cairo_set_source_rgba(cairo, r,g,b, 0.8);
            }

            if (!justlist)
                add_text(cairos, text, px + label_offset, py + dy,
						 halign, valign);

            free(text);

            if (!justlist) {
                // plot a black circle behind the light circle...
                cairo_arc(cairobg, px, py, crad+1.0, 0.0, 2.0*M_PI);
                cairo_stroke(cairobg);

                cairo_arc(cairoshapes, px, py, crad, 0.0, 2.0*M_PI);
                cairo_stroke(cairoshapes);
            }
        }
        pl_free(brightstars);
    }

    if (NGC) {
        double imscale;
        double imsize;
        double dy = 0;
        cairo_font_extents_t extents;

        if (!justlist) {
            cairo_set_source_rgb(cairoshapes, 1.0, 1.0, 1.0);
            cairo_set_source_rgb(cairo, 1.0, 1.0, 1.0);
            cairo_set_line_width(cairo, nw);
            cairo_font_extents(cairo, &extents);
            dy = extents.ascent * 0.5;
        }

        // arcsec/pixel
        imscale = sip_pixel_scale(&sip);
        // arcmin
        imsize = imscale * (imin(W, H) / scale) / 60.0;
        N = ngc_num_entries();

        logverb("Checking %i NGC/IC objects.\n", N);

        for (i=0; i<N; i++) {
            ngc_entry* ngc = ngc_get_entry(i);
            sl* str;
            sl* names;
            double pixsize;
            float ara, adec;
            char* text;

            if (!ngc)
                break;
            if (ngc->size < imsize * ngc_fraction)
                continue;

            if (ngcic_accurate_get_radec(ngc->is_ngc, ngc->id, &ara, &adec) == 0) {
                ngc->ra = ara;
                ngc->dec = adec;
            }

            if (!sip_radec2pixelxy(&sip, ngc->ra, ngc->dec, &px, &py))
                continue;
            if (px < 0 || py < 0 || px*scale > W || py*scale > H)
                continue;

            str = sl_new(4);
            //sl_appendf(str, "%s %i", (ngc->is_ngc ? "NGC" : "IC"), ngc->id);
            names = ngc_get_names(ngc, NULL);
            if (names) {
                int n;
                for (n=0; n<sl_size(names); n++) {
                    if (only_messier && strncmp(sl_get(names, n), "M ", 2))
                        continue;
                    sl_append(str, sl_get(names, n));
                }
            }
            sl_free2(names);

            text = sl_implode(str, " / ");

            printf("%s\n", text);

            pixsize = ngc->size * 60.0 / imscale;

            if (!justlist) {
                // black circle behind the white one...
                cairo_arc(cairobg, px, py, pixsize/2.0+1.0, 0.0, 2.0*M_PI);
                cairo_stroke(cairobg);

                cairo_move_to(cairoshapes, px + pixsize/2.0, py);
                cairo_arc(cairoshapes, px, py, pixsize/2.0, 0.0, 2.0*M_PI);
                debug("size: %f arcsec, pixsize: %f pixels\n", ngc->size, pixsize);
                cairo_stroke(cairoshapes);

                add_text(cairos, text, px + label_offset, py + dy,
						 halign, valign);
            }

            if (json) {
                char* namelist = sl_implode(str, "\", \"");
                sl_appendf(json,
                           "{ \"type\"   : \"ngc\", "
                           "  \"names\"  : [ \"%s\" ], "
                           "  \"pixelx\" : %g, "
                           "  \"pixely\" : %g, "
                           "  \"radius\" : %g }"
                           , namelist, px, py, pixsize/2.0);
                free(namelist);
            }

            free(text);
            sl_free2(str);
        }
    }

    if (HD) {
        double rac, decc, ra2, dec2;
        double arcsec;
        hd_catalog_t* hdcat;
        bl* hdlist;
        int i;

        if (!justlist)
            cairo_set_source_rgb(cairo, 1.0, 1.0, 1.0);

		logverb("Reading HD catalog: %s\n", hdpath);
        hdcat = henry_draper_open(hdpath);
        if (!hdcat) {
            ERROR("Failed to open HD catalog");
            exit(-1);
        }
		logverb("Got %i HD stars\n", henry_draper_n(hdcat));

        sip_pixelxy2radec(&sip, W/(2.0*scale), H/(2.0*scale), &rac, &decc);
        sip_pixelxy2radec(&sip, 0.0, 0.0, &ra2, &dec2);
        arcsec = arcsec_between_radecdeg(rac, decc, ra2, dec2);
        // Fudge
        arcsec *= 1.1;
        hdlist = henry_draper_get(hdcat, rac, decc, arcsec);
		logverb("Found %zu HD stars within range (%g arcsec of RA,Dec %g,%g)\n", bl_size(hdlist), arcsec, rac, decc);

        for (i=0; i<bl_size(hdlist); i++) {
            double px, py;
            char* txt;
            hd_entry_t* hd = bl_access(hdlist, i);
            if (!sip_radec2pixelxy(&sip, hd->ra, hd->dec, &px, &py)) {
                continue;
			}
            if (px < 0 || py < 0 || px*scale > W || py*scale > H) {
				logverb("  HD %i at RA,Dec (%g, %g) -> pixel (%.1f, %.1f) is out of bounds\n",
						hd->hd, hd->ra, hd->dec, px, py);
                continue;
			}
            asprintf_safe(&txt, "HD %i", hd->hd);
            if (!justlist) {
                cairo_text_extents_t textents;
                cairo_text_extents(cairo, txt, &textents);
                cairo_arc(cairobg, px, py, crad+1.0, 0.0, 2.0*M_PI);
                cairo_stroke(cairobg);
                cairo_arc(cairoshapes, px, py, crad, 0.0, 2.0*M_PI);
                cairo_stroke(cairoshapes);

                px -= (textents.width * 0.5);
                py -= (crad + 4.0);

                add_text(cairos, txt, px, py, halign, valign);
            }

            if (json)
                sl_appendf(json,
                           "{ \"type\"  : \"hd\","
                           "  \"pixelx\": %g, "
                           "  \"pixely\": %g, "
                           "  \"name\"  : \"HD %i\" }"
                           , px, py, hd->hd);

            printf("%s\n", txt);
            free(txt);
        }
        bl_free(hdlist);
        henry_draper_close(hdcat);
    }

    if (json) {
        FILE* fout = stderr;
        char* annstr = sl_implode(json, ",\n");
        fprintf(fout, "{ \n");
        fprintf(fout, "  \"status\": \"solved\",\n");
        fprintf(fout, "  \"git-revision\": %s,\n", AN_GIT_REVISION);
        fprintf(fout, "  \"git-date\": \"%s\",\n", AN_GIT_DATE);
        fprintf(fout, "  \"annotations\": [\n%s\n]\n", annstr);
        fprintf(fout, "}\n");
        free(annstr);
    }
    sl_free2(json);
    json = NULL;

    if (justlist)
        return 0;

    target = cairo_image_surface_create_for_data(img, CAIRO_FORMAT_ARGB32, W, H, W*4);
    cairot = cairo_create(target);
    cairo_set_source_rgba(cairot, 0, 0, 0, 1);

    // Here's where you set the background surface's properties...
    cairo_set_source_surface(cairot, surfbg, 0, 0);
    cairo_mask_surface(cairot, surfshapesmask, 0, 0);
    cairo_stroke(cairot);

    // Add on the shapes.
    cairo_set_source_surface(cairot, surfshapes, 0, 0);
    //cairo_mask_surface(cairot, surfshapes, 0, 0);
    cairo_mask_surface(cairot, surfshapesmask, 0, 0);
    cairo_stroke(cairot);

    // Add on the foreground.
    cairo_set_source_surface(cairot, surffg, 0, 0);
    cairo_mask_surface(cairot, surffg, 0, 0);
    cairo_stroke(cairot);

    // Convert image for output...
    cairoutils_argb32_to_rgba(img, W, H);

    if (pngformat) {
        if (cairoutils_write_png(outfn, img, W, H)) {
            ERROR("Failed to write PNG");
            exit(-1);
        }
    } else {
        if (cairoutils_write_ppm(outfn, img, W, H)) {
            ERROR("Failed to write PPM");
            exit(-1);
        }
    }

    cairo_surface_destroy(target);
    cairo_surface_destroy(surfshapesmask);
    cairo_surface_destroy(surffg);
    cairo_surface_destroy(surfbg);
    cairo_surface_destroy(surfshapes);
    cairo_destroy(cairo);
    cairo_destroy(cairot);
    cairo_destroy(cairobg);
    cairo_destroy(cairoshapes);
    cairo_destroy(cairoshapesmask);
    free(img);

    return 0;
}
示例#16
0
shutdown_type application::impl::run(int argc, const char ** argv)
{
    std::list<std::string> targets;
    if (_config.get_property("log_info", LOG_INFO_DEFAULT))
        targets.emplace_back("info");
    if (_config.get_property("log_debug", LOG_DEBUG_DEFAULT))
        targets.emplace_back("debug");
    if (_config.get_property("log_error", LOG_ERROR_DEFAULT))
        targets.emplace_back("error");
    logger::instance().set_targets(std::move(targets));

    std::ostringstream version;
    version << LOGIN_VERSION_MAJOR << "." << LOGIN_VERSION_MINOR
        << "." << LOGIN_VERSION_RELEASE;
    _owner->set_title("desperion login server v" + version.str());

    std::cout << "\n";
    utils::color<utils::TBLUE>(std::cout)
        << ",------,  ,-----. ,-----, ,------. ,-----. ,------.  ,------. ,------, ,,    ,,\n"
        << "| ,--,  ` | .---' |  ,--` | ,--, | | .---' | ,--, |  `--||--' | ,--, | ||\\   ||\n"
        << "| |  |  | | |--.  |  `--, | |  | | | |--.  | |  | |     ||    | |  | | || \\  ||\n"
        << "| |  |  | | |--'  `---, | | `--` | | |--'  | `--` ,     ||    | |  | | ||  \\ ||\n"
        << "| '--'  , | '---, ,---| | | ,----` | '---, | ,-\\  \\  .--||--, | '--' | ||   \\||\n"
        << "`------`  `-----' `-----` `-`      `-----' `-`  '--' `------` `------` ``    `'\n";
    utils::color<utils::TGREEN>(std::cout)
        << "Dofus v" << protocol::DOFUS_VERSION_MAJOR << "." << protocol::DOFUS_VERSION_MINOR << "."
        << protocol::DOFUS_VERSION_RELEASE << "." << protocol::DOFUS_VERSION_REVISION << "."
        << protocol::DOFUS_VERSION_PATCH << "/" << protocol::DOFUS_VERSION_BUILD_TYPE << ", protocol "
        << protocol::PROTOCOL_BUILD << "/" << protocol::PROTOCOL_REQUIRED_BUILD << "\n"

        << "login server v" << version.str() << ", build date: " << __DATE__
        << " " << __TIME__ << "\n" << utils::cendl;

    try {
        start_database();
    } catch (const sql_error & e) {
        utils::color<utils::TRED>(std::cout) << "an sql error occured, please see log files"
            << utils::cendl;
        log_to("error") << "sql error: " << e.what() << "\n";
        return shutdown_type::NORMAL;
    }

    _world.init();
    session::load_patch();

    socket_listener listener;
    auto port = _config.get_property("server_port", SERVER_PORT_DEFAULT);
    listener.listen<session>(port);

    port = _config.get_property("system_port", SERVER_PORT_DEFAULT);
    listener.listen<game_session>(port);

    std::cout << "\nuptime " << _owner->uptime() << " microseconds" << std::endl;

    listener.spawn_threads(_config.get_property("pool_threads", POOL_THREADS_DEFAULT));
    std::thread t { std::bind(&run_service, std::ref(_owner->_service)) };
    std::mutex m;
    std::unique_lock<std::mutex> lock { m };
    while (_owner->get_shutdown() == shutdown_type::NOT_REQUESTED)
        _owner->_condition.wait(lock);
    listener.stop();
    t.join();

    return _owner->get_shutdown();
}
示例#17
0
int main(int argc, char *args[]) {
	int argchar;
	char* progname = args[0];

	plot_args_t pargs;
	plotxy_t* xy;
	plotimage_t* img;
	int loglvl = LOG_MSG;

    // log errors to stderr, not stdout.
    errors_log_to(stderr);

	plotstuff_init(&pargs);
	pargs.fout = stdout;
	pargs.outformat = PLOTSTUFF_FORMAT_PNG;

	xy = plotstuff_get_config(&pargs, "xy");
	img = plotstuff_get_config(&pargs, "image");
	assert(xy);
	assert(img);

	plotstuff_set_color(&pargs, "white");
	plotstuff_set_bgcolor(&pargs, "black");
	
	img->format = PLOTSTUFF_FORMAT_PPM;

	while ((argchar = getopt(argc, args, OPTIONS)) != -1)
		switch (argchar) {
		case 'v':
			loglvl++;
			break;
        case 'C':
			plotstuff_set_color(&pargs, optarg);
            break;
        case 'b':
			plotstuff_set_bgcolor(&pargs, "optarg");
            break;
        case 'o':
            pargs.outfn = optarg;
            break;
        case 'X':
			plot_xy_set_xcol(xy, optarg);
            break;
        case 'Y':
			plot_xy_set_ycol(xy, optarg);
            break;
        case 'P':
            pargs.outformat = PLOTSTUFF_FORMAT_PPM;
            break;
		case 'J':
            pargs.outformat = PLOTSTUFF_FORMAT_PDF;
			break;
		case 'p':
			img->format = PLOTSTUFF_FORMAT_PNG;
            break;
        case 'I':
			plot_image_set_filename(img, optarg);
            break;
		case 'S':
			xy->scale = atof(optarg);
			break;
		case 'i':
			plot_xy_set_filename(xy, optarg);
			break;
		case 'x':
			xy->xoff = atof(optarg);
			break;
		case 'y':
			xy->yoff = atof(optarg);
			break;
		case 'W':
			pargs.W = atoi(optarg);
			break;
		case 'H':
			pargs.H = atoi(optarg);
			break;
		case 'n':
			xy->firstobj = atoi(optarg);
			break;
		case 'N':
			xy->nobjs = atoi(optarg);
			break;
		case 'e':
			xy->ext = atoi(optarg);
			break;
		case 'r':
			pargs.markersize = atof(optarg);
			break;
		case 'w':
			pargs.lw = atof(optarg);
			break;
		case 's':
			plotstuff_set_marker(&pargs, optarg);
			break;
		case 'h':
			printHelp(progname);
            exit(0);
		case '?':
		default:
			printHelp(progname);
            exit(-1);
		}

	if (optind != argc) {
		printHelp(progname);
		exit(-1);
	}
	if (!xy->fn) {
		printHelp(progname);
		exit(-1);
	}
	log_init(loglvl);
	log_to(stderr);
	fits_use_error_system();
	if (img->fn) {
		if (plot_image_setsize(&pargs, img)) {
			ERROR("Failed to set plot size from image");
			exit(-1);
		}
		plotstuff_run_command(&pargs, "image");
	} else {
		if (pargs.W == 0 || pargs.H == 0) {
			if (plot_xy_setsize(&pargs, xy)) {
				ERROR("Failed to set plot size from xylist");
				exit(-1);
			}
		}
	}

	plotstuff_run_command(&pargs, "xy");

	plotstuff_output(&pargs);
	plotstuff_free(&pargs);

	return 0;
}
示例#18
0
int
main(int argc, char *argv[])
{
	printf("ISAKMP: main : <<<START>>> \n");
	fd_set         *rfds, *wfds;
	int             n, m;
	size_t          mask_size;
	struct timeval  tv, *timeout;
	

	
	// closefrom(STDERR_FILENO + 1);

	/*
	 * Make sure init() won't alloc fd 0, 1 or 2, as daemon() will close
	 * them.
	 */
/*
	for (n = 0; n <= 2; n++) 
		if (fcntl(n, F_GETFL, 0) == -1 && errno == EBADF)
			(void) open("/dev/null", n ? O_WRONLY : O_RDONLY, 0);
*/
	/* Log cmd line parsing and initialization errors to stderr.  */
	log_to(stderr);
	parse_args(argc, argv);
	log_init(debug);
	
	

	/* Open protocols and services databases.  */
	setprotoent(1);
	setservent(1);

	/* Open command fifo */
	ui_init();

	set_slave_signals();
	/* Daemonize before forking unpriv'ed child */
	if (!debug)
		if (daemon(0, 0))
			log_fatal("main: daemon (0, 0) failed");

	/* Set timezone before priv'separation */
	tzset();
	
	write_pid_file();
	
	/*
	if (monitor_init(debug)) {
		// The parent, with privileges enters infinite monitor loop.
		//monitor_loop(debug);
		//exit(0);	// Never reached.  
	}*/

	/* Child process only from this point on, no privileges left.  */

	init(); 
	
	/* If we wanted IKE packet capture to file, initialize it now.  */
	if (pcap_file != 0)
		log_packet_init(pcap_file);

	/* Allocate the file descriptor sets just big enough.  */
	
// we change here 
	
	//n = getdtablesize();
	n = 1000;
	mask_size = howmany(n, NFDBITS) * sizeof(fd_mask);
	
	rfds = (fd_set *) malloc(mask_size);
	if (!rfds)
		log_fatal("main: malloc (%lu) failed",
		    (unsigned long)mask_size);

	wfds = (fd_set *) malloc(mask_size);
	if (!wfds)
		log_fatal("main: malloc (%lu) failed",
		    (unsigned long)mask_size);

	//monitor_init_done();
	while (1) {
		/* If someone has sent SIGHUP to us, reconfigure.  */
		if (sighupped) {
			sighupped = 0;
			log_print("SIGHUP received");
			reinit();
		}
		/* and if someone sent SIGUSR1, do a state report.  */
		if (sigusr1ed) {
			sigusr1ed = 0;
			log_print("SIGUSR1 received");
			report();
		}
		/*
		 * and if someone set 'sigtermed' (SIGTERM, SIGINT or via the
		 * UI), this indicates we should start a controlled shutdown
		 * of the daemon.
		 *
		 * Note: Since _one_ message is sent per iteration of this
		 * enclosing while-loop, and we want to send a number of
		 * DELETE notifications, we must loop atleast this number of
		 * times. The daemon_shutdown() function starts by queueing
		 * the DELETEs, all other calls just increments the
		 * 'sigtermed' variable until it reaches a "safe" value, and
		 * the daemon exits.
		 */
		if (sigtermed)
			daemon_shutdown();

		/* Setup the descriptors to look for incoming messages at.  */
		bzero(rfds, mask_size);
		n = transport_fd_set(rfds);
		FD_SET(ui_socket, rfds);
		if (ui_socket + 1 > n)
			n = ui_socket + 1;

		/*
		 * XXX Some day we might want to deal with an abstract
		 * application class instead, with many instantiations
		 * possible.
		 */
		if (!app_none && app_socket >= 0) {
			FD_SET(app_socket, rfds);
			if (app_socket + 1 > n)
				n = app_socket + 1;
		}
		/* Setup the descriptors that have pending messages to send. */
		bzero(wfds, mask_size);
		m = transport_pending_wfd_set(wfds);
		printf(" m = %d , n = %d \n", m,n);
		if (m > n)
			n = m;

		/* Find out when the next timed event is.  */
		timeout = &tv;
		timer_next_event(&timeout);
		printf(" select (n  n= %d )\n ",n );
		n = select(n, rfds, wfds, 0, timeout);
		
		if (n == -1) {
			if (errno != EINTR) {
				log_error("main: select");

				/*
				 * In order to give the unexpected error
				 * condition time to resolve without letting
				 * this process eat up all available CPU
				 * we sleep for a short while.
				 */
				sleep(1);
			}
		} else if (n) {
			
			transport_handle_messages(rfds);
			transport_send_messages(wfds);
			if (FD_ISSET(ui_socket, rfds))
				ui_handler();
			if (!app_none && app_socket >= 0 &&
			    FD_ISSET(app_socket, rfds))
				app_handler();
		}
		
		timer_handle_expirations();
	}
}
示例#19
0
static int read_parameters(blind_t* bp) {
	solver_t* sp = &(bp->solver);
	for (;;) {
		char buffer[10240];
		char* nextword;
		char* line;
		if (!fgets(buffer, sizeof(buffer), stdin)) {
			return -1;
		}
		line = buffer;
		// strip off newline
		if (line[strlen(line) - 1] == '\n')
			line[strlen(line) - 1] = '\0';

		// skip leading whitespace:
		while (*line && isspace(*line))
			line++;

		logverb("Command: %s\n", line);

		if (line[0] == '#') {
			//logmsg("Skipping comment.\n");
			continue;
		}
		// skip blank lines.
		if (line[0] == '\0') {
			continue;
		}
		if (is_word(line, "help", &nextword)) {
			logmsg("No help soup for you!\n  (use the source, Luke)\n");
        } else if (is_word(line, "logtostderr", &nextword)) {
            log_to(stderr);
        } else if (is_word(line, "verbose", &nextword)) {
            log_init(LOG_VERB);
		} else if (is_word(line, "verify ", &nextword)) {
			sl_append(bp->verify_wcsfiles, nextword);
		} else if (is_word(line, "verify_wcs ", &nextword)) {
			sip_t wcs;
            int nread;
			memset(&wcs, 0, sizeof(wcs));
			if (sscanf(nextword, "%lg %lg %lg %lg %lg %lg %lg %lg%n",
			           &(wcs.wcstan.crval[0]), &(wcs.wcstan.crval[1]),
			           &(wcs.wcstan.crpix[0]), &(wcs.wcstan.crpix[1]),
			           &(wcs.wcstan.cd[0][0]), &(wcs.wcstan.cd[0][1]),
			           &(wcs.wcstan.cd[1][0]), &(wcs.wcstan.cd[1][1]),
                       &nread) < 8) {
				logerr("Failed to parse verify_wcs entry.\n");
				continue;
			}
            nextword += nread;
            if (sscanf(nextword, " %i %i%n", &(wcs.a_order), &(wcs.ap_order), &nread) >= 2) {
                int m, n;
                wcs.b_order = wcs.a_order;
                wcs.bp_order = wcs.ap_order;
                nextword += nread;
                for (m=0; m<=wcs.a_order; m++) {
                    for (n=0; (m+n)<=wcs.a_order; n++) {
                        if (sscanf(nextword, " %lg %lg%n", &(wcs.a[m][n]), &(wcs.b[m][n]), &nread) < 2) {
                            logerr("Failed to parse SIP terms: \"%s\"\n", nextword);
                            continue;
                        }
                        nextword += nread;
                    }
                }
                for (m=0; m<=wcs.ap_order; m++) {
                    for (n=0; (m+n)<=wcs.ap_order; n++) {
                        if (sscanf(nextword, " %lg %lg%n", &(wcs.ap[m][n]), &(wcs.bp[m][n]), &nread) < 2) {
                            logerr("Failed to parse SIP terms: \"%s\"\n", nextword);
                            continue;
                        }
                        nextword += nread;
                    }
                }
            }
            blind_add_verify_wcs(bp, &wcs);
		} else if (is_word(line, "cpulimit ", &nextword)) {
			bp->cpulimit = atof(nextword);
		} else if (is_word(line, "timelimit ", &nextword)) {
			bp->timelimit = atoi(nextword);
		} else if (is_word(line, "total_timelimit ", &nextword)) {
			bp->total_timelimit = atof(nextword);
		} else if (is_word(line, "total_cpulimit ", &nextword)) {
			bp->total_cpulimit = atof(nextword);
		} else if (is_word(line, "verify_pix ", &nextword)) {
			sp->verify_pix = atof(nextword);
		} else if (is_word(line, "nsolves ", &nextword)) {
			bp->nsolves = atoi(nextword);
		} else if (is_word(line, "ratio_tosolve ", &nextword)) {
			bp->logratio_tosolve = log(atof(nextword));
		} else if (is_word(line, "ratio_tokeep ", &nextword)) {
			sp->logratio_tokeep = log(atof(nextword));
		} else if (is_word(line, "ratio_toprint ", &nextword)) {
			sp->logratio_toprint = log(atof(nextword));
		} else if (is_word(line, "ratio_tobail ", &nextword)) {
			sp->logratio_bail_threshold = log(atof(nextword));
		} else if (is_word(line, "match ", &nextword)) {
            blind_set_match_file(bp, nextword);
		} else if (is_word(line, "indexrdls ", &nextword)) {
            blind_set_rdls_file(bp, nextword);
		} else if (is_word(line, "correspondences ", &nextword)) {
			free(bp->corr_fname);
			bp->corr_fname = strdup(nextword);
		} else if (is_word(line, "best_only", &nextword)) {
			bp->best_hit_only = TRUE;
		} else if (is_word(line, "solved ", &nextword)) {
            blind_set_solved_file(bp, nextword);
		} else if (is_word(line, "solved_in ", &nextword)) {
            blind_set_solvedin_file(bp, nextword);
		} else if (is_word(line, "solved_out ", &nextword)) {
            blind_set_solvedout_file(bp, nextword);
		} else if (is_word(line, "cancel ", &nextword)) {
            blind_set_cancel_file(bp, nextword);
		} else if (is_word(line, "solvedserver ", &nextword)) {
			free(bp->solvedserver);
			bp->solvedserver = strdup(nextword);
		} else if (is_word(line, "tweak_skipshift", &nextword)) {
			// deprecated
		} else if (is_word(line, "tweak_aborder ", &nextword)) {
			sp->tweak_aborder = atoi(nextword);
		} else if (is_word(line, "tweak_abporder ", &nextword)) {
			sp->tweak_abporder = atoi(nextword);
		} else if (is_word(line, "tweak", &nextword)) {
			sp->do_tweak = TRUE;
		} else if (is_word(line, "wcs ", &nextword)) {
            blind_set_wcs_file(bp, nextword);
		} else if (is_word(line, "fieldid_key ", &nextword)) {
			free(bp->fieldid_key);
			bp->fieldid_key = strdup(nextword);
		} else if (is_word(line, "maxquads ", &nextword)) {
			sp->maxquads = atoi(nextword);
		} else if (is_word(line, "maxmatches ", &nextword)) {
			sp->maxmatches = atoi(nextword);
		} else if (is_word(line, "xcol ", &nextword)) {
            blind_set_xcol(bp, nextword);
		} else if (is_word(line, "ycol ", &nextword)) {
            blind_set_ycol(bp, nextword);
		} else if (is_word(line, "index ", &nextword)) {
            blind_add_index(bp, nextword);
		} else if (is_word(line, "indexes_inparallel", &nextword)) {
			bp->indexes_inparallel = TRUE;
		} else if (is_word(line, "field ", &nextword)) {
            blind_set_field_file(bp, nextword);
		} else if (is_word(line, "fieldw ", &nextword)) {
			sp->field_maxx = atof(nextword);
		} else if (is_word(line, "fieldh ", &nextword)) {
			sp->field_maxy = atof(nextword);
		} else if (is_word(line, "distractors ", &nextword)) {
			sp->distractor_ratio = atof(nextword);
		} else if (is_word(line, "fieldid ", &nextword)) {
			bp->fieldid = atoi(nextword);
		} else if (is_word(line, "sdepth ", &nextword)) {
			sp->startobj = atoi(nextword);
		} else if (is_word(line, "depth ", &nextword)) {
			sp->endobj = atoi(nextword);
		} else if (is_word(line, "tol ", &nextword)) {
			sp->codetol = atof(nextword);
		} else if (is_word(line, "parity ", &nextword)) {
			sp->parity = atoi(nextword);
		} else if (is_word(line, "quadsize_min ", &nextword)) {
			sp->quadsize_min = atof(nextword);
		} else if (is_word(line, "fieldunits_lower ", &nextword)) {
			sp->funits_lower = atof(nextword);
		} else if (is_word(line, "fieldunits_upper ", &nextword)) {
			sp->funits_upper = atof(nextword);
		} else if (is_word(line, "firstfield ", &nextword)) {
			bp->firstfield = atoi(nextword);
		} else if (is_word(line, "lastfield ", &nextword)) {
			bp->lastfield = atoi(nextword);
		} else if (is_word(line, "fields ", &nextword)) {
			char* str = nextword;
            while (str && *str) {
                unsigned int lo, hi;
                int nread;
                if (sscanf(str, "%u%*1[-/]%u", &lo, &hi) == 2) {
                    sscanf(str, "%*u%*1[-/]%*u%n", &nread);
                } else if (sscanf(str, "%u", &lo) == 1) {
                    sscanf(str, "%*u%n", &nread);
                    hi = lo;
                } else {
                    fprintf(stderr, "Failed to parse fields fragment: \"%s\"\n", str);
                    return -1;
                }
                if (lo < 1) {
                    fprintf(stderr, "Field number %i is invalid: must be >= 1.\n", lo);
                    return -1;
                }
                if (lo > hi) {
                    fprintf(stderr, "Field range %i to %i is invalid: max must be >= min!\n", lo, hi);
                    return -1;
                }
                blind_add_field_range(bp, lo, hi);
                str += nread;
                while ((*str == ',') || isspace(*str))
                    str++;
            }
		} else if (is_word(line, "run", &nextword)) {
			return 0;
		} else if (is_word(line, "quit", &nextword)) {
			return 1;

		} else if (is_word(line, "nverify ", &nextword)) {
			logmsg("DEPRECATED: \"nverify\" command.\n");
		} else if (is_word(line, "nindex_tosolve ", &nextword)) {
			logmsg("DEPRECATED: \"nindex_tosolve\" command.\n");
		} else if (is_word(line, "nindex_tokeep ", &nextword)) {
			logmsg("DEPRECATED: \"nindex_tokeep\" command.\n");

		} else {
			logmsg("I didn't understand this command:\n  \"%s\"\n", line);
		}
	}
}
示例#20
0
int main(int argc, char *argv[]) {
    int argchar;
	char* infn = NULL;
	char* outfn = NULL;
	FILE* fout;
	anbool tostdout = FALSE;
    anqfits_t* anq;
    int W, H;
	qfits_header* hdr;
    const anqfits_image_t* animg;
	float* img;
	int loglvl = LOG_MSG;
	int scale = 2;
	int winw;
	int winh;
	int plane;
	int out_bitpix = -32;
	float* outimg;
	int outw, outh;
	int edge = EDGE_TRUNCATE;
	int ext = 0;
	int npixout = 0;

    while ((argchar = getopt (argc, argv, OPTIONS)) != -1)
        switch (argchar) {
		case 'v':
			loglvl++;
			break;
		case 's':
			scale = atoi(optarg);
			break;
		case 'e':
			ext = atoi(optarg);
			break;
        case '?':
        case 'h':
			printHelp(argv[0]);
            return 0;
        default:
            return -1;
        }

	log_init(loglvl);
	log_to(stderr);
	errors_log_to(stderr);
	fits_use_error_system();

	if (argc - optind != 2) {
		logerr("Need two arguments: input and output files.\n");
		printHelp(argv[0]);
		exit(-1);
	}

	infn = argv[optind];
	outfn = argv[optind+1];

	if (streq(outfn, "-")) {
		tostdout = TRUE;
		fout = stdout;
	} else {
		fout = fopen(outfn, "wb");
		if (!fout) {
			SYSERROR("Failed to open output file \"%s\"", outfn);
			exit(-1);
		}
	}

    anq = anqfits_open(infn);
    if (!anq) {
        ERROR("Failed to open input file \"%s\"", infn);
        exit(-1);
    }
    animg = anqfits_get_image_const(anq, ext);
    
    W = (int)animg->width;
    H = (int)animg->height;
    if (!animg) {
        ERROR("Failde to read image from \"%s\"", infn);
        exit(-1);
    }

    /*
	if (tostdout)
		dump.filename = "STDOUT";
	else
		dump.filename = outfn;
	dump.ptype = PTYPE_FLOAT;
	dump.out_ptype = out_bitpix;
     */

	get_output_image_size(W % scale, H % scale,
						  scale, edge, &outw, &outh);
	outw += (W / scale);
	outh += (H / scale);
    
	hdr = qfits_header_default();
    fits_header_add_int(hdr, "BITPIX", out_bitpix, "bits per pixel");
	if (animg->planes > 1)
		fits_header_add_int(hdr, "NAXIS", 3, "number of axes");
	else
		fits_header_add_int(hdr, "NAXIS", 2, "number of axes");
    fits_header_add_int(hdr, "NAXIS1", outw, "image width");
    fits_header_add_int(hdr, "NAXIS2", outh, "image height");
	if (animg->planes > 1)
		fits_header_add_int(hdr, "NAXIS3", animg->planes, "number of planes");

	if (qfits_header_dump(hdr, fout)) {
		ERROR("Failed to write FITS header to \"%s\"", outfn);
		exit(-1);
	}
	qfits_header_destroy(hdr);

	winw = W;
	winh = (int)ceil(ceil(1024*1024 / (float)winw) / (float)scale) * scale;

	outimg = malloc((int)ceil(winw/scale)*(int)ceil(winh/scale) * sizeof(float));
			
	logmsg("Image is %i x %i x %i\n", W, H, (int)animg->planes);
	logmsg("Output will be %i x %i x %i\n", outw, outh, (int)animg->planes);
	logverb("Reading in blocks of %i x %i\n", winw, winh);
	for (plane=0; plane<animg->planes; plane++) {
		int bx, by;
		int nx, ny;
		for (by=0; by<(int)ceil(H / (float)winh); by++) {
			for (bx=0; bx<(int)ceil(W / (float)winw); bx++) {
                int i;
				int lox, loy, hix, hiy, outw, outh;
				nx = MIN(winw, W - bx*winw);
				ny = MIN(winh, H - by*winh);
				lox = bx*winw;
				loy = by*winh;
				hix = lox + nx;
				hiy = loy + ny;
				logverb("  reading %i,%i + %i,%i\n", lox, loy, nx, ny);

                img = anqfits_readpix(anq, ext, lox, hix, loy, hiy, plane,
                                      PTYPE_FLOAT, NULL, &W, &H);
                if (!img) {
                    ERROR("Failed to load pixel window: x=[%i, %i), y=[%i,%i), plane %i\n",
                          lox, hix, loy, hiy, plane);
                    exit(-1);
                }

				average_image_f(img, nx, ny, scale, edge,
								&outw, &outh, outimg);
                free(img);

				logverb("  writing %i x %i\n", outw, outh);
				if (outw * outh == 0)
					continue;

                for (i=0; i<outw*outh; i++) {
                    int nbytes = abs(out_bitpix)/8;
                    char buf[nbytes];
                    if (qfits_pixel_ctofits(PTYPE_FLOAT, out_bitpix,
                                            outimg + i, buf)) {
                        ERROR("Failed to convert pixel to FITS type\n");
                        exit(-1);
                    }
                    if (fwrite(buf, nbytes, 1, fout) != 1) {
                        ERROR("Failed to write pixels\n");
                        exit(-1);
                    }
                }
				npixout += outw*outh;
			}
		}
	}
	free(outimg);
    anqfits_close(anq);

	if (tostdout) {
		// pad.
		int N;
		char pad[2880];
		N = (npixout * (abs(out_bitpix) / 8)) % 2880;
		memset(pad, 0, 2880);
		fwrite(pad, 1, N, fout);
	} else {
		if (fits_pad_file(fout)) {
			ERROR("Failed to pad output file");
			exit(-1);
		}
        if (fclose(fout)) {
            SYSERROR("Failed to close output file");
            exit(-1);
        }
    }
	logverb("Done!\n");
	return 0;
}
示例#21
0
文件: isakmpd.c 项目: ebichu/dd-wrt
int
main (int argc, char *argv[])
{
  fd_set *rfds, *wfds;
  int n, m;
  size_t mask_size;
  struct timeval tv, *timeout;

  /* Make sure init() won't alloc fd 0, 1 or 2, as daemon() will close them. */
  for (n = 0; n <= 2; n++)
    if (fcntl (n, F_GETFL, 0) == -1 && errno == EBADF)
      (void)open ("/dev/null", n ? O_WRONLY : O_RDONLY, 0);

  /* Log cmd line parsing and initialization errors to stderr.  */
  log_to (stderr);
  parse_args (argc, argv);
  log_init ();

  /* Do a clean daemon shutdown on TERM reception. (Needed by monitor).  */
  signal (SIGTERM, daemon_shutdown_now);
  if (debug) signal (SIGINT, daemon_shutdown_now);

#if defined (USE_PRIVSEP)
  if (monitor_init ())
    {
      /* The parent, with privileges.  */
      if (!debug)
	if (daemon (0, 0))
	  log_fatal ("main [priv]: daemon (0, 0) failed");

      /* Enter infinite monitor loop.  */
      monitor_loop (debug);
      exit (0); /* Never reached.  */
    }

  /* Child process only from this point on, no privileges left.  */
#endif

  init ();

  if (!debug)
    {
      if (daemon (0, 0))
	log_fatal ("main: daemon (0, 0) failed");
      /* Switch to syslog.  */
      log_to (0);
    }

  write_pid_file ();

  /* Reinitialize on HUP reception.  */
  signal (SIGHUP, sighup);

  /* Report state on USR1 reception.  */
  signal (SIGUSR1, sigusr1);

  /* Rehash soft expiration timers on USR2 reception.  */
  signal (SIGUSR2, sigusr2);

#if defined (USE_DEBUG)
  /* If we wanted IKE packet capture to file, initialize it now.  */
  if (pcap_file != 0)
    log_packet_init (pcap_file);
#endif

  /* Allocate the file descriptor sets just big enough.  */
  n = getdtablesize ();
  mask_size = howmany (n, NFDBITS) * sizeof (fd_mask);
  rfds = (fd_set *)malloc (mask_size);
  if (!rfds)
    log_fatal ("main: malloc (%lu) failed", (unsigned long)mask_size);
  wfds = (fd_set *)malloc (mask_size);
  if (!wfds)
    log_fatal ("main: malloc (%lu) failed", (unsigned long)mask_size);

  while (1)
    {
      /* If someone has sent SIGHUP to us, reconfigure.  */
      if (sighupped)
	{
	  log_print ("SIGHUP received");
	  reinit ();
	  sighupped = 0;
	}

      /* and if someone sent SIGUSR1, do a state report.  */
      if (sigusr1ed)
	{
	  log_print ("SIGUSR1 received");
	  report ();
	}

      /* and if someone sent SIGUSR2, do a timer rehash.  */
      if (sigusr2ed)
	{
	  log_print ("SIGUSR2 received");
	  rehash_timers ();
	}

      /*
       * and if someone set 'sigtermed' (SIGTERM or via the UI), this
       * indicated we should start a shutdown of the daemon.
       *
       * Note: Since _one_ message is sent per iteration of this enclosing
       * while-loop, and we want to send a number of DELETE notifications,
       * we must loop atleast this number of times. The daemon_shutdown()
       * function starts by queueing the DELETEs, all other calls just
       * increments the 'sigtermed' variable until it reaches a "safe"
       * value, and the daemon exits.
       */
      if (sigtermed)
	daemon_shutdown ();

      /* Setup the descriptors to look for incoming messages at.  */
      memset (rfds, 0, mask_size);
      n = transport_fd_set (rfds);
      FD_SET (ui_socket, rfds);
      if (ui_socket + 1 > n)
	n = ui_socket + 1;

      /*
       * XXX Some day we might want to deal with an abstract application
       * class instead, with many instantiations possible.
       */
      if (!app_none && app_socket >= 0)
	{
	  FD_SET (app_socket, rfds);
	  if (app_socket + 1 > n)
	    n = app_socket + 1;
	}

      /* Setup the descriptors that have pending messages to send.  */
      memset (wfds, 0, mask_size);
      m = transport_pending_wfd_set (wfds);
      if (m > n)
	n = m;

      /* Find out when the next timed event is.  */
      timeout = &tv;
      timer_next_event (&timeout);

      n = select (n, rfds, wfds, 0, timeout);
      if (n == -1)
	{
	  if (errno != EINTR)
	    {
	      log_error ("select");

	      /*
	       * In order to give the unexpected error condition time to
	       * resolve without letting this process eat up all available CPU
	       * we sleep for a short while.
	       */
	      sleep (1);
	    }
	}
      else if (n)
	{
	  transport_handle_messages (rfds);
	  transport_send_messages (wfds);
	  if (FD_ISSET (ui_socket, rfds))
	    ui_handler ();
	  if (!app_none && app_socket >= 0 && FD_ISSET (app_socket, rfds))
	    app_handler ();
	}
      timer_handle_expirations ();
    }
}
示例#22
0
int main(int argc, char** args) {
    int argchar;
	char* infn = NULL;
	char* outfn = NULL;
	unsigned int row;
	int bits;
	FILE* fid = stdin;
	FILE* fout = stdout;
	int loglvl = LOG_MSG;
	char* progname = args[0];
	int bzero = 0;
	int outformat;
	qfits_header* hdr;
	unsigned int plane;
	off_t datastart;
	anbool onepass = FALSE;
	bl* pixcache = NULL;

#if HAVE_NETPBM
	struct pam img;
	tuple * tuplerow;
#else
	void* rowbuf;
#endif
	int W, H, depth, maxval;

    while ((argchar = getopt (argc, args, OPTIONS)) != -1)
        switch (argchar) {
		case '?':
		case 'h':
			printHelp(progname);
			exit(0);
		case 'v':
			loglvl++;
			break;
		case 'q':
			loglvl--;
			break;
		case 'o':
			outfn = optarg;
			break;
		}

	log_init(loglvl);
	log_to(stderr);
	fits_use_error_system();

	if (optind == argc) {
		// ok, stdin to stdout.
	} else if (optind == argc-1) {
		infn = args[optind];
	} else if (optind == argc-2) {
		infn = args[optind];
		outfn = args[optind+1];
	} else {
		printHelp(progname);
		exit(-1);
	}

	if (infn && !streq(infn, "-")) {
		fid = fopen(infn, "rb");
		if (!fid) {
			SYSERROR("Failed to open input file %s", infn);
			exit(-1);
		}
	}
	if (outfn) {
		fout = fopen(outfn, "wb");
		if (!fid) {
			SYSERROR("Failed to open output file %s", outfn);
			exit(-1);
		}
	} else
		outfn = "stdout";

#if HAVE_NETPBM
	pm_init(args[0], 0);
	pnm_readpaminit(fid, &img, 
					// PAM_STRUCT_SIZE isn't defined until Netpbm 10.23 (July 2004)
#if defined(PAM_STRUCT_SIZE)
					PAM_STRUCT_SIZE(tuple_type)
#else
					sizeof(struct pam)
#endif
);
	W = img.width;
	H = img.height;
	depth = img.depth;
	maxval = img.maxval;

	tuplerow = pnm_allocpamrow(&img);
	bits = pm_maxvaltobits(img.maxval); 
	bits = (bits <= 8) ? 8 : 16;

#else // No NETPBM

	if (parse_pnm_header(fid, &W, &H, &depth, &maxval)) {
		ERROR("Failed to parse PNM header from file: %s\n", infn ? infn : "<stdin>");
		exit(-1);
	}
	bits = 8 * maxval_to_bytes(maxval);

	rowbuf = malloc(W * depth * (bits/8));

#endif

	logmsg("Read file %s: %i x %i pixels x %i color(s); maxval %i\n",
		   infn ? infn : "stdin", W, H, depth, maxval);
	if (bits == 8)
		outformat = BPP_8_UNSIGNED;
	else {
		outformat = BPP_16_SIGNED;
		if (maxval >= INT16_MAX)
			bzero = 0x8000;
	}
	logmsg("Using %i-bit output\n", bits);

	hdr = fits_get_header_for_image3(W, H, outformat, depth, NULL);
	if (bzero)
		fits_header_add_int(hdr, "BZERO", bzero, "Number that has been subtracted from pixel values");
	if (qfits_header_dump(hdr, fout)) {
		ERROR("Failed to write FITS header to file %s", outfn);
		exit(-1);
	}
	qfits_header_destroy(hdr);

	datastart = ftello(fid);
	// Figure out if we can seek backward in this input file...
	if ((fid == stdin) ||
		(fseeko(fid, 0, SEEK_SET) ||
		 fseeko(fid, datastart, SEEK_SET)))
		// Nope!
		onepass = TRUE;
	if (onepass && depth > 1) {
		logmsg("Reading in one pass\n");
		pixcache = bl_new(16384, bits/8);
	}

	for (plane=0; plane<depth; plane++) {
		if (plane > 0) {
			if (fseeko(fid, datastart, SEEK_SET)) {
				SYSERROR("Failed to seek back to start of image data");
				exit(-1);
			}
		}
		for (row = 0; row<H; row++) {
			unsigned int column;

#if HAVE_NETPBM
			pnm_readpamrow(&img, tuplerow);
#else
			read_pnm_row(fid, W, depth, maxval, rowbuf);
#endif

			for (column = 0; column<W; column++) {
				int rtn;
				int pixval;

#if HAVE_NETPBM
				pixval = tuplerow[column][plane];
#else
				pixval = (bits == 8 ?
						  ((uint8_t *)rowbuf)[column*depth + plane] :
						  ((uint16_t*)rowbuf)[column*depth + plane]);
#endif
				if (outformat == BPP_8_UNSIGNED)
					rtn = fits_write_data_B(fout, pixval);
				else
					rtn = fits_write_data_I(fout, pixval-bzero, TRUE);
				if (rtn) {
					ERROR("Failed to write FITS pixel");
					exit(-1);
				}
			}
			if (onepass && depth > 1) {
				for (column = 0; column<W; column++) {
					for (plane=1; plane<depth; plane++) {
						int pixval;
#if HAVE_NETPBM
						pixval = tuplerow[column][plane];
#else
						pixval = (bits == 8 ?
								  ((uint8_t *)rowbuf)[column*depth + plane] :
								  ((uint16_t*)rowbuf)[column*depth + plane]);
#endif
						if (outformat == BPP_8_UNSIGNED) {
							uint8_t pix = pixval;
							bl_append(pixcache, &pix);
						} else {
							int16_t pix = pixval - bzero;
							bl_append(pixcache, &pix);
						}
					}
				}
			}
		}
	}
	
#if HAVE_NETPBM
	pnm_freepamrow(tuplerow);
#else
	free(rowbuf);
#endif

	if (pixcache) {
		int i, j;
		int step = (depth - 1);
		logverb("Writing %zu queued pixels\n", bl_size(pixcache));
		for (plane=1; plane<depth; plane++) {
			j = (plane - 1);
			for (i=0; i<(W * H); i++) {
				int rtn;
				if (outformat == BPP_8_UNSIGNED) {
					uint8_t* pix = bl_access(pixcache, j);
					rtn = fits_write_data_B(fout, *pix);
				} else {
					int16_t* pix = bl_access(pixcache, j);
					rtn = fits_write_data_I(fout, *pix, TRUE);
				}
				if (rtn) {
					ERROR("Failed to write FITS pixel");
					exit(-1);
				}
				j += step;
			}
		}
		bl_free(pixcache);
	}

	if (fid != stdin)
		fclose(fid);

	if (fits_pad_file(fout)) {
		ERROR("Failed to pad output file \"%s\"", outfn);
		return -1;
	}

	if (fout != stdout)
		if (fclose(fout)) {
			SYSERROR("Failed to close output file %s", outfn);
			exit(-1);
		}

	return 0;
}
示例#23
0
int main(int argc, char *argv[]) {
  int argchar;

  char* infn = NULL;
  char* outfn = NULL;
  anbool tostdout = FALSE;
  FILE* fin = NULL;
  FILE* fout = NULL;
  il* exts;
  int i;
  char* progname = argv[0];
  anbool inblocks = FALSE;
  anbool inmegs = FALSE;
  int allexts = 0;
  int Next = -1;
  anbool dataonly = FALSE;
  anbool headeronly = FALSE;
  anqfits_t* anq = NULL;
  int loglvl = LOG_MSG;

  exts = il_new(16);

  while ((argchar = getopt (argc, argv, OPTIONS)) != -1)
    switch (argchar) {
    case 'v':
        loglvl++;
        break;
    case 'D':
      dataonly = TRUE;
      break;
    case 'H':
      headeronly = TRUE;
      break;
    case 'a':
      allexts = 1;
      break;
    case 'b':
      inblocks = TRUE;
      break;
    case 'M':
      inmegs = TRUE;
      break;
    case 'e':
      il_append(exts, atoi(optarg));
      break;
    case 'i':
      infn = optarg;
      break;
    case 'o':
      outfn = optarg;
      break;
    case '?':
    case 'h':
      printHelp(progname);
      return 0;
    default:
      return -1;
    }

  if (headeronly && dataonly) {
    fprintf(stderr, "Can't write data blocks only AND header blocks only!\n");
    exit(-1);
  }

  if (inblocks && inmegs) {
    fprintf(stderr, "Can't write sizes in FITS blocks and megabytes.\n");
    exit(-1);
  }

  fits_use_error_system();
  log_init(loglvl);
  log_to(stderr);
  errors_log_to(stderr);

  if (infn) {
    anq = anqfits_open(infn);
    if (!anq) {
      ERROR("Failed to open input file \"%s\"", infn);
      exit(-1);
    }
    Next = anqfits_n_ext(anq);
    fprintf(stderr, "File %s contains %i FITS extensions.\n", infn, Next);
  }

  if (infn && !outfn) {
    for (i=0; i<Next; i++) {
      off_t hdrstart, hdrlen, datastart, datalen;

      hdrstart  = anqfits_header_start(anq, i);
      hdrlen    = anqfits_header_size(anq, i);
      datastart = anqfits_data_start(anq, i);
      datalen   = anqfits_data_size(anq, i);

      if (inblocks) {
	off_t block = (off_t)FITS_BLOCK_SIZE;
	fprintf(stderr, "Extension %i : header start %zu , length %zu ; data start %zu , length %zu blocks.\n",
			i, (size_t)(hdrstart / block), (size_t)(hdrlen / block), (size_t)(datastart / block), (size_t)(datalen / block));
      } else if (inmegs) {
	off_t meg = 1024*1024;
	fprintf(stderr, "Extension %i : header start %zu , length %zu ; data start %zu , length %zu megabytes.\n",
			i, (size_t)(hdrstart/meg), (size_t)(hdrlen/meg), (size_t)(datastart/meg), (size_t)(datalen/meg));
      } else {
	fprintf(stderr, "Extension %i : header start %zu , length %zu ; data start %zu , length %zu .\n",
			i, (size_t)hdrstart, (size_t)hdrlen, (size_t)datastart, (size_t)datalen);
      }
    }
    anqfits_close(anq);
    exit(0);
  }

  if (!infn || !outfn || !(il_size(exts) || allexts)) {
    printHelp(progname);
    exit(-1);
  }

  if (!strcmp(outfn, "-")) {
    tostdout = TRUE;
    if (allexts) {
      fprintf(stderr, "Specify all extensions (-a) and outputting to stdout (-o -) doesn't make much sense...\n");
      exit(-1);
    }
  }

  if (infn) {
    fin = fopen(infn, "rb");
    if (!fin) {
      fprintf(stderr, "Failed to open input file %s: %s\n", infn, strerror(errno));
      exit(-1);
    }
  }

  if (tostdout)
    fout = stdout;
  else {
    if (allexts)
      for (i=0; i<Next; i++)
	il_append(exts, i);
    else {
      // open the (single) output file.
      fout = fopen(outfn, "wb");
      if (!fout) {
	fprintf(stderr, "Failed to open output file %s: %s\n", outfn, strerror(errno));
	exit(-1);
      }
    }
  }

  for (i=0; i<il_size(exts); i++) {
    off_t hdrstart, hdrlen, datastart, datalen;
    int ext = il_get(exts, i);

    if (allexts) {
      char fn[256];
      snprintf(fn, sizeof(fn), outfn, ext);
      fout = fopen(fn, "wb");
      if (!fout) {
	fprintf(stderr, "Failed to open output file %s: %s\n", fn, strerror(errno));
	exit(-1);
      }
    }

    hdrstart  = anqfits_header_start(anq, ext);
    hdrlen    = anqfits_header_size(anq, ext);
    datastart = anqfits_data_start(anq, ext);
    datalen   = anqfits_data_size(anq, ext);

    if (inblocks) {
      off_t block = (off_t)FITS_BLOCK_SIZE;
      fprintf(stderr, "Writing extension %i : header start %zu , length %zu ; data start %zu , length %zu blocks.\n",
			  ext, (size_t)(hdrstart / block), (size_t)(hdrlen / block), (size_t)(datastart / block), (size_t)(datalen / block));
    } else if (inmegs) {
      off_t meg = 1024*1024;
      fprintf(stderr, "Writing extension %i : header start %zu , length %zu ; data start %zu , length %zu megabytes.\n",
			  ext, (size_t)(hdrstart/meg), (size_t)(hdrlen/meg), (size_t)(datastart/meg), (size_t)(datalen/meg));
    } else {
      fprintf(stderr, "Writing extension %i : header start %zu , length %zu ; data start %zu , length %zu .\n",
	      ext, (size_t)hdrstart, (size_t)hdrlen, (size_t)datastart, (size_t)datalen);
    }

    if (hdrlen && !dataonly) {
      if (pipe_file_offset(fin, hdrstart, hdrlen, fout)) {
	fprintf(stderr, "Failed to write header for extension %i: %s\n", ext, strerror(errno));
	exit(-1);
      }
    }
    if (datalen && !headeronly) {
      if (pipe_file_offset(fin, datastart, datalen, fout)) {
	fprintf(stderr, "Failed to write data for extension %i: %s\n", ext, strerror(errno));
	exit(-1);
      }
    }

    if (allexts)
      if (fclose(fout)) {
	fprintf(stderr, "Failed to close output file: %s\n", strerror(errno));
	exit(-1);
      }
  }

  fclose(fin);
  if (!allexts && !tostdout)
    fclose(fout);
  il_free(exts);
  anqfits_close(anq);
  return 0;
}
示例#24
0
int main(int argc, char** args) {
	int c;
	dl* xys = dl_new(16);
	dl* radecs = dl_new(16);
	dl* otherradecs = dl_new(16);

	double* xy;
	double* xyz;
	int i, N;
	tan_t tan, tan2, tan3;
	int W=0, H=0;
	double crpix[] = { HUGE_VAL, HUGE_VAL };
	int loglvl = LOG_MSG;
	FILE* logstream = stderr;
	int order = 1;

    while ((c = getopt(argc, args, OPTIONS)) != -1) {
        switch (c) {
		case 'v':
			loglvl++;
			break;
		case 'h':
			exit(0);
		case 'o':
			order = atoi(optarg);
			break;
		case 'W':
			W = atoi(optarg);
			break;
		case 'H':
			H = atoi(optarg);
			break;
		case 'X':
			crpix[0] = atof(optarg);
			break;
		case 'Y':
			crpix[1] = atof(optarg);
			break;
		}
	}
	if (optind != argc) {
		exit(-1);
	}
	log_init(loglvl);
	log_to(logstream);
	errors_log_to(logstream);

	if (W == 0 || H == 0) {
		logerr("Need -W, -H\n");
		exit(-1);
	}
	if (crpix[0] == HUGE_VAL)
		crpix[0] = W/2.0;
	if (crpix[1] == HUGE_VAL)
		crpix[1] = H/2.0;

	while (1) {
		double x,y,ra,dec;
		if (fscanf(stdin, "%lf %lf %lf %lf\n", &x, &y, &ra, &dec) < 4)
			break;
		if (x == -1 && y == -1) {
			dl_append(otherradecs, ra);
			dl_append(otherradecs, dec);
		} else {
			dl_append(xys, x);
			dl_append(xys, y);
			dl_append(radecs, ra);
			dl_append(radecs, dec);
		}
	}
	logmsg("Read %i x,y,ra,dec tuples\n", dl_size(xys)/2);

	N = dl_size(xys)/2;
	xy = dl_to_array(xys);
	xyz = malloc(3 * N * sizeof(double));
	for (i=0; i<N; i++)
		radecdeg2xyzarr(dl_get(radecs, 2*i), dl_get(radecs, 2*i+1), xyz + i*3);
	dl_free(xys);
	dl_free(radecs);

	fit_tan_wcs(xyz, xy, N, &tan, NULL);
	tan.imagew = W;
	tan.imageh = H;

	logmsg("Computed TAN WCS:\n");
	tan_print_to(&tan, logstream);

	sip_t* sip;
	{
		tweak_t* t = tweak_new();
		starxy_t* sxy = starxy_new(N, FALSE, FALSE);
		il* imginds = il_new(256);
		il* refinds = il_new(256);

		for (i=0; i<N; i++) {
			starxy_set_x(sxy, i, xy[2*i+0]);
			starxy_set_y(sxy, i, xy[2*i+1]);
		}
		tweak_init(t);
		tweak_push_ref_xyz(t, xyz, N);
		tweak_push_image_xy(t, sxy);
		for (i=0; i<N; i++) {
			il_append(imginds, i);
			il_append(refinds, i);
		}
		// unweighted; no dist2s
		tweak_push_correspondence_indices(t, imginds, refinds, NULL, NULL);

		tweak_push_wcs_tan(t, &tan);
		t->sip->a_order = t->sip->b_order = t->sip->ap_order = t->sip->bp_order = order;

		for (i=0; i<10; i++) {
			// go to TWEAK_HAS_LINEAR_CD -> do_sip_tweak
			// t->image has the indices of corresponding image stars
			// t->ref   has the indices of corresponding catalog stars
			tweak_go_to(t, TWEAK_HAS_LINEAR_CD);
			logmsg("\n");
			sip_print(t->sip);
			t->state &= ~TWEAK_HAS_LINEAR_CD;
		}
		tan_write_to_file(&t->sip->wcstan, "kt1.wcs");
		sip = t->sip;
	}

	for (i=0; i<dl_size(otherradecs)/2; i++) {
		double ra, dec, x,y;
		ra = dl_get(otherradecs, 2*i);
		dec = dl_get(otherradecs, 2*i+1);
		if (!sip_radec2pixelxy(sip, ra, dec, &x, &y)) {
			logerr("Not in tangent plane: %g,%g\n", ra, dec);
			exit(-1);
			//continue;
		}
		printf("%g %g\n", x, y);
	}

	/*
	 blind_wcs_move_tangent_point(xyz, xy, N, crpix, &tan, &tan2);
	 blind_wcs_move_tangent_point(xyz, xy, N, crpix, &tan2, &tan3);
	 logmsg("Moved tangent point to (%g,%g):\n", crpix[0], crpix[1]);
	 tan_print_to(&tan3, logstream);
	 tan_write_to_file(&tan, "kt1.wcs");
	 tan_write_to_file(&tan3, "kt2.wcs");
	 */

	dl_free(otherradecs);
	free(xy);
	free(xyz);
	return 0;
}
示例#25
0
int main(int argc, char** args) {
    char* default_configfn = "astrometry.cfg";
    char* default_config_path = "../etc";

	int c;
	char* configfn = NULL;
	int i;
	engine_t* engine;
    char* mydir = NULL;
    char* basedir = NULL;
    char* me;
    anbool help = FALSE;
    sl* strings = sl_new(4);
    char* cancelfn = NULL;
    char* solvedfn = NULL;
    int loglvl = LOG_MSG;
    anbool tostderr = FALSE;
    char* infn = NULL;
    FILE* fin = NULL;
    anbool fromstdin = FALSE;

	bl* opts = opts_from_array(myopts, sizeof(myopts)/sizeof(an_option_t), NULL);
	sl* inds = sl_new(4);

	char* datalog = NULL;

	engine = engine_new();

	while (1) {
		c = opts_getopt(opts, argc, args);
		if (c == -1)
			break;
		switch (c) {
		case 'D':
			datalog = optarg;
			break;
		case 'p':
			engine->inparallel = TRUE;
			break;
		case 'i':
			sl_append(inds, optarg);
			break;
		case 'd':
		  basedir = optarg;
		  break;
        case 'f':
            infn = optarg;
            fromstdin = streq(infn, "-");
            break;
        case 'E':
            tostderr = TRUE;
            break;
		case 'h':
            help = TRUE;
			break;
        case 'v':
            loglvl++;
            break;
		case 's':
		  solvedfn = optarg;
        case 'C':
            cancelfn = optarg;
            break;
		case 'c':
			configfn = strdup(optarg);
			break;
		case '?':
			break;
		default:
            printf("Unknown flag %c\n", c);
			exit( -1);
		}
	}

	if (optind == argc && !infn) {
		// Need extra args: filename
		printf("You must specify at least one input file!\n\n");
		help = TRUE;
	}
	if (help) {
		print_help(args[0], opts);
		exit(0);
	}
	bl_free(opts);

	gslutils_use_error_system();

    log_init(loglvl);
    if (tostderr)
        log_to(stderr);

	if (datalog) {
		datalogfid = fopen(datalog, "wb");
		if (!datalogfid) {
			SYSERROR("Failed to open data log file \"%s\" for writing", datalog);
			return -1;
		}
		atexit(close_datalogfid);
		data_log_init(100);
		data_log_enable_all();
		data_log_to(datalogfid);
		data_log_start();
	}

    if (infn) {
        logverb("Reading input filenames from %s\n", (fromstdin ? "stdin" : infn));
        if (!fromstdin) {
            fin = fopen(infn, "rb");
            if (!fin) {
                ERROR("Failed to open file %s for reading input filenames", infn);
                exit(-1);
            }
        } else
            fin = stdin;
    }

    // directory containing the 'engine' executable:
    me = find_executable(args[0], NULL);
    if (!me)
        me = strdup(args[0]);
    mydir = sl_append(strings, dirname(me));
    free(me);

	// Read config file
    if (!configfn) {
        int i;
        sl* trycf = sl_new(4);
        sl_appendf(trycf, "%s/%s/%s", mydir, default_config_path, default_configfn);
        // if I'm in /usr/bin, look for config file in /etc
        if (streq(mydir, "/usr/bin")) {
            sl_appendf(trycf, "/etc/%s", default_configfn);
        }
        sl_appendf(trycf, "%s/%s", mydir, default_configfn);
        sl_appendf(trycf, "./%s", default_configfn);
        sl_appendf(trycf, "./%s/%s", default_config_path, default_configfn);
        for (i=0; i<sl_size(trycf); i++) {
            char* cf = sl_get(trycf, i);
            if (file_exists(cf)) {
                configfn = strdup(cf);
                logverb("Using config file \"%s\"\n", cf);
                break;
            } else {
                logverb("Config file \"%s\" doesn't exist.\n", cf);
            }
        }
        if (!configfn) {
            char* cflist = sl_join(trycf, "\n  ");
            logerr("Couldn't find config file: tried:\n  %s\n", cflist);
            free(cflist);
        }
        sl_free2(trycf);
    }

	if (!streq(configfn, "none")) {
		if (engine_parse_config_file(engine, configfn)) {
			logerr("Failed to parse (or encountered an error while interpreting) config file \"%s\"\n", configfn);
			exit( -1);
		}
	}

	if (sl_size(inds)) {
		// Expand globs.
		for (i=0; i<sl_size(inds); i++) {
			char* s = sl_get(inds, i);
			glob_t myglob;
			int flags = GLOB_TILDE | GLOB_BRACE;
			if (glob(s, flags, NULL, &myglob)) {
				SYSERROR("Failed to expand wildcards in index-file path \"%s\"", s);
				exit(-1);
			}
			for (c=0; c<myglob.gl_pathc; c++) {
				if (engine_add_index(engine, myglob.gl_pathv[c])) {
					ERROR("Failed to add index \"%s\"", myglob.gl_pathv[c]);
					exit(-1);
				}
			}
			globfree(&myglob);
		}
	}

	if (!pl_size(engine->indexes)) {
		logerr("\n\n"
			   "---------------------------------------------------------------------\n"
			   "You must list at least one index in the config file (%s)\n\n"
			   "See http://astrometry.net/use.html about how to get some index files.\n"
			   "---------------------------------------------------------------------\n"
			   "\n", configfn);
		exit(-1);
	}

	if (engine->minwidth <= 0.0 || engine->maxwidth <= 0.0) {
		logerr("\"minwidth\" and \"maxwidth\" in the config file %s must be positive!\n", configfn);
		exit(-1);
	}

    free(configfn);

    if (!il_size(engine->default_depths)) {
        parse_depth_string(engine->default_depths,
                           "10 20 30 40 50 60 70 80 90 100 "
                           "110 120 130 140 150 160 170 180 190 200");
    }

    engine->cancelfn = cancelfn;
    engine->solvedfn = solvedfn;

    i = optind;
    while (1) {
		char* jobfn;
        job_t* job;
		struct timeval tv1, tv2;

        if (infn) {
            // Read name of next input file to be read.
            logverb("\nWaiting for next input filename...\n");
            jobfn = read_string_terminated(fin, "\n\r\0", 3, FALSE);
            if (strlen(jobfn) == 0)
                break;
        } else {
            if (i == argc)
                break;
            jobfn = args[i];
            i++;
        }
        gettimeofday(&tv1, NULL);
        logmsg("Reading file \"%s\"...\n", jobfn);
        job = engine_read_job_file(engine, jobfn);
        if (!job) {
            ERROR("Failed to read job file \"%s\"", jobfn);
            exit(-1);
        }

	if (basedir) {
	  logverb("Setting job's output base directory to %s\n", basedir);
	  job_set_output_base_dir(job, basedir);
	}

		if (engine_run_job(engine, job))
			logerr("Failed to run_job()\n");

		job_free(job);
        gettimeofday(&tv2, NULL);
		logverb("Spent %g seconds on this field.\n", millis_between(&tv1, &tv2)/1000.0);
	}

	engine_free(engine);
    sl_free2(strings);
	sl_free2(inds);

    if (fin && !fromstdin)
        fclose(fin);

    return 0;
}
示例#26
0
//---------------------------------------------------------------------------
void dma_sound_set_mode(BYTE new_mode)
{
  dma_sound_mode=new_mode;
  dma_sound_freq=dma_sound_mode_to_freq[dma_sound_mode & 3];
  log_to(LOGSECTION_SOUND,EasyStr("SOUND: ")+HEXSl(old_pc,6)+" - DMA sound mode set to $"+HEXSl(dma_sound_mode,2)+" freq="+dma_sound_freq);
}