Example #1
0
static int conn_handle_ports (uint16_t port_local, uint16_t port_remote, uint8_t state)
{
  port_entry_t *pe = NULL;

  if ((state > TCP_STATE_MAX)
#if TCP_STATE_MIN > 0
      || (state < TCP_STATE_MIN)
#endif
     )
  {
    NOTICE ("tcpconns plugin: Ignoring connection with "
	"unknown state 0x%02"PRIx8".", state);
    return (-1);
  }

  count_total[state]++;

  /* Listening sockets */
  if ((state == TCP_STATE_LISTEN) && (port_collect_listening != 0))
  {
    pe = conn_get_port_entry (port_local, 1 /* create */);
    if (pe != NULL)
      pe->flags |= PORT_IS_LISTENING;
  }

  DEBUG ("tcpconns plugin: Connection %"PRIu16" <-> %"PRIu16" (%s)",
      port_local, port_remote, tcp_state[state]);

  pe = conn_get_port_entry (port_local, 0 /* no create */);
  if (pe != NULL)
    pe->count_local[state]++;

  pe = conn_get_port_entry (port_remote, 0 /* no create */);
  if (pe != NULL)
    pe->count_remote[state]++;

  return (0);
} /* int conn_handle_ports */
Example #2
0
int rt2x00lib_suspend(struct rt2x00_dev *rt2x00dev, pm_message_t state)
{
	NOTICE(rt2x00dev, "Going to sleep.\n");

	/*
	 * Prevent mac80211 from accessing driver while suspended.
	 */
	if (!test_and_clear_bit(DEVICE_STATE_PRESENT, &rt2x00dev->flags))
		return 0;

	/*
	 * Cleanup as much as possible.
	 */
	rt2x00lib_uninitialize(rt2x00dev);

	/*
	 * Suspend/disable extra components.
	 */
	rt2x00leds_suspend(rt2x00dev);
	rt2x00debug_deregister(rt2x00dev);

	/*
	 * Set device mode to sleep for power management,
	 * on some hardware this call seems to consistently fail.
	 * From the specifications it is hard to tell why it fails,
	 * and if this is a "bad thing".
	 * Overall it is safe to just ignore the failure and
	 * continue suspending. The only downside is that the
	 * device will not be in optimal power save mode, but with
	 * the radio and the other components already disabled the
	 * device is as good as disabled.
	 */
	if (rt2x00dev->ops->lib->set_device_state(rt2x00dev, STATE_SLEEP))
		WARNING(rt2x00dev, "Device failed to enter sleep state, "
			"continue suspending.\n");

	return 0;
}
Example #3
0
/*----------------------------------------------------------
 | daemonize
 |   set the process in background
 +--------------------------------------------------------- */
static void daemonize(struct afb_config *config)
{
  int            consoleFD;
  int            pid;

      // open /dev/console to redirect output messAFBes
      consoleFD = open(config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
      if (consoleFD < 0) {
  		ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
  		exit (1);
      }

      // fork process when running background mode
      pid = fork ();

      // if fail nothing much to do
      if (pid == -1) {
  		ERROR("AFB-daemon Failed to fork son process");
  		exit (1);
	}

      // if in father process, just leave
      if (pid != 0) _exit (0);

      // son process get all data in standalone mode
     NOTICE("background mode [pid:%d console:%s]", getpid(),config->console);

      // redirect default I/O on console
      close (2); dup(consoleFD);  // redirect stderr
      close (1); dup(consoleFD);  // redirect stdout
      close (0);           // no need for stdin
      close (consoleFD);

#if 0
  	 setsid();   // allow father process to fully exit
     sleep (2);  // allow main to leave and release port
#endif
}
Example #4
0
static int rt2400pci_set_state(struct rt2x00_dev *rt2x00dev,
			       enum dev_state state)
{
	u32 reg;
	unsigned int i;
	char put_to_sleep;
	char bbp_state;
	char rf_state;

	put_to_sleep = (state != STATE_AWAKE);

	rt2x00pci_register_read(rt2x00dev, PWRCSR1, &reg);
	rt2x00_set_field32(&reg, PWRCSR1_SET_STATE, 1);
	rt2x00_set_field32(&reg, PWRCSR1_BBP_DESIRE_STATE, state);
	rt2x00_set_field32(&reg, PWRCSR1_RF_DESIRE_STATE, state);
	rt2x00_set_field32(&reg, PWRCSR1_PUT_TO_SLEEP, put_to_sleep);
	rt2x00pci_register_write(rt2x00dev, PWRCSR1, reg);

	/*
	 * Device is not guaranteed to be in the requested state yet.
	 * We must wait until the register indicates that the
	 * device has entered the correct state.
	 */
	for (i = 0; i < REGISTER_BUSY_COUNT; i++) {
		rt2x00pci_register_read(rt2x00dev, PWRCSR1, &reg);
		bbp_state = rt2x00_get_field32(reg, PWRCSR1_BBP_CURR_STATE);
		rf_state = rt2x00_get_field32(reg, PWRCSR1_RF_CURR_STATE);
		if (bbp_state == state && rf_state == state)
			return 0;
		msleep(10);
	}

	NOTICE(rt2x00dev, "Device failed to enter state %d, "
	       "current device state: bbp %d and rf %d.\n",
	       state, bbp_state, rf_state);

	return -EBUSY;
}
static uintptr_t trusty_generic_platform_smc(uint32_t smc_fid,
			 u_register_t x1,
			 u_register_t x2,
			 u_register_t x3,
			 u_register_t x4,
			 void *cookie,
			 void *handle,
			 u_register_t flags)
{
	switch (smc_fid) {
	case SMC_FC_DEBUG_PUTC:
		trusty_dputc(x1, is_caller_secure(flags));
		SMC_RET1(handle, 0);

	case SMC_FC_GET_REG_BASE:
	case SMC_FC64_GET_REG_BASE:
		SMC_RET1(handle, trusty_get_reg_base(x1));

	default:
		NOTICE("%s(0x%x, 0x%lx) unknown smc\n", __func__, smc_fid, x1);
		SMC_RET1(handle, SMC_UNK);
	}
}
Example #6
0
void init_container_store() {

	sds containerfile = sdsdup(destor.working_directory);
	containerfile = sdscat(containerfile, "/container.pool");

	if ((fp = fopen(containerfile, "r+"))) {
		fread(&container_count, 8, 1, fp);
	} else if (!(fp = fopen(containerfile, "w+"))) {
		perror(
				"Can not create container.pool for read and write because");
		exit(1);
	}

	sdsfree(containerfile);

	container_buffer = sync_queue_new(25);

	pthread_mutex_init(&mutex, NULL);

	pthread_create(&append_t, NULL, append_thread, NULL);

    NOTICE("Init container store successfully");
}
Example #7
0
void VoxPlayer::run()
{
    sigset_t mask;
    sigfillset(&mask);
    pthread_sigmask(SIG_BLOCK, &mask, NULL);

    INFORMATION("(PLAY) start of loop");

    while(!g_main.isExit())
    {
        if(!m_playpath.empty())
        {
            std::string path = m_playpath;
            NOTICE("(PLAY) async play '%s'", path.c_str());
            aoplay(path);
            m_playpath = "";
        }

        delay(100);
    }

    INFORMATION("(PLAY) end of loop");
}
Example #8
0
int sunaudio_init(audiodevice_t *dev, char *devaudio, char *devaudioctl) {
	audio_sun_t *asun;

	asun = g_new0(audio_sun_t, 1);
	
	asun->fd = -1;
	asun->dev = (devaudio == NULL ? "/dev/audio" : devaudio);
	mixer_init(dev, devaudioctl);
	
	dev->data_pcm = asun;
	dev->id = AUDIO_PCM_SUN;
	dev->fd = -1;
	dev->open = audio_open;
	dev->close = audio_close;
	dev->write = audio_write;
	dev->mix_set = mixer_set_level;
	dev->mix_get = mixer_get_level;
	dev->exit = sunaudio_exit;
	
	NOTICE("SUN audio Initilize OK\n");
	
	return OK;
}
Example #9
0
 /** @par
  *  This function is executed at the end of main(), after the necessary subsystems
  *  have been started, typically in separate threads. Thus, the main thread will
  *  enter a blocking wait, until all activated subsystems have signalled shutdown.
  *  After returning, we can proceed with the normal shutdown sequence.
  *  
  *  The SubsystemRunner ensures that in case of a premature failure of one subsystem,
  *  the termination of all other subsystems is initiated; when detecting this case,
  *  the emergency exit sequence is called. Any error which can't be handled within
  *  this scheme, should be thrown as exception, in which case the abort handler
  *  is activated.  
  */
 ExitCode
 AppState::maybeWait()
 {
   if (subsystems_)
     {
       emergency_ |= subsystems_->wait();
       subsystems_.reset(0);
     }
   
   NOTICE (common, "Shutting down Lumiera...");
   
   if (emergency_)
     {
       ALERT (common, "Triggering emergency exit...");
       LifecycleHook::trigger (ON_EMERGENCY);
       return CLEAN_EMERGENCY_EXIT;
     }
   else
     {
       LifecycleHook::trigger (ON_GLOBAL_SHUTDOWN);
       return NORMAL_EXIT;
     }
 }
Example #10
0
static size_t apache_header_callback (void *buf, size_t size, size_t nmemb,
		void *user_data)
{
	size_t len = size * nmemb;
	apache_t *st;

	st = user_data;
	if (st == NULL)
	{
		ERROR ("apache plugin: apache_header_callback: "
				"user_data pointer is NULL.");
		return (0);
	}

	if (len <= 0)
		return (len);

	/* look for the Server header */
	if (strncasecmp (buf, "Server: ", strlen ("Server: ")) != 0)
		return (len);

	if (strstr (buf, "Apache") != NULL)
		st->server_type = APACHE;
	else if (strstr (buf, "lighttpd") != NULL)
		st->server_type = LIGHTTPD;
	else if (strstr (buf, "IBM_HTTP_Server") != NULL)
		st->server_type = APACHE;
	else
	{
		const char *hdr = buf;

		hdr += strlen ("Server: ");
		NOTICE ("apache plugin: Unknown server software: %s", hdr);
	}

	return (len);
} /* apache_header_callback */
Example #11
0
static int cj_cb_string (void *ctx, const unsigned char *val,
                           unsigned int len)
{
  cj_t *db = (cj_t *)ctx;
  char str[len + 1];

  /* Create a null-terminated version of the string. */
  memcpy (str, val, len);
  str[len] = 0;

  /* No configuration for this string -> simply return. */
  if (db->state[db->depth].key == NULL)
    return (CJ_CB_CONTINUE);

  if (!CJ_IS_KEY (db->state[db->depth].key))
  {
    NOTICE ("curl_json plugin: Found string \"%s\", but the configuration "
        "expects a map here.", str);
    return (CJ_CB_CONTINUE);
  }

  /* Handle the string as if it was a number. */
  return (cj_cb_number (ctx, (const char *) val, len));
} /* int cj_cb_string */
Example #12
0
static void selinux_initialize(bool in_kernel_domain) {
    Timer t;

    selinux_callback cb;
    cb.func_log = selinux_klog_callback;
    selinux_set_callback(SELINUX_CB_LOG, cb);
    cb.func_audit = audit_callback;
    selinux_set_callback(SELINUX_CB_AUDIT, cb);

    if (in_kernel_domain) {
        INFO("Loading SELinux policy...\n");
        if (selinux_android_load_policy() < 0) {
            ERROR("failed to load policy: %s\n", strerror(errno));
            security_failure();
        }

        bool kernel_enforcing = (security_getenforce() == 1);
        bool is_enforcing = selinux_is_enforcing();
        if (kernel_enforcing != is_enforcing) {
            if (security_setenforce(is_enforcing)) {
                ERROR("security_setenforce(%s) failed: %s\n",
                      is_enforcing ? "true" : "false", strerror(errno));
                security_failure();
            }
        }

        if (write_file("/sys/fs/selinux/checkreqprot", "0") == -1) {
            security_failure();
        }

        NOTICE("(Initializing SELinux %s took %.2fs.)\n",
               is_enforcing ? "enforcing" : "non-enforcing", t.duration());
    } else {
        selinux_init_all_handles();
    }
}
Example #13
0
CoreServer::Result CoreServer::test()
{
#ifdef INTEL
    if (m_info.coreId != 0)
    {
        FileSystemMessage msg;
        msg.type   = ChannelMessage::Request;
        msg.action = StatFile;
        msg.path = (char *)0x12345678;
        msg.size = m_info.coreId;
        m_toMaster->write(&msg);
    }
    else
    {
        FileSystemMessage msg;
        Size numCores = m_cores->getCores().count();

        for (Size i = 1; i < numCores; i++)
        {
            MemoryChannel *ch = (MemoryChannel *) m_fromSlave->get(i);
            if (!ch)
                return IOError;

            // TODO: replace with ChannelClient::syncReceiveFrom
            while (ch->read(&msg) != Channel::Success);

            if (msg.action == StatFile)
            {
                NOTICE("core" << i << " send a Ping");
            }
        }

    }
#endif /* INTEL */
    return Success;
}
Example #14
0
static int apcups_config (oconfig_item_t *ci)
{
	int i;
	_Bool persistent_conn_set = 0;

	for (i = 0; i < ci->children_num; i++)
	{
		oconfig_item_t *child = ci->children + i;

		if (strcasecmp (child->key, "Host") == 0)
			cf_util_get_string (child, &conf_node);
		else if (strcasecmp (child->key, "Port") == 0)
			cf_util_get_service (child, &conf_service);
		else if (strcasecmp (child->key, "ReportSeconds") == 0)
			cf_util_get_boolean (child, &conf_report_seconds);
		else if (strcasecmp (child->key, "PersistentConnection") == 0) {
			cf_util_get_boolean (child, &conf_persistent_conn);
			persistent_conn_set = 1;
		}
		else
			ERROR ("apcups plugin: Unknown config option \"%s\".", child->key);
	}

	if (!persistent_conn_set) {
		double interval = CDTIME_T_TO_DOUBLE(plugin_get_interval());
		if (interval > APCUPS_SERVER_TIMEOUT) {
			NOTICE ("apcups plugin: Plugin poll interval set to %.3f seconds. "
				"Apcupsd NIS socket timeout is %.3f seconds, "
				"PersistentConnection disabled by default.",
				interval, APCUPS_SERVER_TIMEOUT);
			conf_persistent_conn = 0;
		}
	}

	return (0);
} /* int apcups_config */
AM_ERR CTsHttpWriter::ServerThreadLoop ()
{
   CURLcode res;
   double uploadSpeed, totalTime;
   char readFileName[MAX_FILE_NAME_LEN];

   mbRun = true;
   while (mbCurlRun) {
      if (mUploadIndex >= (mFileCounter - 1)) {
         /* Latest file has not been written completed. */
         mpWaitCond->Wait (mpMutex);
      }

      snprintf (readFileName, sizeof (readFileName),
            "/tmp/ts_file_%d.ts", mUploadIndex ++);

      /* Open latest file to prepare reading. */
      if ((mUploadFile = open (readFileName, O_RDONLY)) < 0) {
         ERROR ("Failed to open %s: %s",
               readFileName,
               strerror (errno));
         mpOwner->PostEngineMsg (IEngine::MSG_ERROR);

         mbCurlRun = false;
         return ME_ERROR;
      }

      if ((res = curl_easy_perform (mpCurlHandle)) != CURLE_OK) {
         mbCurlRun = false;
         ERROR ("curl_easy_perform error: %d\n", res);
         if ((res == CURLE_COULDNT_RESOLVE_HOST) ||
               (res == CURLE_COULDNT_CONNECT)) {
            ERROR ("Cann't connect to %s!", mpDestURL);
            mpOwner->PostEngineMsg (IEngine::MSG_ERROR);
         } else {
            NOTICE ("Recording will restart!");
            mpOwner->PostEngineMsg (IEngine::MSG_OVFL);
         }

         close(mUploadFile);
         mUploadFile = -1;
         return ME_ERROR;
      }

      /* Now, extract transfer info */
      curl_easy_getinfo (mpCurlHandle, CURLINFO_SPEED_UPLOAD, &uploadSpeed);
      curl_easy_getinfo (mpCurlHandle, CURLINFO_TOTAL_TIME, &totalTime);
      NOTICE ("\nSize: %.3f bytes/sec during %.3f seconds\n\n",
            uploadSpeed, totalTime);

      close (mUploadFile);
      mUploadFile = -1;
      if (remove (readFileName) < 0) {
         ERROR ("Failed to remove %s: %s",
               readFileName,
               strerror (errno));
      }

      if (totalTime >= (double)(CURL_TRANSFER_TIMEOUT)) {
         NOTICE ("Network is not good!");

         mbCurlRun = false;
         mpOwner->PostEngineMsg (IEngine::MSG_OVFL);
         return ME_ERROR;
      }

      if (!mbRun) {
         break;
      }
   }

   INFO ("Curl thread exit mainloop");
   return ME_OK;
}
Example #16
0
static int init (void)
{
#if PROCESSOR_CPU_LOAD_INFO
	kern_return_t status;

	port_host = mach_host_self ();

	/* FIXME: Free `cpu_list' if it's not NULL */
	if ((status = host_processors (port_host, &cpu_list, &cpu_list_len)) != KERN_SUCCESS)
	{
		ERROR ("cpu plugin: host_processors returned %i", (int) status);
		cpu_list_len = 0;
		return (-1);
	}

	DEBUG ("host_processors returned %i %s", (int) cpu_list_len, cpu_list_len == 1 ? "processor" : "processors");
	INFO ("cpu plugin: Found %i processor%s.", (int) cpu_list_len, cpu_list_len == 1 ? "" : "s");
/* #endif PROCESSOR_CPU_LOAD_INFO */

#elif defined(HAVE_LIBKSTAT)
	kstat_t *ksp_chain;

	numcpu = 0;

	if (kc == NULL)
		return (-1);

	/* Solaris doesn't count linear.. *sigh* */
	for (numcpu = 0, ksp_chain = kc->kc_chain;
			(numcpu < MAX_NUMCPU) && (ksp_chain != NULL);
			ksp_chain = ksp_chain->ks_next)
		if (strncmp (ksp_chain->ks_module, "cpu_stat", 8) == 0)
			ksp[numcpu++] = ksp_chain;
/* #endif HAVE_LIBKSTAT */

#elif CAN_USE_SYSCTL
	size_t numcpu_size;
	int mib[2] = {CTL_HW, HW_NCPU};
	int status;

	numcpu = 0;
	numcpu_size = sizeof (numcpu);

	status = sysctl (mib, STATIC_ARRAY_SIZE (mib),
			&numcpu, &numcpu_size, NULL, 0);
	if (status == -1)
	{
		char errbuf[1024];
		WARNING ("cpu plugin: sysctl: %s",
				sstrerror (errno, errbuf, sizeof (errbuf)));
		return (-1);
	}
/* #endif CAN_USE_SYSCTL */

#elif defined (HAVE_SYSCTLBYNAME)
	size_t numcpu_size;

	numcpu_size = sizeof (numcpu);

	if (sysctlbyname ("hw.ncpu", &numcpu, &numcpu_size, NULL, 0) < 0)
	{
		char errbuf[1024];
		WARNING ("cpu plugin: sysctlbyname(hw.ncpu): %s",
				sstrerror (errno, errbuf, sizeof (errbuf)));
		return (-1);
	}

#ifdef HAVE_SYSCTL_KERN_CP_TIMES
	numcpu_size = sizeof (maxcpu);

	if (sysctlbyname("kern.smp.maxcpus", &maxcpu, &numcpu_size, NULL, 0) < 0)
	{
		char errbuf[1024];
		WARNING ("cpu plugin: sysctlbyname(kern.smp.maxcpus): %s",
				sstrerror (errno, errbuf, sizeof (errbuf)));
		return (-1);
	}
#else
	if (numcpu != 1)
		NOTICE ("cpu: Only one processor supported when using `sysctlbyname' (found %i)", numcpu);
#endif
/* #endif HAVE_SYSCTLBYNAME */

#elif defined(HAVE_LIBSTATGRAB)
	/* nothing to initialize */
/* #endif HAVE_LIBSTATGRAB */

#elif defined(HAVE_PERFSTAT)
	/* nothing to initialize */
#endif /* HAVE_PERFSTAT */

	return (0);
} /* int init */
Example #17
0
/*
 * Subscribing code
 */
static int camqp_read_body (camqp_config_t *conf, /* {{{ */
        size_t body_size, const char *content_type)
{
    char body[body_size + 1];
    char *body_ptr;
    size_t received;
    amqp_frame_t frame;
    int status;

    memset (body, 0, sizeof (body));
    body_ptr = &body[0];
    received = 0;

    while (received < body_size)
    {
        status = amqp_simple_wait_frame (conf->connection, &frame);
        if (status < 0)
        {
            char errbuf[1024];
            status = (-1) * status;
            ERROR ("amqp plugin: amqp_simple_wait_frame failed: %s",
                    sstrerror (status, errbuf, sizeof (errbuf)));
            camqp_close_connection (conf);
            return (status);
        }

        if (frame.frame_type != AMQP_FRAME_BODY)
        {
            NOTICE ("amqp plugin: Unexpected frame type: %#"PRIx8,
                    frame.frame_type);
            return (-1);
        }

        if ((body_size - received) < frame.payload.body_fragment.len)
        {
            WARNING ("amqp plugin: Body is larger than indicated by header.");
            return (-1);
        }

        memcpy (body_ptr, frame.payload.body_fragment.bytes,
                frame.payload.body_fragment.len);
        body_ptr += frame.payload.body_fragment.len;
        received += frame.payload.body_fragment.len;
    } /* while (received < body_size) */

    if (strcasecmp ("text/collectd", content_type) == 0)
    {
        status = handle_putval (stderr, body);
        if (status != 0)
            ERROR ("amqp plugin: handle_putval failed with status %i.",
                    status);
        return (status);
    }
    else if (strcasecmp ("application/json", content_type) == 0)
    {
        ERROR ("amqp plugin: camqp_read_body: Parsing JSON data has not "
                "been implemented yet. FIXME!");
        return (0);
    }
    else
    {
        ERROR ("amqp plugin: camqp_read_body: Unknown content type \"%s\".",
                content_type);
        return (EINVAL);
    }

    /* not reached */
    return (0);
} /* }}} int camqp_read_body */
Example #18
0
void DrawPict(SDL_Surface *screen, char *bmpfile,
					int speedy, int flip, int nofade)
{
	SDL_Surface *picture;
	SDL_Rect dest, update;
	int i, centered;
	int ncolors;
	SDL_Color *colors, *cmap;

	/* Load the image into a surface */
	if ( bmpfile == NULL ) {
		bmpfile = "sample.bmp";		/* Sample image */
	}
fprintf(stderr, "Loading picture: %s\n", bmpfile);
	picture = SDL_LoadBMP(bmpfile);
	if ( picture == NULL ) {
		fprintf(stderr, "Couldn't load %s: %s\n", bmpfile,
							SDL_GetError());
		return;
	}

	/* Set the display colors -- on a hicolor display this is a no-op */
	if ( picture->format->palette ) {
		ncolors = picture->format->palette->ncolors;
		colors  = (SDL_Color *)malloc(ncolors*sizeof(SDL_Color));
		cmap    = (SDL_Color *)malloc(ncolors*sizeof(SDL_Color));
		memcpy(colors, picture->format->palette->colors,
						ncolors*sizeof(SDL_Color));
	} else {
		int       r, g, b;

		/* Allocate 256 color palette */
		ncolors = 256;
		colors  = (SDL_Color *)malloc(ncolors*sizeof(SDL_Color));
		cmap    = (SDL_Color *)malloc(ncolors*sizeof(SDL_Color));

		/* Set a 3,3,2 color cube */
		for ( r=0; r<8; ++r ) {
			for ( g=0; g<8; ++g ) {
				for ( b=0; b<4; ++b ) {
					i = ((r<<5)|(g<<2)|b);
					colors[i].r = r<<5;
					colors[i].g = g<<5;
					colors[i].b = b<<6;
				}
			}
		}
	}
NOTICE("testwin: setting colors\n");
	if ( ! SDL_SetColors(screen, colors, 0, ncolors) &&
				(screen->format->palette != NULL) ) {
		fprintf(stderr,
"Warning: Couldn't set all of the colors, but SDL will map the image\n"
"         (colormap fading will suffer - try the -warp option)\n"
		);
	}

	/* Set the screen to black (not really necessary) */
	if ( SDL_LockSurface(screen) == 0 ) {
		Uint32 black;
		Uint8 *pixels;

		black = SDL_MapRGB(screen->format, 0, 0, 0);
		pixels = (Uint8 *)screen->pixels;
		for ( i=0; i<screen->h; ++i ) {
			memset(pixels, black,
				screen->w*screen->format->BytesPerPixel);
			pixels += screen->pitch;
		}
		SDL_UnlockSurface(screen);
		SDL_UpdateRect(screen, 0, 0, 0, 0);
	}
	
	/* Display the picture */
	if ( speedy ) {
		SDL_Surface *displayfmt;

fprintf(stderr, "Converting picture\n");
		displayfmt = SDL_DisplayFormat(picture);
		if ( displayfmt == NULL ) {
			fprintf(stderr,
				"Couldn't convert image: %s\n", SDL_GetError());
			goto done;
		}
		SDL_FreeSurface(picture);
		picture = displayfmt;
	}
	printf("(image surface located in %s memory)\n", 
			(picture->flags&SDL_HWSURFACE) ? "video" : "system");
	centered = (screen->w - picture->w)/2;
	if ( centered < 0 ) {
		centered = 0;
	}
	dest.y = (screen->h - picture->h)/2;
	dest.w = picture->w;
	dest.h = picture->h;
NOTICE("testwin: moving image\n");
	for ( i=0; i<=centered; ++i ) {
		dest.x = i;
		update = dest;
		if ( SDL_BlitSurface(picture, NULL, screen, &update) < 0 ) {
			fprintf(stderr, "Blit failed: %s\n", SDL_GetError());
			break;
		}
		if ( flip ) {
			SDL_Flip(screen);
		} else {
			SDL_UpdateRects(screen, 1, &update);
		}
	}

#ifdef SCREENSHOT
	if ( SDL_SaveBMP(screen, "screen.bmp") < 0 )
		printf("Couldn't save screen: %s\n", SDL_GetError());
#endif

#ifndef BENCHMARK_SDL
	/* Let it sit there for a while */
	SDL_Delay(5*1000);
#endif
	/* Fade the colormap */
	if ( ! nofade ) {
		int maxstep;
		SDL_Color final;
		SDL_Color palcolors[256];
		struct {
			Sint16 r, g, b;
		} cdist[256];

NOTICE("testwin: fading out...\n");
		memcpy(cmap, colors, ncolors*sizeof(SDL_Color));
		maxstep = 32-1;
		final.r = 0xFF;
Example #19
0
int main(int argc, char *argv[])
{
	int ret,pipefd;
	char *lxcpath = argv[1];
	char logpath[PATH_MAX];
	sigset_t mask;

	if (argc != 3) {
		fprintf(stderr,
			"Usage: lxc-monitord lxcpath sync-pipe-fd\n\n"
			"NOTE: lxc-monitord is intended for use by lxc internally\n"
			"      and does not need to be run by hand\n\n");
		exit(EXIT_FAILURE);
	}

	ret = snprintf(logpath, sizeof(logpath), "%s/lxc-monitord.log",
		       lxcpath);
	if (ret < 0 || ret >= sizeof(logpath))
		return EXIT_FAILURE;

	ret = lxc_log_init(NULL, logpath, "NOTICE", "lxc-monitord", 0, lxcpath);
	if (ret)
		INFO("Failed to open log file %s, log will be lost", lxcpath);

	pipefd = atoi(argv[2]);

	if (sigfillset(&mask) ||
	    sigdelset(&mask, SIGILL)  ||
	    sigdelset(&mask, SIGSEGV) ||
	    sigdelset(&mask, SIGBUS)  ||
	    sigdelset(&mask, SIGTERM) ||
	    sigprocmask(SIG_BLOCK, &mask, NULL)) {
		SYSERROR("failed to set signal mask");
		return -1;
	}

	signal(SIGILL,  lxc_monitord_sig_handler);
	signal(SIGSEGV, lxc_monitord_sig_handler);
	signal(SIGBUS,  lxc_monitord_sig_handler);
	signal(SIGTERM, lxc_monitord_sig_handler);

	ret = EXIT_FAILURE;
	memset(&mon, 0, sizeof(mon));
	mon.lxcpath = lxcpath;
	if (lxc_mainloop_open(&mon.descr)) {
		ERROR("failed to create mainloop");
		goto out;
	}

	if (lxc_monitord_create(&mon)) {
		goto out;
	}

	/* sync with parent, we're ignoring the return from write
	 * because regardless if it works or not, the following
	 * close will sync us with the parent process. the
	 * if-empty-statement construct is to quiet the
	 * warn-unused-result warning.
	 */
	if (write(pipefd, "S", 1)) ;
	close(pipefd);

	if (lxc_monitord_mainloop_add(&mon)) {
		ERROR("failed to add mainloop handlers");
		goto out;
	}

	NOTICE("monitoring lxcpath %s", mon.lxcpath);
	for(;;) {
		ret = lxc_mainloop(&mon.descr, 1000 * 30);
		if (mon.clientfds_cnt <= 0)
		{
			NOTICE("no clients for 30 seconds, exiting");
			break;
		}
	}

	lxc_mainloop_close(&mon.descr);
	lxc_monitord_cleanup();
	ret = EXIT_SUCCESS;
	NOTICE("monitor exiting");
out:
	return ret;
}
Example #20
0
static int execute_post_start(struct lxc_handler *handler, void* data)
{
	struct execute_args *my_args = data;
	NOTICE("'%s' started with pid '%d'", my_args->argv[0], handler->pid);
	return 0;
}
void service_start(struct service *svc, const char *dynamic_args)
{
    struct stat s;
    pid_t pid;
    int needs_console;
    int n;
#ifdef HAVE_SELINUX
    char *scon = NULL;
    int rc;
#endif
        /* starting a service removes it from the disabled or reset
         * state and immediately takes it out of the restarting
         * state if it was in there
         */
    svc->flags &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET));
    svc->time_started = 0;

        /* running processes require no additional work -- if
         * they're in the process of exiting, we've ensured
         * that they will immediately restart on exit, unless
         * they are ONESHOT
         */
    if (svc->flags & SVC_RUNNING) {
        return;
    }

    needs_console = (svc->flags & SVC_CONSOLE) ? 1 : 0;
    if (needs_console && (!have_console)) {
        ERROR("service '%s' requires console\n", svc->name);
        svc->flags |= SVC_DISABLED;
        return;
    }

    if (stat(svc->args[0], &s) != 0) {
        ERROR("cannot find '%s', disabling '%s'\n", svc->args[0], svc->name);
        svc->flags |= SVC_DISABLED;
        return;
    }

    if ((!(svc->flags & SVC_ONESHOT)) && dynamic_args) {
        ERROR("service '%s' must be one-shot to use dynamic args, disabling\n",
               svc->args[0]);
        svc->flags |= SVC_DISABLED;
        return;
    }

#ifdef HAVE_SELINUX
    if (is_selinux_enabled() > 0) {
        char *mycon = NULL, *fcon = NULL;

        INFO("computing context for service '%s'\n", svc->args[0]);
        rc = getcon(&mycon);
        if (rc < 0) {
            ERROR("could not get context while starting '%s'\n", svc->name);
            return;
        }

        rc = getfilecon(svc->args[0], &fcon);
        if (rc < 0) {
            ERROR("could not get context while starting '%s'\n", svc->name);
            freecon(mycon);
            return;
        }

        rc = security_compute_create(mycon, fcon, string_to_security_class("process"), &scon);
        freecon(mycon);
        freecon(fcon);
        if (rc < 0) {
            ERROR("could not get context while starting '%s'\n", svc->name);
            return;
        }
    }
#endif

    NOTICE("starting '%s'\n", svc->name);

    pid = fork();

    if (pid == 0) {
        struct socketinfo *si;
        struct svcenvinfo *ei;
        char tmp[32];
        int fd, sz;

        umask(077);
#ifdef __arm__
        /*
         * b/7188322 - Temporarily revert to the compat memory layout
         * to avoid breaking third party apps.
         *
         * THIS WILL GO AWAY IN A FUTURE ANDROID RELEASE.
         *
         * http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=commitdiff;h=7dbaa466
         * changes the kernel mapping from bottom up to top-down.
         * This breaks some programs which improperly embed
         * an out of date copy of Android's linker.
         */
        int current = personality(0xffffFFFF);
        personality(current | ADDR_COMPAT_LAYOUT);
#endif
        if (properties_inited()) {
            get_property_workspace(&fd, &sz);
            sprintf(tmp, "%d,%d", dup(fd), sz);
            add_environment("ANDROID_PROPERTY_WORKSPACE", tmp);
        }

        for (ei = svc->envvars; ei; ei = ei->next)
            add_environment(ei->name, ei->value);

#ifdef HAVE_SELINUX
        setsockcreatecon(scon);
#endif

        for (si = svc->sockets; si; si = si->next) {
            int socket_type = (
                    !strcmp(si->type, "stream") ? SOCK_STREAM :
                        (!strcmp(si->type, "dgram") ? SOCK_DGRAM : SOCK_SEQPACKET));
            int s = create_socket(si->name, socket_type,
                                  si->perm, si->uid, si->gid);
            if (s >= 0) {
                publish_socket(si->name, s);
            }
        }

#ifdef HAVE_SELINUX
        freecon(scon);
        scon = NULL;
        setsockcreatecon(NULL);
#endif

        if (svc->ioprio_class != IoSchedClass_NONE) {
            if (android_set_ioprio(getpid(), svc->ioprio_class, svc->ioprio_pri)) {
                ERROR("Failed to set pid %d ioprio = %d,%d: %s\n",
                      getpid(), svc->ioprio_class, svc->ioprio_pri, strerror(errno));
            }
        }

        if (needs_console) {
            setsid();
            open_console();
        } else {
            zap_stdio();
        }

#if 0
        for (n = 0; svc->args[n]; n++) {
            INFO("args[%d] = '%s'\n", n, svc->args[n]);
        }
        for (n = 0; ENV[n]; n++) {
            INFO("env[%d] = '%s'\n", n, ENV[n]);
        }
#endif

        setpgid(0, getpid());

    /* as requested, set our gid, supplemental gids, and uid */
        if (svc->gid) {
            if (setgid(svc->gid) != 0) {
                ERROR("setgid failed: %s\n", strerror(errno));
                _exit(127);
            }
        }
        if (svc->nr_supp_gids) {
            if (setgroups(svc->nr_supp_gids, svc->supp_gids) != 0) {
                ERROR("setgroups failed: %s\n", strerror(errno));
                _exit(127);
            }
        }
        if (svc->uid) {
            if (setuid(svc->uid) != 0) {
                ERROR("setuid failed: %s\n", strerror(errno));
                _exit(127);
            }
        }

#ifdef HAVE_SELINUX
        if (svc->seclabel) {
            if (is_selinux_enabled() > 0 && setexeccon(svc->seclabel) < 0) {
                ERROR("cannot setexeccon('%s'): %s\n", svc->seclabel, strerror(errno));
                _exit(127);
            }
        }
#endif

        if (!dynamic_args) {
            if (execve(svc->args[0], (char**) svc->args, (char**) ENV) < 0) {
                ERROR("cannot execve('%s'): %s\n", svc->args[0], strerror(errno));
            }
        } else {
            char *arg_ptrs[INIT_PARSER_MAXARGS+1];
            int arg_idx = svc->nargs;
            char *tmp = strdup(dynamic_args);
            char *next = tmp;
            char *bword;

            /* Copy the static arguments */
            memcpy(arg_ptrs, svc->args, (svc->nargs * sizeof(char *)));

            while((bword = strsep(&next, " "))) {
                arg_ptrs[arg_idx++] = bword;
                if (arg_idx == INIT_PARSER_MAXARGS)
                    break;
            }
            arg_ptrs[arg_idx] = '\0';
            execve(svc->args[0], (char**) arg_ptrs, (char**) ENV);
        }
        _exit(127);
    }

#ifdef HAVE_SELINUX
    freecon(scon);
#endif

    if (pid < 0) {
        ERROR("failed to start '%s'\n", svc->name);
        svc->pid = 0;
        return;
    }

    svc->time_started = gettime();
    svc->pid = pid;
    svc->flags |= SVC_RUNNING;

    if (properties_inited())
        notify_service_state(svc->name, "running");
}
Example #22
0
int main(int argc, char **argv) {
    ////joseph stuff

    get_full_conf(argc, argv);

    ////justin stuff
    int sock;
    struct addrinfo hints, *res;
    int reuseaddr = 1; /* True */

    /* Get the address info */
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    char str_envelope_port[25];
    sprintf(str_envelope_port, "%d", int_global_envelope_port);
    if (getaddrinfo(NULL, str_envelope_port, &hints, &res) != 0) {
        DEBUG("getaddrinfo");
        return 1;
    }

    /* Create the socket */
    sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    if (sock == -1) {
        DEBUG("socket");
        return 1;
    }

    /* Enable the socket to reuse the address */
    if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(int)) == -1) {
        DEBUG("setsockopt");
        return 1;
    }

    /* Bind to the address */
    if (bind(sock, res->ai_addr, res->ai_addrlen) == -1) {
        DEBUG("bind");
        return 1;
    }

    /* Listen */
    if (listen(sock, 128) == -1) {
        DEBUG("listen");
        return 1;
    }

    freeaddrinfo(res);

    /* Set up the zombie signal handler */
    struct sigaction sa1;
    sa1.sa_handler = wait_for_child;
    sigemptyset(&sa1.sa_mask);
    sa1.sa_flags = SA_RESTART | SA_NOCLDSTOP;
    if (sigaction(SIGCHLD, &sa1, NULL) == -1) {
        DEBUG("sigaction Set Listen SIGCHLD error");
        return 1;
    }

    /* Set up the kill signal handler */
    struct sigaction sa2;
    sa2.sa_handler = kill_handler;
    sigemptyset(&sa2.sa_mask);
    //sa2.sa_flags = SA_RESTART;
    sa2.sa_flags = 0;//nothing
    if (sigaction(SIGTERM, &sa2, NULL) == -1) {
        DEBUG("sigaction Set Listen SIGTERM error");
        return 1;
    }

    init_aes_key_iv();

    //get time zone
    time_t time_last;
    time(&time_last);

    //convert to localtime
    struct tm *tm_last = localtime(&time_last);
    time_t time_current;
    struct tm *tm_current;

    NOTICE("STARTUP SUCCESSFULL\n");
    bol_error_state = false;//stop var logs caused by startup non-error
    errno = 0;//now if there is an error that doesn't set errno, we know that it didn't

    /* Main loop */
    while (1) {
        struct sockaddr_in their_addr;
        socklen_t size = sizeof(struct sockaddr_in);
        int newsock = accept(sock, (struct sockaddr*)&their_addr, &size);
        if (newsock == -1) {
            DEBUG("accept:(%s)", strerror(errno));
            //perror("accept");
            free_config();
            return 0;
        }
        DEBUG("Got a connection from %s on port %d\n", inet_ntoa(their_addr.sin_addr), htons(their_addr.sin_port));

        // when we were starting as root and then setting the user name
        //setuid( pwbufp->pw_uid );

        //get time zone
        time(&time_current);

        //convert to localtime
        tm_current = localtime(&time_current);

        //check for reinit
        if (tm_current->tm_yday != tm_last->tm_yday) {
            init_aes_key_iv();
            tm_last = tm_current;
        }

        DEBUG("###################################################\n");
        DEBUG("############## NEW ENVELOPE REQUEST ###############\n");

        // ############ development ###############
        /*
        handle(newsock);
        close(newsock);
        */
        // ############ production ###############

        int pid;
        pid = fork();
        if (pid == 0) {
            // In child process
            close(sock);

            /* Set up the default kill signal handler (read: remove custom handler) */
            /*
            struct sigaction sa3;
            sa3.sa_handler = SIG_DFL;
            sigemptyset(&sa3.sa_mask);
            //sa3.sa_flags = SA_RESTART;
            if (sigaction(SIGTERM, &sa3, NULL) == -1) {
            	perror("sigaction Set Listen SIGTERM default error");
            	return 1;
            }
            */

            global_csock = newsock;
            errno = 0;//now if there is an error that doesn't set errno, we know that it didn't
            handle(newsock);
            if (close(newsock) != 0) {
                ERROR_NORESPONSE("close(newsock): %d (%s)", errno, strerror(errno));
            }
            free_config();
            //exit(EXIT_SUCCESS);
            return 0;
        } else {
            // Parent process
            if (pid == -1) {
                DEBUG("fork:(%s)", strerror(errno));
                //perror("fork");
                free_config();
                return 1;
            } else {
                close(newsock);
            }
        }

        //##########################################
    }

    free_config();
    close(sock);
    return 0;
}
Example #23
0
static void
isc_httpd_recvdone(isc_task_t *task, isc_event_t *ev) {
	isc_region_t r;
	isc_result_t result;
	isc_httpd_t *httpd = ev->ev_arg;
	isc_socketevent_t *sev = (isc_socketevent_t *)ev;
	isc_httpdurl_t *url;
	isc_time_t now;
	char datebuf[32];  /* Only need 30, but safety first */

	ENTER("recv");

	INSIST(ISC_HTTPD_ISRECV(httpd));

	if (sev->result != ISC_R_SUCCESS) {
		NOTICE("recv destroying client");
		destroy_client(&httpd);
		goto out;
	}

	result = process_request(httpd, sev->n);
	if (result == ISC_R_NOTFOUND) {
		if (httpd->recvlen >= HTTP_RECVLEN - 1) {
			destroy_client(&httpd);
			goto out;
		}
		r.base = (unsigned char *)httpd->recvbuf + httpd->recvlen;
		r.length = HTTP_RECVLEN - httpd->recvlen - 1;
		/* check return code? */
		(void)isc_socket_recv(httpd->sock, &r, 1, task,
				      isc_httpd_recvdone, httpd);
		goto out;
	} else if (result != ISC_R_SUCCESS) {
		destroy_client(&httpd);
		goto out;
	}

	ISC_HTTPD_SETSEND(httpd);

	/*
	 * XXXMLG Call function here.  Provide an add-header function
	 * which will append the common headers to a response we generate.
	 */
	isc_buffer_initnull(&httpd->bodybuffer);
	isc_time_now(&now);
	isc_time_formathttptimestamp(&now, datebuf, sizeof(datebuf));
	url = ISC_LIST_HEAD(httpd->mgr->urls);
	while (url != NULL) {
		if (strcmp(httpd->url, url->url) == 0)
			break;
		url = ISC_LIST_NEXT(url, link);
	}
	if (url == NULL)
		result = httpd->mgr->render_404(httpd->url, NULL,
						httpd->querystring,
						NULL, NULL,
						&httpd->retcode,
						&httpd->retmsg,
						&httpd->mimetype,
						&httpd->bodybuffer,
						&httpd->freecb,
						&httpd->freecb_arg);
	else
		result = url->action(httpd->url, url,
				     httpd->querystring,
				     httpd->headers,
				     url->action_arg,
				     &httpd->retcode, &httpd->retmsg,
				     &httpd->mimetype, &httpd->bodybuffer,
				     &httpd->freecb, &httpd->freecb_arg);
	if (result != ISC_R_SUCCESS) {
		result = httpd->mgr->render_500(httpd->url, url,
						httpd->querystring,
						NULL, NULL,
						&httpd->retcode,
						&httpd->retmsg,
						&httpd->mimetype,
						&httpd->bodybuffer,
						&httpd->freecb,
						&httpd->freecb_arg);
		RUNTIME_CHECK(result == ISC_R_SUCCESS);
	}

	isc_httpd_response(httpd);
	isc_httpd_addheader(httpd, "Content-Type", httpd->mimetype);
	isc_httpd_addheader(httpd, "Date", datebuf);
	isc_httpd_addheader(httpd, "Expires", datebuf);

	if (url != NULL && url->isstatic) {
		char loadbuf[32];
		isc_time_formathttptimestamp(&url->loadtime,
					     loadbuf, sizeof(loadbuf));
		isc_httpd_addheader(httpd, "Last-Modified", loadbuf);
		isc_httpd_addheader(httpd, "Cache-Control: public", NULL);
	} else {
	isc_httpd_addheader(httpd, "Last-Modified", datebuf);
	isc_httpd_addheader(httpd, "Pragma: no-cache", NULL);
	isc_httpd_addheader(httpd, "Cache-Control: no-cache", NULL);
	}

	isc_httpd_addheader(httpd, "Server: libisc", NULL);
	isc_httpd_addheaderuint(httpd, "Content-Length",
				isc_buffer_usedlength(&httpd->bodybuffer));
	isc_httpd_endheaders(httpd);  /* done */

	ISC_LIST_APPEND(httpd->bufflist, &httpd->headerbuffer, link);
	/*
	 * Link the data buffer into our send queue, should we have any data
	 * rendered into it.  If no data is present, we won't do anything
	 * with the buffer.
	 */
	if (isc_buffer_length(&httpd->bodybuffer) > 0)
		ISC_LIST_APPEND(httpd->bufflist, &httpd->bodybuffer, link);

	/* check return code? */
	(void)isc_socket_sendv(httpd->sock, &httpd->bufflist, task,
			       isc_httpd_senddone, httpd);

 out:
	isc_event_free(&ev);
	EXIT("recv");
}
Example #24
0
/*
 * XXX: btrie插入操作有其特殊性
 *      对rule匹配规则而言,它是松散的,count表示了str[]的总项数,valids表示有效的str项,end_index
 *            则表示最后一个有效str项的索引值,end_index可能大于valids。
 *      对host匹配规则而言,它是连续的,count依然表示str[]的总项数,但由于是连续,end_index总是等于
 *            valids-1。
 *      valids用于指导分配btrie_node,end_index则用于最后的检查工作。
 */
btrie_node_t *btrie_insert(btrie_ctx_t *ctx,
                           btrie_node_t **ptr_root,
                           unsigned long count,
                           string_t str[],
                           unsigned long valids,
                           int end_index)
{
    int node_cnt = 0, node_used = 0;
    btrie_node_t *new_node_array, *node, *wildcard;
    int i, found = 0;
    btrie_node_t **proot, *root, *ret = NULL;
    btrie_node_t **pcurr, *curr; /* 注意: 用于算法内部临时查找,而非当前处理节点 */

    if (ctx == NULL || ptr_root == NULL || count == 0 || str == NULL || valids > count || valids == 0) {
        return NULL;
    }
    if (end_index < 0 || end_index >= count) {
        return NULL;
    }

    node_cnt = valids * 2; /* 预留通配符节点,节点分配数量翻倍 */
    /* 注意: new_node_array必须是连续分配的,且严格的从头开始连续使用,以便连续释放空闲的 */
    new_node_array = btrie_node_alloc(ctx, node_cnt);
    if (new_node_array == NULL) {
        NOTICE();
        return NULL;
    }

    proot = ptr_root; /* 存放root的位置,方便修改root的值 */
    root = *proot;
    for (i = 0; i < count; i++) {
        if (str[i].len == 0) {
            continue;
        }
        if (str[i].len == BTRIE_NO_VALUE_MAGIC_LEN) {
            /* 对str是no val型,恢复其正确值0。 */
            str[i].len = 0;
        }
again:
        if (node_used >= node_cnt) {
            /* BUG: 使用量已经超过分配的数量 */
            BUG();
            return NULL;
        }
        if (root == NULL) {
            node = &new_node_array[node_used];
            node->index = i;
            if (str[i].len == BTRIE_WILDCARD_MAGIC_LEN) {
                node->flags = BTRIE_FLAG_WILDCARD;
            } else {
                if ((str[i].len > 0)
                        && (symtab_add(ctx->symtab, &str[i], &node->str) != 0)) {
                    goto err_out;
                }
            }
            node_used++;
            *proot = node;

            ret = node;
            proot = &node->child;
            root = node->child;
        } else if (root->index == i) {
            for (pcurr = proot, curr = root;
                    (curr != NULL) && (curr->flags != BTRIE_FLAG_WILDCARD);
                    pcurr = &curr->sibling, curr = curr->sibling) {
                if (string_is_equal(&curr->str, &str[i])) {
                    found = 1;
                    break;
                }
            }
            if (found) {
                found = 0;
                proot = &curr->child;
                root = curr->child;
                ret = curr;
                continue;
            }

            if (str[i].len == BTRIE_WILDCARD_MAGIC_LEN) {
                if (curr == NULL) {
                    /* 通配符节点不存在,首先创建通配符节点 */
                    node = &new_node_array[node_used];
                    node->index = i;
                    node->flags = BTRIE_FLAG_WILDCARD;
                    node_used++;
                    /* 然后将通配符节点加入树中 */
                    node->sibling = curr;
                    *pcurr = node;
                    curr = node;
                }

                proot = &curr->child;
                root = curr->child;
                ret = curr;
                continue;
            } else {
                node = &new_node_array[node_used];
                node->index = i;
                if ((str[i].len > 0)
                        && (symtab_add(ctx->symtab, &str[i], &node->str) != 0)) {
                    goto err_out;
                }
                node_used++;

                node->sibling = curr;
                *pcurr = node;
                proot = &node->child;
                root = node->child;
                ret = node;
                continue;
            }
        } else if (root->index > i) {
            /* root节点等级比待加入节点低 */
            if (str[i].len == BTRIE_WILDCARD_MAGIC_LEN) {
                /* XXX: 目前只有host涉及到通配符,其不可能进入本分支 */
                BUG();
                goto err_out;
            }
            node = &new_node_array[node_used];
            node->index = i;
            if ((str[i].len > 0)
                    && (symtab_add(ctx->symtab, &str[i], &node->str) != 0)) {
                goto err_out;
            }
            node_used++;

            wildcard = &new_node_array[node_used++];
            wildcard->flags = BTRIE_FLAG_WILDCARD;
            wildcard->index = i;

            node->sibling = wildcard;
            wildcard->child = root;
            *proot = node;

            ret = node;
            proot = &node->child;
            root = node->child;
        } else {
            /* root节点等级比待加入节点高 root->index < i */
            if (str[i].len == BTRIE_WILDCARD_MAGIC_LEN) {
                /* XXX: 目前只有host涉及到通配符,其不可能进入本分支 */
                BUG();
                goto err_out;
            }
            for (pcurr = proot, curr = root;
                    (curr != NULL) && (curr->flags != BTRIE_FLAG_WILDCARD);
                    pcurr = &curr->sibling, curr = curr->sibling) {
                (void)0;
            }
            if (curr == NULL) {
                wildcard = &new_node_array[node_used++];
                wildcard->flags = BTRIE_FLAG_WILDCARD;
                wildcard->index = root->index;

                *pcurr = wildcard;
                curr = wildcard;
            }
            proot = &curr->child;
            root = curr->child;
            goto again;
        }
    }

    /* 对ret的有效性做检查 */
    if ((ret != NULL) && (ret->index != end_index)) {
        /* BUG: 竟然有ret,但还未到末尾的节点 */
        BUG();
        goto err_out;
    }
    /* XXX: 如果添加相同的RULE或者HOST,则ret中data不为NULL,认定为出错 */
    if ((ret != NULL) && (ret->data != NULL)) {
        NOTICE();
        goto err_out;
    }

    /* 释放未使用的mnode */
    btrie_node_free(ctx, (node_cnt - node_used));

    return ret;

err_out:
    /* 释放掉还未加入查找树中的节点,已加入的就不删除了 */
    btrie_node_free(ctx, (node_cnt - node_used));

    return NULL;
}
Example #25
0
static void
isc_httpd_accept(isc_task_t *task, isc_event_t *ev) {
	isc_result_t result;
	isc_httpdmgr_t *httpdmgr = ev->ev_arg;
	isc_httpd_t *httpd;
	isc_region_t r;
	isc_socket_newconnev_t *nev = (isc_socket_newconnev_t *)ev;
	isc_sockaddr_t peeraddr;

	ENTER("accept");

	LOCK(&httpdmgr->lock);
	if (MSHUTTINGDOWN(httpdmgr)) {
		NOTICE("accept shutting down, goto out");
		goto out;
	}

	if (nev->result == ISC_R_CANCELED) {
		NOTICE("accept canceled, goto out");
		goto out;
	}

	if (nev->result != ISC_R_SUCCESS) {
		/* XXXMLG log failure */
		NOTICE("accept returned failure, goto requeue");
		goto requeue;
	}

	(void)isc_socket_getpeername(nev->newsocket, &peeraddr);
	if (httpdmgr->client_ok != NULL &&
	    !(httpdmgr->client_ok)(&peeraddr, httpdmgr->cb_arg)) {
		isc_socket_detach(&nev->newsocket);
		goto requeue;
	}

	httpd = isc_mem_get(httpdmgr->mctx, sizeof(isc_httpd_t));
	if (httpd == NULL) {
		/* XXXMLG log failure */
		NOTICE("accept failed to allocate memory, goto requeue");
		isc_socket_detach(&nev->newsocket);
		goto requeue;
	}

	httpd->mgr = httpdmgr;
	ISC_LINK_INIT(httpd, link);
	ISC_LIST_APPEND(httpdmgr->running, httpd, link);
	ISC_HTTPD_SETRECV(httpd);
	httpd->sock = nev->newsocket;
	isc_socket_setname(httpd->sock, "httpd", NULL);
	httpd->flags = 0;

	/*
	 * Initialize the buffer for our headers.
	 */
	httpd->headerdata = isc_mem_get(httpdmgr->mctx, HTTP_SENDGROW);
	if (httpd->headerdata == NULL) {
		isc_mem_put(httpdmgr->mctx, httpd, sizeof(isc_httpd_t));
		isc_socket_detach(&nev->newsocket);
		goto requeue;
	}
	httpd->headerlen = HTTP_SENDGROW;
	isc_buffer_init(&httpd->headerbuffer, httpd->headerdata,
			httpd->headerlen);

	ISC_LIST_INIT(httpd->bufflist);

	isc_buffer_initnull(&httpd->bodybuffer);
	reset_client(httpd);

	r.base = (unsigned char *)httpd->recvbuf;
	r.length = HTTP_RECVLEN - 1;
	result = isc_socket_recv(httpd->sock, &r, 1, task, isc_httpd_recvdone,
				 httpd);
	/* FIXME!!! */
	POST(result);
	NOTICE("accept queued recv on socket");

 requeue:
	result = isc_socket_accept(httpdmgr->sock, task, isc_httpd_accept,
				   httpdmgr);
	if (result != ISC_R_SUCCESS) {
		/* XXXMLG what to do?  Log failure... */
		NOTICE("accept could not reaccept due to failure");
	}

 out:
	UNLOCK(&httpdmgr->lock);

	httpdmgr_destroy(httpdmgr);

	isc_event_free(&ev);

	EXIT("accept");
}
Example #26
0
void do_backup(char *path) {

	init_recipe_store();
	init_container_store();
	init_index();

	init_backup_jcr(path);
    
	NOTICE("\n\n==== backup begin ====");

	TIMER_DECLARE(1);
	TIMER_BEGIN(1);

    time_t start = time(NULL);
	if (destor.simulation_level == SIMULATION_ALL) {
		start_read_trace_phase();
	} else {
		start_read_phase();
		start_chunk_phase();
		start_hash_phase();
	}
	start_dedup_phase();
	start_rewrite_phase();
	start_filter_phase();

    do{
        sleep(5);
        /*time_t now = time(NULL);*/
        fprintf(stderr,"job %" PRId32 ", data size %" PRId64 " bytes, %" PRId32 " chunks, %d files processed\r",
                jcr.id, jcr.data_size, jcr.chunk_num, jcr.file_num);
    }while(jcr.status == JCR_STATUS_RUNNING || jcr.status != JCR_STATUS_DONE);
    fprintf(stderr,"job %" PRId32 ", data size %" PRId64 " bytes, %" PRId32 " chunks, %d files processed\n",
        jcr.id, jcr.data_size, jcr.chunk_num, jcr.file_num);

	if (destor.simulation_level == SIMULATION_ALL) {
		stop_read_trace_phase();
	} else {
		stop_read_phase();
		stop_chunk_phase();
		stop_hash_phase();
	}
	stop_dedup_phase();
	stop_rewrite_phase();
	stop_filter_phase();

	TIMER_END(1, jcr.total_time);
    
	close_index();
	close_container_store();
	close_recipe_store();

	update_backup_version(jcr.bv);
	free_backup_version(jcr.bv);
    
    
	printf("\n\njob id: %" PRId32 "\n", jcr.id);
    printf("index method: %d.(Remark 0: NO; 1: DDFS; 2: Extreme binning; 3: Silo; 4: Sparse; 5: Sampled; 6: Block; 7: Learn)\n",
           destor.index_specific);
    
    printf("sampling method: %d (%d) (Remark 1:Random; 2: Min; 3: Uniform; 4: Optimized_min)\n", destor.index_sampling_method[0], destor.index_sampling_method[1]);
	printf("segment method: %d (%d) (Remark 0: Fixed; 1: Content; 2: File)\n", destor.index_segment_algorithm[0], destor.index_segment_algorithm[1]);
    printf("prefetch # of segments: %d (Remark 1 for sparse index)\n", destor.index_segment_prefech);
    printf("segment selection method: %d (%d)(Remark 0: Base; 1: Top; 2: Mix)\n", destor.index_segment_selection_method[0], destor.index_segment_selection_method[1]);
    printf("backup path: %s\n", jcr.path);
	printf("number of files: %d\n", jcr.file_num);
	printf("number of chunks: %" PRId32 " (%" PRId64 " bytes on average)\n", jcr.chunk_num,
			jcr.data_size / jcr.chunk_num);
	printf("number of unique chunks: %" PRId32 "\n", jcr.unique_chunk_num);
	printf("total size(B): %" PRId64 "\n", jcr.data_size);
	printf("stored data size(B): %" PRId64 "\n",
			jcr.unique_data_size + jcr.rewritten_chunk_size);
	printf("deduplication ratio: %.4f, %.4f\n",
			jcr.data_size != 0 ?
					(jcr.data_size - jcr.unique_data_size
							- jcr.rewritten_chunk_size)
							/ (double) (jcr.data_size) :
					0,
			jcr.data_size
					/ (double) (jcr.unique_data_size + jcr.rewritten_chunk_size));
	printf("total time(s): %.3f\n", jcr.total_time / 1000000);
    printf("the index memory footprint (B): %" PRId32 "\n", destor.index_memory_footprint);
	printf("throughput(MB/s): %.2f\n",
			(double) jcr.data_size * 1000000 / (1024 * 1024 * jcr.total_time));
	printf("number of zero chunks: %" PRId32 "\n", jcr.zero_chunk_num);
	printf("size of zero chunks: %" PRId64 "\n", jcr.zero_chunk_size);
	printf("number of rewritten chunks: %" PRId32 "\n", jcr.rewritten_chunk_num);
	printf("size of rewritten chunks: %" PRId64 "\n", jcr.rewritten_chunk_size);
	printf("rewritten rate in size: %.3f\n",
			jcr.rewritten_chunk_size / (double) jcr.data_size);

	destor.data_size += jcr.data_size;
	destor.stored_data_size += jcr.unique_data_size + jcr.rewritten_chunk_size;

	destor.chunk_num += jcr.chunk_num;
	destor.stored_chunk_num += jcr.unique_chunk_num + jcr.rewritten_chunk_num;
	destor.zero_chunk_num += jcr.zero_chunk_num;
	destor.zero_chunk_size += jcr.zero_chunk_size;
	destor.rewritten_chunk_num += jcr.rewritten_chunk_num;
	destor.rewritten_chunk_size += jcr.rewritten_chunk_size;

	printf("read_time : %.3fs, %.2fMB/s\n", jcr.read_time / 1000000,
			jcr.data_size * 1000000 / jcr.read_time / 1024 / 1024);
	printf("chunk_time : %.3fs, %.2fMB/s\n", jcr.chunk_time / 1000000,
			jcr.data_size * 1000000 / jcr.chunk_time / 1024 / 1024);
	printf("hash_time : %.3fs, %.2fMB/s\n", jcr.hash_time / 1000000,
			jcr.data_size * 1000000 / jcr.hash_time / 1024 / 1024);

	printf("dedup_time : %.3fs, %.2fMB/s\n",
			jcr.dedup_time / 1000000,
			jcr.data_size * 1000000 / jcr.dedup_time / 1024 / 1024);

	printf("rewrite_time : %.3fs, %.2fMB/s\n", jcr.rewrite_time / 1000000,
			jcr.data_size * 1000000 / jcr.rewrite_time / 1024 / 1024);

	printf("filter_time : %.3fs, %.2fMB/s\n",
			jcr.filter_time / 1000000,
			jcr.data_size * 1000000 / jcr.filter_time / 1024 / 1024);

	printf("write_time : %.3fs, %.2fMB/s\n", jcr.write_time / 1000000,
			jcr.data_size * 1000000 / jcr.write_time / 1024 / 1024);

	//double seek_time = 0.005; //5ms
	//double bandwidth = 120 * 1024 * 1024; //120MB/s

	/*	double index_lookup_throughput = jcr.data_size
	 / (index_read_times * seek_time
	 + index_read_entry_counter * 24 / bandwidth) / 1024 / 1024;

	 double write_data_throughput = 1.0 * jcr.data_size * bandwidth
	 / (jcr->unique_chunk_num) / 1024 / 1024;
	 double index_read_throughput = 1.0 * jcr.data_size / 1024 / 1024
	 / (index_read_times * seek_time
	 + index_read_entry_counter * 24 / bandwidth);
	 double index_write_throughput = 1.0 * jcr.data_size / 1024 / 1024
	 / (index_write_times * seek_time
	 + index_write_entry_counter * 24 / bandwidth);*/

	/*	double estimated_throughput = write_data_throughput;
	 if (estimated_throughput > index_read_throughput)
	 estimated_throughput = index_read_throughput;*/
	/*if (estimated_throughput > index_write_throughput)
	 estimated_throughput = index_write_throughput;*/

	char logfile[] = "backup.log";
	FILE *fp = fopen(logfile, "a");
	/*
	 * job id,
	 * the size of backup
	 * accumulative consumed capacity,
	 * deduplication rate,
	 * rewritten rate,
	 * total container number,
	 * sparse container number,
	 * inherited container number,
	 * 4 * index overhead (4 * int)
	 * throughput,
	 */
	fprintf(fp, "%" PRId32 " %" PRId64 " %" PRId64 " %.4f %.4f %" PRId32 " %" PRId32 " %" PRId32 " %" PRId32" %" PRId32 " %" PRId32" %" PRId32" %.2f\n",
			jcr.id,
			jcr.data_size,
			destor.stored_data_size,
			jcr.data_size != 0 ?
					(jcr.data_size - jcr.rewritten_chunk_size - jcr.unique_data_size)/(double) (jcr.data_size)
					: 0,
			jcr.data_size != 0 ? (double) (jcr.rewritten_chunk_size) / (double) (jcr.data_size) : 0,
			jcr.total_container_num,
			jcr.sparse_container_num,
			jcr.inherited_sparse_num,
			index_overhead.lookup_requests,
			index_overhead.lookup_requests_for_unique,
			index_overhead.update_requests,
			index_overhead.read_prefetching_units,
			(double) jcr.data_size * 1000000 / (1024 * 1024 * jcr.total_time));

	fclose(fp);

}
Example #27
0
static void
isc_httpd_senddone(isc_task_t *task, isc_event_t *ev) {
	isc_httpd_t *httpd = ev->ev_arg;
	isc_region_t r;
	isc_socketevent_t *sev = (isc_socketevent_t *)ev;

	ENTER("senddone");
	INSIST(ISC_HTTPD_ISSEND(httpd));

	/*
	 * First, unlink our header buffer from the socket's bufflist.  This
	 * is sort of an evil hack, since we know our buffer will be there,
	 * and we know it's address, so we can just remove it directly.
	 */
	NOTICE("senddone unlinked header");
	ISC_LIST_UNLINK(sev->bufferlist, &httpd->headerbuffer, link);

	/*
	 * We will always want to clean up our receive buffer, even if we
	 * got an error on send or we are shutting down.
	 *
	 * We will pass in the buffer only if there is data in it.  If
	 * there is no data, we will pass in a NULL.
	 */
	if (httpd->freecb != NULL) {
		isc_buffer_t *b = NULL;
		if (isc_buffer_length(&httpd->bodybuffer) > 0)
			b = &httpd->bodybuffer;
		httpd->freecb(b, httpd->freecb_arg);
		NOTICE("senddone free callback performed");
	}
	if (ISC_LINK_LINKED(&httpd->bodybuffer, link)) {
		ISC_LIST_UNLINK(sev->bufferlist, &httpd->bodybuffer, link);
		NOTICE("senddone body buffer unlinked");
	}

	if (sev->result != ISC_R_SUCCESS) {
		destroy_client(&httpd);
		goto out;
	}

	if ((httpd->flags & HTTPD_CLOSE) != 0) {
		destroy_client(&httpd);
		goto out;
	}

	ISC_HTTPD_SETRECV(httpd);

	NOTICE("senddone restarting recv on socket");

	reset_client(httpd);

	r.base = (unsigned char *)httpd->recvbuf;
	r.length = HTTP_RECVLEN - 1;
	/* check return code? */
	(void)isc_socket_recv(httpd->sock, &r, 1, task,
			      isc_httpd_recvdone, httpd);

out:
	isc_event_free(&ev);
	EXIT("senddone");
}
Example #28
0
int main(int argc, char *argv[])
{
	STACK_OF(X509_EXTENSION) * sk = NULL;
	X509_EXTENSION *hash_ext = NULL;
	X509_EXTENSION *nvctr_ext = NULL;
	X509_EXTENSION *trusted_key_ext = NULL;
	X509_EXTENSION *non_trusted_key_ext = NULL;
	FILE *file = NULL;
	int i, tz_nvctr_nid, ntz_nvctr_nid, hash_nid, pk_nid;
	int c, opt_idx = 0;
	unsigned int err_code;
	unsigned char md[SHA256_DIGEST_LENGTH];
	const EVP_MD *md_info;

	NOTICE("CoT Generation Tool: %s\n", build_msg);
	NOTICE("Target platform: %s\n", platform_msg);

	/* Set default options */
	key_alg = KEY_ALG_RSA;

	while (1) {
		/* getopt_long stores the option index here. */
		c = getopt_long(argc, argv, "ahknp", long_opt, &opt_idx);

		/* Detect the end of the options. */
		if (c == -1) {
			break;
		}

		switch (c) {
		case 'a':
			key_alg = get_key_alg(optarg);
			if (key_alg < 0) {
				ERROR("Invalid key algorithm '%s'\n", optarg);
				exit(1);
			}
			break;
		case 'h':
			print_help(argv[0]);
			break;
		case 'k':
			save_keys = 1;
			break;
		case 'n':
			new_keys = 1;
			break;
		case 'p':
			print_cert = 1;
			break;
		case BL2_ID:
			certs[BL2_CERT].bin = strdup(optarg);
			break;
		case BL30_ID:
			certs[BL30_CERT].bin = strdup(optarg);
			break;
		case BL31_ID:
			certs[BL31_CERT].bin = strdup(optarg);
			break;
		case BL32_ID:
			certs[BL32_CERT].bin = strdup(optarg);
			break;
		case BL33_ID:
			certs[BL33_CERT].bin = strdup(optarg);
			break;
		case BL2_CERT_ID:
			certs[BL2_CERT].fn = strdup(optarg);
			break;
		case TRUSTED_KEY_CERT_ID:
			certs[TRUSTED_KEY_CERT].fn = strdup(optarg);
			break;
		case BL30_KEY_CERT_ID:
			certs[BL30_KEY_CERT].fn = strdup(optarg);
			break;
		case BL30_CERT_ID:
			certs[BL30_CERT].fn = strdup(optarg);
			break;
		case BL31_KEY_CERT_ID:
			certs[BL31_KEY_CERT].fn = strdup(optarg);
			break;
		case BL31_CERT_ID:
			certs[BL31_CERT].fn = strdup(optarg);
			break;
		case BL32_KEY_CERT_ID:
			certs[BL32_KEY_CERT].fn = strdup(optarg);
			break;
		case BL32_CERT_ID:
			certs[BL32_CERT].fn = strdup(optarg);
			break;
		case BL33_KEY_CERT_ID:
			certs[BL33_KEY_CERT].fn = strdup(optarg);
			break;
		case BL33_CERT_ID:
			certs[BL33_CERT].fn = strdup(optarg);
			break;
		case ROT_KEY_ID:
			keys[ROT_KEY].fn = strdup(optarg);
			break;
		case TRUSTED_WORLD_KEY_ID:
			keys[TRUSTED_WORLD_KEY].fn = strdup(optarg);
			break;
		case NON_TRUSTED_WORLD_KEY_ID:
			keys[NON_TRUSTED_WORLD_KEY].fn = strdup(optarg);
			break;
		case BL30_KEY_ID:
			keys[BL30_KEY].fn = strdup(optarg);
			break;
		case BL31_KEY_ID:
			keys[BL31_KEY].fn = strdup(optarg);
			break;
		case BL32_KEY_ID:
			keys[BL32_KEY].fn = strdup(optarg);
			break;
		case BL33_KEY_ID:
			keys[BL33_KEY].fn = strdup(optarg);
			break;
		case '?':
		default:
			printf("%s\n", optarg);
			exit(1);
		}
	}

	/* Set the value of the NVCounters */
	tf_nvcounter = NVCOUNTER_VALUE;
	non_tf_nvcounter = NVCOUNTER_VALUE;

	/* Check command line arguments */
	check_cmd_params();

	/* Register the new types and OIDs for the extensions */
	if (ext_init(tbb_ext) != 0) {
		ERROR("Cannot initialize TBB extensions\n");
		exit(1);
	}

	/* Indicate SHA256 as image hash algorithm in the certificate
	 * extension */
	md_info = EVP_sha256();

	/* Get non-volatile counters NIDs */
	CHECK_OID(tz_nvctr_nid, TZ_FW_NVCOUNTER_OID);
	CHECK_OID(ntz_nvctr_nid, NTZ_FW_NVCOUNTER_OID);

	/* Load private keys from files (or generate new ones) */
	for (i = 0 ; i < NUM_KEYS ; i++) {
		/* First try to load the key from disk */
		if (key_load(&keys[i], &err_code)) {
			/* Key loaded successfully */
			continue;
		}

		/* Key not loaded. Check the error code */
		if (err_code == KEY_ERR_MALLOC) {
			/* Cannot allocate memory. Abort. */
			ERROR("Malloc error while loading '%s'\n", keys[i].fn);
			exit(1);
		} else if (err_code == KEY_ERR_LOAD) {
			/* File exists, but it does not contain a valid private
			 * key. Abort. */
			ERROR("Error loading '%s'\n", keys[i].fn);
			exit(1);
		}

		/* File does not exist, could not be opened or no filename was
		 * given */
		if (new_keys) {
			/* Try to create a new key */
			NOTICE("Creating new key for '%s'\n", keys[i].desc);
			if (!key_create(&keys[i], key_alg)) {
				ERROR("Error creating key '%s'\n", keys[i].desc);
				exit(1);
			}
		} else {
			if (err_code == KEY_ERR_OPEN) {
				ERROR("Error opening '%s'\n", keys[i].fn);
			} else {
				ERROR("Key '%s' not specified\n", keys[i].desc);
			}
			exit(1);
		}
	}

	/* *********************************************************************
	 * BL2 certificate (Trusted Boot Firmware certificate):
	 *     - Self-signed with OEM ROT private key
	 *     - Extensions:
	 *         - TrustedFirmwareNVCounter (TODO)
	 *         - BL2 hash
	 **********************************************************************/
	CHECK_NULL(sk, sk_X509_EXTENSION_new_null());

	/* Add the NVCounter as a critical extension */
	CHECK_NULL(nvctr_ext, ext_new_nvcounter(tz_nvctr_nid, EXT_CRIT,
			tf_nvcounter));
	sk_X509_EXTENSION_push(sk, nvctr_ext);

	/* Add hash of BL2 as an extension */
	if (!sha_file(certs[BL2_CERT].bin, md)) {
		ERROR("Cannot calculate the hash of %s\n", certs[BL2_CERT].bin);
		exit(1);
	}
	CHECK_OID(hash_nid, BL2_HASH_OID);
	CHECK_NULL(hash_ext, ext_new_hash(hash_nid, EXT_CRIT, md_info, md,
			SHA256_DIGEST_LENGTH));
	sk_X509_EXTENSION_push(sk, hash_ext);

	/* Create certificate. Signed with ROT key */
	if (!cert_new(&certs[BL2_CERT], VAL_DAYS, 0, sk)) {
		ERROR("Cannot create %s\n", certs[BL2_CERT].cn);
		exit(1);
	}
	sk_X509_EXTENSION_free(sk);

	/* *********************************************************************
	 * Trusted Key certificate:
	 *     - Self-signed with OEM ROT private key
	 *     - Extensions:
	 *         - TrustedFirmwareNVCounter (TODO)
	 *         - TrustedWorldPK
	 *         - NonTrustedWorldPK
	 **********************************************************************/
	CHECK_NULL(sk, sk_X509_EXTENSION_new_null());
	CHECK_NULL(nvctr_ext, ext_new_nvcounter(tz_nvctr_nid, EXT_CRIT,
			tf_nvcounter));
	sk_X509_EXTENSION_push(sk, nvctr_ext);
	CHECK_OID(pk_nid, TZ_WORLD_PK_OID);
	CHECK_NULL(trusted_key_ext, ext_new_key(pk_nid, EXT_CRIT,
			keys[TRUSTED_WORLD_KEY].key));
	sk_X509_EXTENSION_push(sk, trusted_key_ext);
	CHECK_OID(pk_nid, NTZ_WORLD_PK_OID);
	CHECK_NULL(non_trusted_key_ext, ext_new_key(pk_nid, EXT_CRIT,
			keys[NON_TRUSTED_WORLD_KEY].key));
	sk_X509_EXTENSION_push(sk, non_trusted_key_ext);
	if (!cert_new(&certs[TRUSTED_KEY_CERT], VAL_DAYS, 0, sk)) {
		ERROR("Cannot create %s\n", certs[TRUSTED_KEY_CERT].cn);
		exit(1);
	}
	sk_X509_EXTENSION_free(sk);

	/* *********************************************************************
	 * BL30 Key certificate (Trusted SCP Firmware Key certificate):
	 *     - Self-signed with Trusted World key
	 *     - Extensions:
	 *         - TrustedFirmwareNVCounter (TODO)
	 *         - SCPFirmwareContentCertPK
	 **********************************************************************/
	if (bl30_present) {
		CHECK_NULL(sk, sk_X509_EXTENSION_new_null());
		CHECK_NULL(nvctr_ext, ext_new_nvcounter(tz_nvctr_nid, EXT_CRIT,
				tf_nvcounter));
		sk_X509_EXTENSION_push(sk, nvctr_ext);
		CHECK_OID(pk_nid, BL30_CONTENT_CERT_PK_OID);
		CHECK_NULL(trusted_key_ext, ext_new_key(pk_nid, EXT_CRIT,
				keys[BL30_KEY].key));
		sk_X509_EXTENSION_push(sk, trusted_key_ext);
		if (!cert_new(&certs[BL30_KEY_CERT], VAL_DAYS, 0, sk)) {
			ERROR("Cannot create %s\n", certs[BL30_KEY_CERT].cn);
			exit(1);
		}
		sk_X509_EXTENSION_free(sk);
	}

	/* *********************************************************************
	 * BL30 certificate (SCP Firmware Content certificate):
	 *     - Signed with Trusted World Key
	 *     - Extensions:
	 *         - TrustedFirmwareNVCounter (TODO)
	 *         - SCPFirmwareHash
	 **********************************************************************/
	if (bl30_present) {
		CHECK_NULL(sk, sk_X509_EXTENSION_new_null());
		CHECK_NULL(nvctr_ext, ext_new_nvcounter(tz_nvctr_nid, EXT_CRIT,
				tf_nvcounter));
		sk_X509_EXTENSION_push(sk, nvctr_ext);

		if (!sha_file(certs[BL30_CERT].bin, md)) {
			ERROR("Cannot calculate the hash of %s\n",
					certs[BL30_CERT].bin);
			exit(1);
		}
		CHECK_OID(hash_nid, BL30_HASH_OID);
		CHECK_NULL(hash_ext, ext_new_hash(hash_nid, EXT_CRIT, md_info,
				md, SHA256_DIGEST_LENGTH));
		sk_X509_EXTENSION_push(sk, hash_ext);

		if (!cert_new(&certs[BL30_CERT], VAL_DAYS, 0, sk)) {
			ERROR("Cannot create %s\n", certs[BL30_CERT].cn);
			exit(1);
		}

		sk_X509_EXTENSION_free(sk);
	}

	/* *********************************************************************
	 * BL31 Key certificate (Trusted SoC Firmware Key certificate):
	 *     - Self-signed with Trusted World key
	 *     - Extensions:
	 *         - TrustedFirmwareNVCounter (TODO)
	 *         - SoCFirmwareContentCertPK
	 **********************************************************************/
	CHECK_NULL(sk, sk_X509_EXTENSION_new_null());
	CHECK_NULL(nvctr_ext, ext_new_nvcounter(tz_nvctr_nid, EXT_CRIT,
			tf_nvcounter));
	sk_X509_EXTENSION_push(sk, nvctr_ext);
	CHECK_OID(pk_nid, BL31_CONTENT_CERT_PK_OID);
	CHECK_NULL(trusted_key_ext, ext_new_key(pk_nid, EXT_CRIT,
			keys[BL31_KEY].key));
	sk_X509_EXTENSION_push(sk, trusted_key_ext);
	if (!cert_new(&certs[BL31_KEY_CERT], VAL_DAYS, 0, sk)) {
		ERROR("Cannot create %s\n", certs[BL31_KEY_CERT].cn);
		exit(1);
	}
	sk_X509_EXTENSION_free(sk);

	/* *********************************************************************
	 * BL31 certificate (SOC Firmware Content certificate):
	 *     - Signed with Trusted World Key
	 *     - Extensions:
	 *         - TrustedFirmwareNVCounter (TODO)
	 *         - BL31 hash
	 **********************************************************************/
	CHECK_NULL(sk, sk_X509_EXTENSION_new_null());
	CHECK_NULL(nvctr_ext, ext_new_nvcounter(tz_nvctr_nid, EXT_CRIT,
			tf_nvcounter));
	sk_X509_EXTENSION_push(sk, nvctr_ext);

	if (!sha_file(certs[BL31_CERT].bin, md)) {
		ERROR("Cannot calculate the hash of %s\n", certs[BL31_CERT].bin);
		exit(1);
	}
	CHECK_OID(hash_nid, BL31_HASH_OID);
	CHECK_NULL(hash_ext, ext_new_hash(hash_nid, EXT_CRIT, md_info, md,
			SHA256_DIGEST_LENGTH));
	sk_X509_EXTENSION_push(sk, hash_ext);

	if (!cert_new(&certs[BL31_CERT], VAL_DAYS, 0, sk)) {
		ERROR("Cannot create %s\n", certs[BL31_CERT].cn);
		exit(1);
	}

	sk_X509_EXTENSION_free(sk);

	/* *********************************************************************
	 * BL32 Key certificate (Trusted OS Firmware Key certificate):
	 *     - Self-signed with Trusted World key
	 *     - Extensions:
	 *         - TrustedFirmwareNVCounter (TODO)
	 *         - TrustedOSFirmwareContentCertPK
	 **********************************************************************/
	if (bl32_present) {
		CHECK_NULL(sk, sk_X509_EXTENSION_new_null());
		CHECK_NULL(nvctr_ext, ext_new_nvcounter(tz_nvctr_nid, EXT_CRIT,
				tf_nvcounter));
		sk_X509_EXTENSION_push(sk, nvctr_ext);
		CHECK_OID(pk_nid, BL32_CONTENT_CERT_PK_OID);
		CHECK_NULL(trusted_key_ext, ext_new_key(pk_nid, EXT_CRIT,
				keys[BL32_KEY].key));
		sk_X509_EXTENSION_push(sk, trusted_key_ext);
		if (!cert_new(&certs[BL32_KEY_CERT], VAL_DAYS, 0, sk)) {
			ERROR("Cannot create %s\n", certs[BL32_KEY_CERT].cn);
			exit(1);
		}
		sk_X509_EXTENSION_free(sk);
	}

	/* *********************************************************************
	 * BL32 certificate (TrustedOS Firmware Content certificate):
	 *     - Signed with Trusted World Key
	 *     - Extensions:
	 *         - TrustedFirmwareNVCounter (TODO)
	 *         - BL32 hash
	 **********************************************************************/
	if (bl32_present) {
		CHECK_NULL(sk, sk_X509_EXTENSION_new_null());
		CHECK_NULL(nvctr_ext, ext_new_nvcounter(tz_nvctr_nid, EXT_CRIT,
				tf_nvcounter));
		sk_X509_EXTENSION_push(sk, nvctr_ext);

		if (!sha_file(certs[BL32_CERT].bin, md)) {
			ERROR("Cannot calculate the hash of %s\n",
					certs[BL32_CERT].bin);
			exit(1);
		}
		CHECK_OID(hash_nid, BL32_HASH_OID);
		CHECK_NULL(hash_ext, ext_new_hash(hash_nid, EXT_CRIT, md_info,
				md, SHA256_DIGEST_LENGTH));
		sk_X509_EXTENSION_push(sk, hash_ext);

		if (!cert_new(&certs[BL32_CERT], VAL_DAYS, 0, sk)) {
			ERROR("Cannot create %s\n", certs[BL32_CERT].cn);
			exit(1);
		}

		sk_X509_EXTENSION_free(sk);
	}

	/* *********************************************************************
	 * BL33 Key certificate (Non Trusted Firmware Key certificate):
	 *     - Self-signed with Non Trusted World key
	 *     - Extensions:
	 *         - NonTrustedFirmwareNVCounter (TODO)
	 *         - NonTrustedFirmwareContentCertPK
	 **********************************************************************/
	CHECK_NULL(sk, sk_X509_EXTENSION_new_null());
	CHECK_NULL(nvctr_ext, ext_new_nvcounter(ntz_nvctr_nid, EXT_CRIT,
			non_tf_nvcounter));
	sk_X509_EXTENSION_push(sk, nvctr_ext);
	CHECK_OID(pk_nid, BL33_CONTENT_CERT_PK_OID);
	CHECK_NULL(non_trusted_key_ext, ext_new_key(pk_nid, EXT_CRIT,
			keys[BL33_KEY].key));
	sk_X509_EXTENSION_push(sk, non_trusted_key_ext);
	if (!cert_new(&certs[BL33_KEY_CERT], VAL_DAYS, 0, sk)) {
		ERROR("Cannot create %s\n", certs[BL33_KEY_CERT].cn);
		exit(1);
	}
	sk_X509_EXTENSION_free(sk);

	/* *********************************************************************
	 * BL33 certificate (Non-Trusted World Content certificate):
	 *     - Signed with Non-Trusted World Key
	 *     - Extensions:
	 *         - NonTrustedFirmwareNVCounter (TODO)
	 *         - BL33 hash
	 **********************************************************************/
	CHECK_NULL(sk, sk_X509_EXTENSION_new_null());
	CHECK_NULL(nvctr_ext, ext_new_nvcounter(ntz_nvctr_nid, EXT_CRIT,
			non_tf_nvcounter));
	sk_X509_EXTENSION_push(sk, nvctr_ext);

	if (!sha_file(certs[BL33_CERT].bin, md)) {
		ERROR("Cannot calculate the hash of %s\n", certs[BL33_CERT].bin);
		exit(1);
	}
	CHECK_OID(hash_nid, BL33_HASH_OID);
	CHECK_NULL(hash_ext, ext_new_hash(hash_nid, EXT_CRIT, md_info, md,
			SHA256_DIGEST_LENGTH));
	sk_X509_EXTENSION_push(sk, hash_ext);

	if (!cert_new(&certs[BL33_CERT], VAL_DAYS, 0, sk)) {
		ERROR("Cannot create %s\n", certs[BL33_CERT].cn);
		exit(1);
	}
	sk_X509_EXTENSION_free(sk);

	/* Print the certificates */
	if (print_cert) {
		for (i = 0 ; i < NUM_CERTIFICATES ; i++) {
			if (!certs[i].x) {
				continue;
			}
			printf("\n\n=====================================\n\n");
			X509_print_fp(stdout, certs[i].x);
		}
	}

	/* Save created certificates to files */
	for (i = 0 ; i < NUM_CERTIFICATES ; i++) {
		if (certs[i].x && certs[i].fn) {
			file = fopen(certs[i].fn, "w");
			if (file != NULL) {
				i2d_X509_fp(file, certs[i].x);
				fclose(file);
			} else {
				ERROR("Cannot create file %s\n", certs[i].fn);
			}
		}
	}

	/* Save keys */
	if (save_keys) {
		for (i = 0 ; i < NUM_KEYS ; i++) {
			if (!key_store(&keys[i])) {
				ERROR("Cannot save %s\n", keys[i].desc);
			}
		}
	}

	X509_EXTENSION_free(hash_ext);
	X509_EXTENSION_free(nvctr_ext);
	X509_EXTENSION_free(trusted_key_ext);
	X509_EXTENSION_free(non_trusted_key_ext);

#ifndef OPENSSL_NO_ENGINE
	ENGINE_cleanup();
#endif
	CRYPTO_cleanup_all_ex_data();

	return 0;
}
Example #29
0
/* Get and print status from apcupsd NIS server */
static int apc_query_server (char *host, int port,
		struct apc_detail_s *apcups_detail)
{
	int     n;
	char    recvline[1024];
	char   *tokptr;
	char   *toksaveptr;
	char   *key;
	double  value;
	_Bool retry = 1;
	int status;

#if APCMAIN
# define PRINT_VALUE(name, val) printf("  Found property: name = %s; value = %f;\n", name, val)
#else
# define PRINT_VALUE(name, val) /**/
#endif

	while (retry)
	{
		if (global_sockfd < 0)
		{
			global_sockfd = net_open (host, port);
			if (global_sockfd < 0)
			{
				ERROR ("apcups plugin: Connecting to the "
						"apcupsd failed.");
				return (-1);
			}
		}


		status = net_send (&global_sockfd, "status", strlen ("status"));
		if (status != 0)
		{
			/* net_send is closing the socket on error. */
			assert (global_sockfd < 0);
			if (retry)
			{
				retry = 0;
				count_retries++;
				continue;
			}

			ERROR ("apcups plugin: Writing to the socket failed.");
			return (-1);
		}

		break;
	} /* while (retry) */

        /* When collectd's collection interval is larger than apcupsd's
         * timeout, we would have to retry / re-connect each iteration. Try to
         * detect this situation and shut down the socket gracefully in that
         * case. Otherwise, keep the socket open to avoid overhead. */
	count_iterations++;
	if ((count_iterations == 10) && (count_retries > 2))
	{
		NOTICE ("apcups plugin: There have been %i retries in the "
				"first %i iterations. Will close the socket "
				"in future iterations.",
				count_retries, count_iterations);
		close_socket = 1;
	}

	while ((n = net_recv (&global_sockfd, recvline, sizeof (recvline) - 1)) > 0)
	{
		assert ((unsigned int)n < sizeof (recvline));
		recvline[n] = '\0';
#if APCMAIN
		printf ("net_recv = `%s';\n", recvline);
#endif /* if APCMAIN */

		toksaveptr = NULL;
		tokptr = strtok_r (recvline, " :\t", &toksaveptr);
		while (tokptr != NULL)
		{
			key = tokptr;
			if ((tokptr = strtok_r (NULL, " :\t", &toksaveptr)) == NULL)
				continue;
			value = atof (tokptr);

			PRINT_VALUE (key, value);

			if (strcmp ("LINEV", key) == 0)
				apcups_detail->linev = value;
			else if (strcmp ("BATTV", key) == 0)
				apcups_detail->battv = value;
			else if (strcmp ("ITEMP", key) == 0)
				apcups_detail->itemp = value;
			else if (strcmp ("LOADPCT", key) == 0)
				apcups_detail->loadpct = value;
			else if (strcmp ("BCHARGE", key) == 0)
				apcups_detail->bcharge = value;
			else if (strcmp ("OUTPUTV", key) == 0)
				apcups_detail->outputv = value;
			else if (strcmp ("LINEFREQ", key) == 0)
				apcups_detail->linefreq = value;
			else if (strcmp ("TIMELEFT", key) == 0)
			{
				/* Convert minutes to seconds if requested by
				 * the user. */
				if (conf_report_seconds)
					value *= 60.0;
				apcups_detail->timeleft = value;
			}

			tokptr = strtok_r (NULL, ":", &toksaveptr);
		} /* while (tokptr != NULL) */
	}
	status = errno; /* save errno, net_shutdown() may re-set it. */

	if (close_socket)
		net_shutdown (&global_sockfd);

	if (n < 0)
	{
		char errbuf[1024];
		ERROR ("apcups plugin: Reading from socket failed: %s",
				sstrerror (status, errbuf, sizeof (errbuf)));
		return (-1);
	}

	return (0);
}
Example #30
0
int
main (int argc, char **argv, char **envp)
{
  FILE *list, *fp;
  int i, j, count;
  int lines = 0;
  
  struct ionogram *ionogram;
  struct ionogram_filename fn;
  struct strlist *names;
  struct station_info *info;
  struct globe_data *globe;
  struct ionogram_filetype *ft;
  struct layer_info *this;
  
  if (argc != 2)
  {
    fprintf (stderr, "Usage: %s <pattern.lst>\n", argv[0]);
    fprintf (stderr, "\n%s picks random ionogram from the NOAA server and builds\n", argv[0]);
    fprintf (stderr, "a training set with the existence state of each ionosphere layer.\n");
    fprintf (stderr, "\n");
    fprintf (stderr, "The training set file is in ID3 format.\n");
    
    return 1;
  }
  
  signal (SIGINT, sigint_handler);
  
  if (access (argv[1], F_OK) != -1)
    fprintf (stderr, "%s: appending to existing file %s\n", argv[0], argv[1]);
  
  if ((list = fopen (argv[1], "a")) == NULL)
  {
    fprintf (stderr, "%s: couldn't append to file %s: %s\n", argv[0], argv[1], strerror (errno));
    
    return 1;
  }
  
  srand (time (NULL));
  
  if (libsao_init () == -1)
    return 1;
    
  if (ionowatch_config_init () == -1)
    return -1;
    
  globe = globe_data_new (0, 0, 100, 100);
  ft = ionogram_filetype_lookup ("SAO");
  
  printf ("%s staring (press Ctrl+C to stop)\n", argv[0]);
  
  for (; training;)
  {
    printf ("Please wait while %s looks for a suitable station...\n", argv[0]);
  
    for (;;)
    {
      names = pickup_random_files ();
      
      if (names->strings_count == 0)
      {
        strlist_destroy (names);
        continue;
      }
      
      break;
    }
    
    if (ionogram_parse_filename (names->strings_list[0], &fn) == -1)
    {
      ERROR ("%s: malformed filename, couldn't load\n", names->strings_list[i]);
      strlist_destroy (names);
      continue;
    }

    if ((info = station_lookup (fn.station)) == NULL)
    {
      ERROR ("couldn't find station data for `%s'\n", fn.station);
      strlist_destroy (names);
      continue; /* We're almost sure that there will be no other filename
                 refering to a different station in this directory */
    }
    
    for (i = 0; i < names->strings_count && training; i++)
    {
      NOTICE ("parsing files [%3d/%3d]... ", 
        i + 1, names->strings_count);
      
      fflush (stdout);
      
      if (ionogram_parse_filename (names->strings_list[i], &fn) == -1)
      {
        NOTICE ("%s: malformed filename, couldn't load\n", names->strings_list[i]);
        continue;
      }

      if ((fp = cache_get_ionogram (&fn)) != NULL)
      {
        ionogram = ionogram_new ();
        
        if ((ft->parse_callback) (ionogram, fp) == 0)
        {
          globe_data_set_time (globe, fn.time);
          
          count = 0;
          
          for (j = 0; j < IONOGRAM_MAX_LAYERS && training; j++)
          {
            fprintf (list, "%lg %lg %lg %lg %lg %d ",
              info->lat, info->lon,
              globe_data_get_sun_inclination (globe, RADADJUST (DEG2RAD (info->lat)), RADADJUST (DEG2RAD (-info->lon))),
              RADADJUST (globe->sol),
              get_monthly_sunspot_number (fn.time),
              j);
              
            if ((this = ionogram->layers[j]) != NULL)
            {
              count++;
              fprintf (list, " 1\n");
            }
            else
              fprintf (list, " 0\n");
              
            lines++;
          }
           
          printf ("%d layers present\n", count); 
        }
        else
          printf ("%s: error parsing ionogram\n", names->strings_list[i]);
        
        ionogram_destroy (ionogram);
        
        fclose (fp);
      }
      else
        NOTICE ("%s: coudln't retrieve form cache\n", names->strings_list[i]);
    }
    
    strlist_destroy (names);
  }
  
  printf ("\n%s: fetching stopped, %d samples saved to %s\n", 
    argv[0], lines, argv[1]);
    
  fclose (list);
  
  return 0;
}