Example #1
0
File: main.c Project: harbop/spop
/**********************
 *** Initialization ***
 **********************/
int main(int argc, char** argv) {
    gboolean daemon_mode = TRUE;
    const char* username;
    const char* password;
    GMainLoop* main_loop;

    /* Parse command line options */
    int opt;
    while ((opt = getopt(argc, argv, "dfhv")) != -1) {
        switch (opt) {
        case 'd':
            debug_mode = TRUE;
        case 'v':
            verbose_mode = TRUE;
        case 'f':
            daemon_mode = FALSE; break;
        default:
            printf("Usage: spopd [options]\n"
                   "Options:\n"
                   "  -d        debug mode (implies -f and -v)\n"
                   "  -f        run in foreground (default: fork to background)\n"
                   "  -v        verbose mode (implies -f)\n"
                   "  -h        display this message\n");
            return 0;
        }
    }

    g_set_application_name("spop " SPOP_VERSION);
    g_set_prgname("spop");
    g_type_init();

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

    /* Log handler */
    logging_init();

    if (!daemon_mode) {
        /* Stay in foreground: do everything here */
        if (debug_mode)
            g_info("Running in debug mode");
    }
    else {
        /* Run in daemon mode: fork to background */
        printf("Switching to daemon mode...\n");
        if (daemon(0, 0) != 0)
            g_error("Error while forking process: %s", g_strerror(errno));

    }

    /* Init essential stuff */
    main_loop = g_main_loop_new(NULL, FALSE);
    exit_handler_init();

    /* Read username and password */
    username = config_get_string("spotify_username");
    password = config_get_string("spotify_password");

    /* Init plugins */
    plugins_init();

    /* Init login */
    session_init();
    session_login(username, password);

    /* Init various subsystems */
    interface_init();

    /* Event loop */
    g_main_loop_run(main_loop);

    return 0;
}
Example #2
0
/**
 * Set the page cache size.
 * @return 0 if OK, -1 on failure with errno set.
 */
int
setcache(DBM *db, long pages)
{
	struct lru_cache *cache = db->cache;
	gboolean wdelay;

	if (pages <= 0) {
		errno = EINVAL;
		return -1;
	}

	if (NULL == cache)
		return init_cache(db, pages, FALSE);

	/*
	 * Easiest case: the size identical.
	 */

	if (pages == cache->pages)
		return 0;

	/*
	 * Cache size is changed.
	 *
	 * This means the arena will be reallocated, so we must invalidate the
	 * current db->pagbuf pointer, which lies within the old arena.  It is
	 * sufficient to reset db->pagbno, forcing a reload from the upper layers.
	 * Note than when the cache size is enlarged, the old page is still cached
	 * so reloading will be just a matter of recomputing db->pagbuf.  We could
	 * do so here, but cache size changes should only be infrequent.
	 *
	 * We also reset all the cache statistics, since a different cache size
	 * will imply a different set of hit/miss ratio.
	 */

	db->pagbno = -1;		/* Current page address will become invalid */
	db->pagbuf = NULL;

	if (common_stats) {
		g_info("sdbm: \"%s\" LRU cache size %s from %ld page%s to %ld",
			sdbm_name(db), pages > cache->pages ? "increased" : "decreased",
			cache->pages, 1 == cache->pages ? "" : "s", pages);
		log_lrustats(db);
	}

	cache->rhits = cache->rmisses = 0;
	cache->whits = cache->wmisses = 0;

	/*
	 * Straightforward: the size is increased.
	 */

	if (pages > cache->pages) {
		char *new_arena = vmm_alloc(pages * DBM_PBLKSIZ);
		if (NULL == new_arena)
			return -1;
		memmove(new_arena, cache->arena, cache->pages * DBM_PBLKSIZ);
		vmm_free(cache->arena, cache->pages * DBM_PBLKSIZ);
		cache->arena = new_arena;
		cache->dirty = wrealloc(cache->dirty, cache->pages, pages);
		cache->numpag = wrealloc(cache->numpag,
			cache->pages * sizeof(long), pages * sizeof(long));
		cache->pages = pages;
		return 0;
	}

	/*
	 * Difficult: the size is decreased.
	 *
	 * The current page buffer could point in a cache area that is going
	 * to disappear, and the internal data structures must forget about
	 * all the old indices that are greater than the new limit.
	 *
	 * We do not try to optimize anything here, as this call should happen
	 * only infrequently: we flush the current cache (in case there are
	 * deferred writes), destroy the LRU cache data structures, recreate a
	 * new one and invalidate the current DB page.
	 */

	wdelay = cache->write_deferred;
	flush_dirtypag(db);
	free_cache(cache);
	return setup_cache(cache, pages, wdelay);
}
Example #3
0
JsonObject *
cockpit_auth_login_finish (CockpitAuth *self,
                           GAsyncResult *result,
                           CockpitAuthFlags flags,
                           GHashTable *out_headers,
                           GError **error)
{
  CockpitAuthClass *klass = COCKPIT_AUTH_GET_CLASS (self);
  CockpitAuthenticated *authenticated;
  CockpitTransport *transport = NULL;
  JsonObject *prompt_data = NULL;
  CockpitCreds *creds;
  gchar *cookie_b64 = NULL;
  gchar *cookie_name = NULL;
  gchar *header;
  gchar *id;

  g_return_val_if_fail (klass->login_finish != NULL, FALSE);
  creds = klass->login_finish (self, result, out_headers,
                               &prompt_data, &transport, error);
  self->startups--;

  if (creds == NULL)
    return prompt_data;

  id = cockpit_auth_nonce (self);
  authenticated = g_new0 (CockpitAuthenticated, 1);
  authenticated->cookie = g_strdup_printf ("v=2;k=%s", id);
  authenticated->creds = creds;
  authenticated->service = cockpit_web_service_new (creds, transport);
  authenticated->auth = self;

  authenticated->idling_sig = g_signal_connect (authenticated->service, "idling",
                                                G_CALLBACK (on_web_service_idling), authenticated);
  authenticated->destroy_sig = g_signal_connect (authenticated->service, "destroy",
                                                G_CALLBACK (on_web_service_destroy), authenticated);

  if (transport)
    g_object_unref (transport);

  g_object_weak_ref (G_OBJECT (authenticated->service),
                     on_web_service_gone, authenticated);

  /* Start off in the idling state, and begin a timeout during which caller must do something else */
  on_web_service_idling (authenticated->service, authenticated);

  g_hash_table_insert (self->authenticated, authenticated->cookie, authenticated);

  g_debug ("sending %s credential id '%s' for user '%s'", id,
           cockpit_creds_get_application (creds),
           cockpit_creds_get_user (creds));

  g_free (id);

  if (out_headers)
    {
      gboolean force_secure = !(flags & COCKPIT_AUTH_COOKIE_INSECURE);
      cookie_name = application_cookie_name (cockpit_creds_get_application (creds));
      cookie_b64 = g_base64_encode ((guint8 *)authenticated->cookie, strlen (authenticated->cookie));
      header = g_strdup_printf ("%s=%s; Path=/; %s HttpOnly",
                                cookie_name, cookie_b64,
                                force_secure ? " Secure;" : "");
      g_free (cookie_b64);
      g_free (cookie_name);
      g_hash_table_insert (out_headers, g_strdup ("Set-Cookie"), header);
    }

  g_info ("logged in user: %s", cockpit_creds_get_user (authenticated->creds));

  return cockpit_creds_to_json (creds);
}
Example #4
0
static void load_input_conf(GmpvMpv *mpv, const gchar *input_conf)
{
	const gchar *default_keybinds[] = DEFAULT_KEYBINDS;
	gchar *tmp_path;
	FILE *tmp_file;
	gint tmp_fd;

	tmp_fd = g_file_open_tmp(NULL, &tmp_path, NULL);
	tmp_file = fdopen(tmp_fd, "w");
	mpv->tmp_input_file = tmp_path;

	if(!tmp_file)
	{
		g_error("Failed to open temporary input config file");
	}

	for(gint i = 0; default_keybinds[i]; i++)
	{
		const gsize len = strlen(default_keybinds[i]);
		gsize write_size;
		gint rc;

		write_size = fwrite(default_keybinds[i], len, 1, tmp_file);
		rc = fputc('\n', tmp_file);

		if(write_size != 1 || rc != '\n')
		{
			g_error(	"Error writing default keybindings to "
					"temporary input config file" );
		}
	}

	g_debug("Using temporary input config file: %s", tmp_path);
	mpv_set_option_string(mpv->mpv_ctx, "input-conf", tmp_path);

	if(input_conf && strlen(input_conf) > 0)
	{
		const gsize buf_size = 65536;
		void *buf = g_malloc(buf_size);
		FILE *src_file = g_fopen(input_conf, "r");
		gsize read_size = buf_size;

		if(!src_file)
		{
			g_warning(	"Cannot open input config file: %s",
					input_conf );
		}

		while(src_file && read_size == buf_size)
		{
			read_size = fread(buf, 1, buf_size, src_file);

			if(read_size != fwrite(buf, 1, read_size, tmp_file))
			{
				g_error(	"Error writing requested input "
						"config file to temporary "
						"input config file" );
			}
		}

		g_info("Loaded input config file: %s", input_conf);

		g_free(buf);
	}

	fclose(tmp_file);
}
Example #5
0
static  void    gml_hx_common( gml_tag gtag, int hx_lvl )
{
    char    *   p;
    char    *   headp;
    bool        idseen;
    bool        stitleseen;
    int         rc;
    int         k;
    size_t      headlen;
    size_t      txtlen;
    char        hnumstr[64];
    ref_entry   *   re;
    ref_entry   *   rwk;
    static char hxstr[4] = ":HX";
    static char htextx[8] = "$htextX";
    static char headx[7]  = "$headX";

    gtag = gtag;

    *(hxstr + 2) = '0' + hx_lvl;
    htextx[6] = '0' + hx_lvl;
    hnumx[5] = '0' + hx_lvl;
    headx[5] = '0' + hx_lvl;

    switch( hx_lvl ) {
    case   0:
        if( !((ProcFlags.doc_sect == doc_sect_body) ||
            (ProcFlags.doc_sect_nxt == doc_sect_body)) ) {

            g_err( err_tag_wrong_sect, hxstr, ":BODY section" );
            err_count++;
            file_mac_info();
        }
        break;
    case  1:
        if( !((ProcFlags.doc_sect >= doc_sect_body) ||
            (ProcFlags.doc_sect_nxt >= doc_sect_body)) ) {

            g_err( err_tag_wrong_sect, hxstr, ":BODY :APPENDIX :BACKM sections" );
            err_count++;
            file_mac_info();
        }
        break;
    default:
        if( !((ProcFlags.doc_sect >= doc_sect_abstract) ||
            (ProcFlags.doc_sect_nxt >= doc_sect_abstract)) ) {

            g_err( err_tag_wrong_sect, hxstr, ":ABSTRACT section or later" );
            err_count++;
            file_mac_info();
        }
        break;
    }
    if( layout_work.hx[hx_lvl].number_form != num_none ) {
        layout_work.hx[hx_lvl].headn++;
    }

    idseen = false;
    stitleseen = false;
    p = scan_start;
    re = NULL;

    /***********************************************************************/
    /*  Scan attributes  for :Hx                                           */
    /*  id=                                                                */
    /*  stitle=                                                            */
    /***********************************************************************/

    for( ;; ) {
        while( *p == ' ' ) {
            p++;
        }
        if( *p == '\0' || *p == '.'  ) {
            break;                      // tag end found
        }
        if( !strnicmp( "stitle=", p, 7 ) ) {
            p += 6;
            stitleseen = true;

            /***************************************************************/
            /*  Although unsupported scan stitle='xxx'                     */
            /***************************************************************/
            g_warn( wng_unsupp_att, "stitle" );
            wng_count++;
            file_mac_info();

            p = get_att_value( p );

            scan_start = p;
            if( !ProcFlags.tag_end_found ) {
                continue;
            }
            break;
        }

        /*******************************************************************/
        /*  ID='xxxxxxxx'                                                  */
        /*******************************************************************/

        if( !strnicmp( "id=", p, 3 ) ) {
            p += 2;

            p = get_refid_value( p );

            if( val_len > 0 ) {
                idseen = true;          // valid id attribute found
                *(val_start + val_len) = '\0';

                if( re == NULL ) {      // prepare reference entry
                    re = mem_alloc( sizeof( ref_entry ) );
                    init_ref_entry( re, val_start, val_len );
                } else {
                    fill_id( re, val_start, val_len );
                }
            }
            scan_start = p;
            if( !ProcFlags.tag_end_found ) {
                continue;
            }
            break;
        }

        /*******************************************************************/
        /* no more valid attributes, process remaining input as header text*/
        /*******************************************************************/
        break;
    }
    if( *p == '.' ) {                   // tag end ?
        p++;
    }

    /************************************************************************/
    /*  set the global vars $headx, $headnumx, $htextx                      */
    /*    perhaps text translated to upper or lower case                    */
    /************************************************************************/
    while( *p == ' ' ) {                // ignore leading blanks
        p++;
    }
    if( *p ) {                          // text exists
        if( layout_work.hx[hx_lvl].cases == case_lower ) {
            strlwr( p );
        } else if( layout_work.hx[hx_lvl].cases == case_upper ) {
            strupr( p );
        }
    }
    rc = add_symvar( &global_dict, htextx, p, no_subscript, 0 );

    update_headnumx( hx_lvl, hnumstr, sizeof( hnumstr ) );

    txtlen = strlen( p );
    headlen = strlen( hnumstr) + txtlen + 2;
    headp = mem_alloc( headlen );
    if( layout_work.hx[hx_lvl].number_form != num_none ) {
        strcpy( headp, hnumstr); // numbered header
        strcat( headp, " " );
    } else {
        *headp = '\0';
    }
    strcat( headp, p );
    rc = add_symvar( &global_dict, headx, headp, no_subscript, 0 );

    out_msg( " %s\n", headp );          // always verbose output ? TBD

    mem_free( headp );

    /***********************************************************************/
    /*  if id  specified add it to reference dict                          */
    /***********************************************************************/
    if( idseen ) {
        rwk = find_refid( ref_dict, re->id );
        if( !rwk ) {                    // new entry
            if( txtlen > 0 ) {          // text line not empty
                re->u.info.text_cap = mem_alloc( txtlen + 1 );
                strcpy( re->u.info.text_cap, p );
            }
            add_ref_entry( &ref_dict, re );
            re = NULL;                  // free will be done via dictionary
        } else {
            /***************************************************************/
            /*  test for duplicate id                                      */
            /*  it is done with comparing line no only, in the hope that   */
            /*  two identical ids are not specified in different files on  */
            /*  the same line no.                                          */
            /***************************************************************/
            if( re->lineno != rwk->lineno ) {
                g_err( wng_id_xxx, re->id );
                g_info( inf_id_duplicate );
                file_mac_info();
                err_count++;
            }
            if( re->u.info.text_cap != NULL ) {
                mem_free( re->u.info.text_cap );
            }
            mem_free( re );
        }
    }

    if( layout_work.hx[hx_lvl].number_reset ) {
        for( k = hx_lvl + 1; k < 7; k++ ) {
            layout_work.hx[k].headn = 0;// reset following levels
            if( layout_work.hx[k].headnsub != NULL ) {
                *(layout_work.hx[k].headnsub->value) = '\0';
            }
        }
    }

    /***********************************************************************/
    /*  creation of actual heading                                         */
    /***********************************************************************/

    /***********************************************************************/
    /*  eject page(s) if specified                                         */
    /***********************************************************************/
    if( layout_work.hx[hx_lvl].page_eject != ej_no ) {

        if( ProcFlags.page_started ) {
            do_page_out();
            reset_t_page();
        }

        if( !ProcFlags.start_section ) {
            start_doc_sect();
        }
        set_headx_banners( hx_lvl );        // set possible banners
        reset_t_page();                     // and adjust page margins


        if( (layout_work.hx[hx_lvl].page_eject == ej_odd) && (page & 1) ) {
            do_page_out();              // next page would be even
            reset_t_page();
        } else if( (layout_work.hx[hx_lvl].page_eject == ej_even) && !(page & 1) ) {
            do_page_out();              // next page would be odd
            reset_t_page();
        }
    }

    if( layout_work.hx[hx_lvl].display_heading ) {

        hx_header( hx_lvl, hnumstr, p );
    }

    scan_start = scan_stop;
    return;
}
Example #6
0
static void onNativeWindowResized(ANativeActivity* activity, ANativeWindow* window) {
    g_info("NativeWindowResized: %p -- %p\n", activity, window);
    //android_app_write_cmd((struct android_app*)activity->instance, APP_CMD_WINDOW_RESIZED);
}
Example #7
0
static void onContentRectChanged(ANativeActivity* activity, const ARect* rect) {
    g_info("ContentRectChanged: %p -- (%d,%d)-(%d,%d)\n", activity, rect->left,
           rect->top, rect->right, rect->bottom);
    //android_app_set_content_rect((struct android_app*)activity->instance, rect);
}
Example #8
0
static void queue_outgoing(struct mwChannel *chan,
			   struct mwMsgChannelSend *msg) {

  g_info("queue_outgoing, channel 0x%08x", chan->id);
  chan->outgoing_queue = g_slist_append(chan->outgoing_queue, msg);
}
Example #9
0
static int execute_command(const gchar *command, const gchar *username,
    const gchar *password, const gchar *lttd_path)
{
  pid_t pid;
  int fdpty;
  pid = forkpty(&fdpty, NULL, NULL, NULL);
  int retval = 0;

  if(pid > 0) {
    /* parent */
    gchar buf[256];
    int status;
    ssize_t count;
    /* discuss with su */

    struct pollfd pollfd;
    int num_rdy;
    int num_hup = 0;
		enum read_state { GET_LINE, GET_SEMI, GET_SPACE } read_state = GET_LINE;

		retval = fcntl(fdpty, F_SETFL, O_WRONLY);
		if(retval == -1) {
			perror("Error in fcntl");
			goto wait_child;
		}

    /* Read the output from the child terminal before the prompt. If no data in
     * 200 ms, we stop reading to give the password */
    g_info("Reading from child console...");
    while(1) {
      pollfd.fd = fdpty;
      pollfd.events = POLLIN|POLLPRI|POLLERR|POLLHUP|POLLNVAL;

      num_rdy = poll(&pollfd, 1, -1);
      if(num_rdy == -1) {
        perror("Poll error");
        goto wait_child;
      }
      
      /* Timeout : Stop waiting for chars */
      if(num_rdy == 0) goto wait_child;

      /* Check for fatal errors */
      if(pollfd.revents & POLLERR) {
          g_warning("Error returned in polling fd\n");
          num_hup++;
      }
      if(pollfd.revents & POLLNVAL) {
	g_warning("Polling fd tells it is not open");
	num_hup++;
      }

      if(pollfd.revents & POLLHUP) {

	g_info("Polling FD : hung up.");
	num_hup++;

      }

      if(pollfd.revents & (POLLIN | POLLPRI)) {
	int count;
	count = read (fdpty, buf, 256);
	if(count > 0) {
	  unsigned int i;
	  buf[count] = '\0';
	  g_printf("%s", buf);
	  for(i=0; i<count; i++) {
	    switch(read_state) {
	    case GET_LINE:
	      if(buf[i] == '\n') {
		read_state = GET_SEMI;
		g_debug("Tracecontrol input line skip\n");
	      }
	      break;
	    case GET_SEMI:
	      if(buf[i] == ':') {
		g_debug("Tracecontrol input  : marker found\n");
		read_state = GET_SPACE;
	      }
	      break;
	    case GET_SPACE:
	      if(buf[i] == ' ') {
		g_debug("Tracecontrol input space marker found\n");
		goto write_password;
	      }
	      break;
	    }
	  }
	} else if(count == -1) {
	  perror("Error in read");
	  goto wait_child;
	}

      }

      if(num_hup > 0) {
        g_warning("Child hung up without returning a full reply");
        goto wait_child;
      }
    }
write_password:
		fsync(fdpty);
		pollfd.fd = fdpty;
		pollfd.events = POLLOUT|POLLERR|POLLHUP|POLLNVAL;

		num_rdy = poll(&pollfd, 1, -1);
		if(num_rdy == -1) {
			perror("Poll error");
			goto wait_child;
		}

    /* Write the password */
    g_info("Got su prompt, now writing password...");
    int ret;
		sleep(1);
    ret = write(fdpty, password, strlen(password));
    if(ret < 0) perror("Error in write");
    ret = write(fdpty, "\n", 1);
    if(ret < 0) perror("Error in write");
    fsync(fdpty);
    /* Take the output from the terminal and show it on the real console */
    g_info("Getting data from child terminal...");
    while(1) {
      int num_hup = 0;
      pollfd.fd = fdpty;
      pollfd.events = POLLIN|POLLPRI|POLLERR|POLLHUP|POLLNVAL;

      num_rdy = poll(&pollfd, 1, -1);
      if(num_rdy == -1) {
        perror("Poll error");
        goto wait_child;
      }
      if(num_rdy == 0) break;
	
			if(pollfd.revents & (POLLERR|POLLNVAL)) {
				g_warning("Error returned in polling fd\n");
				num_hup++;
			}

			if(pollfd.revents & (POLLIN|POLLPRI) ) {
				count = read (fdpty, buf, 256);
				if(count > 0) {
					buf[count] = '\0';
					printf("%s", buf);
				} else if(count == -1) {
					perror("Error in read");
					goto wait_child;
				}
			}

			if(pollfd.revents & POLLHUP) {
        g_info("Polling FD : hung up.");
        num_hup++;
			}

      if(num_hup > 0) goto wait_child;
    }
wait_child:
    g_info("Waiting for child exit...");
    
    ret = waitpid(pid, &status, 0);
    
    if(ret == -1) {
      g_warning("An error occured in wait : %s",
          strerror(errno));
    } else {
      if(WIFEXITED(status))
        if(WEXITSTATUS(status) != 0) {
          retval = WEXITSTATUS(status);
          g_warning("An error occured in the su command : %s",
              strerror(retval));
        }
    }

    g_info("Child exited.");

  } else if(pid == 0) {
    /* Setup environment variables */
    if(strcmp(lttd_path, "") != 0)
      setenv("LTT_DAEMON", lttd_path, 1);
   
		/* One comment line (must be only one) */
    g_printf("Executing (as %s) : %s\n", username, command);
    
    execlp("su", "su", "-p", "-c", command, username, NULL);
    exit(-1); /* not supposed to happen! */
    
    //gint ret = execvp();
  
  } else {
    /* error */
    g_warning("Error happened when forking for su");
  }

  return retval;
}
Example #10
0
/* Check for completed transfers, and remove their easy handles */
static void check_run_count(void)
{
	g_debug("%s queued %i active %i", __PRETTY_FUNCTION__, curl_runtime.queued, curl_runtime.active);
	if( curl_runtime.queued > curl_runtime.active )
	{
		char *eff_url=NULL;
		CURLMsg *msg;
		int msgs_left;
		struct session *session=NULL;
		CURL*easy;

		g_debug("REMAINING: %d", curl_runtime.queued);
		easy=NULL;
		while( (msg = curl_multi_info_read(curl_runtime.multi, &msgs_left)) )
		{
			if( msg->msg == CURLMSG_DONE )
			{
				curl_runtime.queued--;

				easy=msg->easy_handle;
				curl_easy_getinfo(easy, CURLINFO_PRIVATE, (char **)&session );
				curl_easy_getinfo(easy, CURLINFO_EFFECTIVE_URL, &eff_url);

				switch( session->type )
				{
				case session_type_download:
					if( msg->data.result == CURLE_OK )
					{
						g_info("DOWNLOAD DONE: %s => (%d) %s", eff_url, msg->data.result, session->error);
						tempfile_close(session->action.download.file);

						struct incident *i = incident_new("dionaea.download.complete");
						incident_value_string_set(i, "path", g_string_new(session->action.download.file->path));
						incident_value_string_set(i, "url", g_string_new(session->url));
						if( session->action.download.ctxcon )
							incident_value_con_set(i, "con", session->action.download.ctxcon);

						incident_report(i);
						incident_free(i);
					} else
					{
						g_warning("DOWNLOAD FAIL: %s => (%d) %s", eff_url, msg->data.result, session->error);
						tempfile_close(session->action.download.file);
					}
					break;

				case session_type_upload:
					if( msg->data.result == CURLE_OK )
					{
						g_info("UPLOAD DONE: %s => (%d) %s", eff_url, msg->data.result, session->error);

						if( session->action.upload.callback == NULL )
							break;
						
						tempfile_close(session->action.upload.file);
						// if we have a callback, call the callback
						struct incident *i = incident_new(session->action.upload.callback);
						incident_value_string_set(i, "path", g_string_new(session->action.upload.file->path));
						if( session->action.upload.userdata != NULL )
							incident_value_string_set(i, "_userdata", g_string_new(session->action.upload.userdata));
						incident_report(i);
						incident_free(i);
						tempfile_unlink(session->action.upload.file);
					} else
					{
						g_warning("UPLOAD FAIL: %s => (%d) %s", eff_url, msg->data.result, session->error);

						if( session->action.upload.callback == NULL )
							break;

						tempfile_close(session->action.upload.file);
						tempfile_unlink(session->action.upload.file);
					}
					break;
				}

				curl_multi_remove_handle(curl_runtime.multi, easy);
				curl_easy_cleanup(easy);
				session_free(session);
			}
		}
	}
}
Example #11
0
static bool curl_new(struct dionaea *d)
{
	g_debug("%s", __PRETTY_FUNCTION__);

	struct lcfgx_tree_node *node;
	if( lcfgx_get_string(g_dionaea->config.root, &node, "downloads.dir") != LCFGX_PATH_FOUND_TYPE_OK )
	{
		g_warning("missing downloads.dir in dionaea.conf");
		return false;
	}

	curl_runtime.download_dir = g_strdup((char *)node->value.string.data);


	if( curl_global_init(CURL_GLOBAL_ALL) != 0 )
		return false;

	curl_version_info_data *curlinfo;
	curlinfo = curl_version_info(CURLVERSION_NOW);

	GString *features = g_string_new("");
	GString *protocols = g_string_new("");
	if( curlinfo->features )
	{

		struct curl_feature
		{
			const char *name;
			int bitmask;
		};
		static const struct curl_feature feats[] = {
			{"c-ares", CURL_VERSION_ASYNCHDNS},
			{"debug", CURL_VERSION_DEBUG},
#ifdef CURL_VERSION_CURLDEBUG
			{"debugmemory", CURL_VERSION_CURLDEBUG},
#endif
			{"gss", CURL_VERSION_GSSNEGOTIATE},
			{"idn", CURL_VERSION_IDN},
			{"ipv6", CURL_VERSION_IPV6},
			{"largefile", CURL_VERSION_LARGEFILE},
			{"ntlm", CURL_VERSION_NTLM},
			{"spnego", CURL_VERSION_SPNEGO},
			{"ssl",  CURL_VERSION_SSL},
			{"sspi",  CURL_VERSION_SSPI},
			{"krb4", CURL_VERSION_KERBEROS4},
			{"libz", CURL_VERSION_LIBZ},
			{"charconv", CURL_VERSION_CONV}
		};
		for( unsigned int i=0; i<sizeof(feats)/sizeof(feats[0]); i++ )
			if( curlinfo->features & feats[i].bitmask )
				g_string_append_printf(features, ",%s", feats[i].name);

	}
	if( curlinfo->protocols )
		for( const char * const *proto=curlinfo->protocols; *proto; ++proto )
			g_string_append_printf(protocols, ",%s", *proto);

	g_info("curl version %s features:%s protocols:%s ", curlinfo->version, features->str+1, protocols->str+1);
	g_string_free(features, TRUE);
	g_string_free(protocols, TRUE);

	curl_runtime.multi = curl_multi_init();
	ev_timer_init(&curl_runtime.timer_event, timer_cb, 0., 0.);
	curl_multi_setopt(curl_runtime.multi, CURLMOPT_SOCKETFUNCTION, curl_socketfunction_cb);
	curl_multi_setopt(curl_runtime.multi, CURLMOPT_SOCKETDATA, NULL);
	curl_multi_setopt(curl_runtime.multi, CURLMOPT_TIMERFUNCTION, multi_timer_cb);
	curl_multi_setopt(curl_runtime.multi, CURLMOPT_TIMERDATA, NULL);
	CURLMcode rc;
	do
	{
		rc = curl_multi_socket_all(curl_runtime.multi, &curl_runtime.active);
	} while( CURLM_CALL_MULTI_PERFORM == rc );

	curl_runtime.download_ihandler = ihandler_new("dionaea.download.offer", curl_ihandler_cb, NULL);
	curl_runtime.upload_ihandler = ihandler_new("dionaea.upload.request", curl_ihandler_cb, NULL);
	return true;
}
Example #12
0
static gboolean
handle_kill_sessions (CockpitAccount *object,
                      GDBusMethodInvocation *invocation)
{
    Account *acc = ACCOUNT (object);
    GError *error = NULL;

    if (!auth_check_sender_role (invocation, COCKPIT_ROLE_USER_ADMIN))
        return TRUE;

    if (acc->u)
    {
        gs_unref_object GDBusConnection *bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM,
                                               NULL,
                                               &error);
        if (bus == NULL)
            goto out;

        GVariant *result =
            g_dbus_connection_call_sync (bus,
                                         "org.freedesktop.login1",
                                         "/org/freedesktop/login1",
                                         "org.freedesktop.login1.Manager",
                                         "KillUser",
                                         g_variant_new ("(ui)",
                                                 act_user_get_uid (acc->u),
                                                 SIGTERM),
                                         NULL,
                                         0,
                                         -1,
                                         NULL,
                                         &error);

        if (!error)
        {
            g_variant_unref (result);
        }
        else
        {
            /* logind from systemd 208 is buggy, so we use systemd directly if it fails
               https://bugs.freedesktop.org/show_bug.cgi?id=71092
             */
            g_dbus_error_strip_remote_error (error);
            g_warning ("logind.KillUser failed (%s), trying systemd.KillUnit", error->message);
            g_clear_error (&error);
            gs_free gchar *unit = g_strdup_printf ("user-%d.slice", act_user_get_uid (acc->u));
            GVariant *result =
                g_dbus_connection_call_sync (bus,
                                             "org.freedesktop.systemd1",
                                             "/org/freedesktop/systemd1",
                                             "org.freedesktop.systemd1.Manager",
                                             "KillUnit",
                                             g_variant_new ("(ssi)",
                                                     unit,
                                                     "all",
                                                     SIGTERM),
                                             NULL,
                                             0,
                                             -1,
                                             NULL,
                                             &error);
            if (!error)
            {
                g_info ("systemd.KillUnit worked");
                g_variant_unref (result);
            }
        }
    }

out:
    if (error)
    {
        g_dbus_method_invocation_return_error (invocation,
                                               COCKPIT_ERROR, COCKPIT_ERROR_FAILED,
                                               "Failed to kill sessions: %s", error->message);
        g_error_free (error);
    }
    else
        cockpit_account_complete_kill_sessions (object, invocation);

    return TRUE;
}
Example #13
0
void    scr_do( void )
{
    ifcb    *   cb = input_cbs->if_cb;
    condcode    cc;
    char        linestr[MAX_L_AS_STR];

    scan_err = false;
    garginit();                         // find end of control word
    cc = getarg();

    cb->if_flags[cb->if_level].ifcwdo = false;
    if( cc == omit || !strnicmp( tok_start, "begin", 5 )) {

        if( !(cb->if_flags[cb->if_level].ifthen
              || cb->if_flags[cb->if_level].ifelse)
            || cb->if_flags[cb->if_level].ifdo ) {

            scan_err = true;
            g_err( err_if_do );
            if( input_cbs->fmflags & II_macro ) {
                ultoa( input_cbs->s.m->lineno, linestr, 10 );
                g_info( inf_mac_line, linestr, input_cbs->s.m->mac->name );
            } else {
                ultoa( input_cbs->s.f->lineno, linestr, 10 );
                g_info( inf_file_line, linestr, input_cbs->s.f->filename );
            }
            show_ifcb( "dobegin", cb );
            show_include_stack();
            err_count++;
            return;
        }
        cb->if_flags[cb->if_level].ifdo = true;
        if( input_cbs->fmflags & II_research && GlobalFlags.firstpass ) {
            show_ifcb( "dobegin", cb );
        }
        scan_restart = scan_stop + 1;
        return;
    } else {
        if( !strnicmp( tok_start, "end", 3 )) {
            if( input_cbs->fmflags & II_research && GlobalFlags.firstpass ) {
                show_ifcb( "doend", cb );
            }
            do {                            // loop for last active .do begin

                if( cb->if_flags[cb->if_level].ifdo ) {

                    cb->if_flags[cb->if_level].ifdo = false;
                    if( input_cbs->fmflags & II_research &&
                        GlobalFlags.firstpass ) {
                        show_ifcb( "doend", cb );
                    }
                    scan_restart = scan_stop + 1;
                    return;
                }
                if( cb->if_flags[cb->if_level].ifthen
                    || cb->if_flags[cb->if_level].ifelse
                    || !(cb->if_flags[cb->if_level].iftrue
                         || cb->if_flags[cb->if_level].iffalse) ) {

                    scan_err = true;
                    g_err( err_if_do_end );
                    if( input_cbs->fmflags & II_macro ) {
                        ultoa( input_cbs->s.m->lineno, linestr, 10 );
                        g_info( inf_mac_line, linestr, input_cbs->s.m->mac->name );
                    } else {
                        ultoa( input_cbs->s.f->lineno, linestr, 10 );
                        g_info( inf_file_line, linestr, input_cbs->s.f->filename );
                    }
                    show_ifcb( "doend", cb );
                    show_include_stack();
                    err_count++;
                    return;
                }

            } while( cb->if_level-- > 0 );
#if 0
            if( input_cbs->fmflags & II_research && GlobalFlags.firstpass ) {
                out_msg( "\t.do end Level %d\n"
                         "\t.ifcb iftrue %d, iffalse %d\n",
                         cb->if_level,
                         cb->if_flags[cb->if_level].iftrue,
                         cb->if_flags[cb->if_level].iffalse );
            }
#endif
        } else {
            scan_err = true;
            g_err( err_if_do_fun );
            if( input_cbs->fmflags & II_macro ) {
                ultoa( input_cbs->s.m->lineno, linestr, 10 );
                g_info( inf_mac_line, linestr, input_cbs->s.m->mac->name );
            } else {
                ultoa( input_cbs->s.f->lineno, linestr, 10 );
                g_info( inf_file_line, linestr, input_cbs->s.f->filename );
            }
            show_include_stack();
            err_count++;
            return;
        }
    }
    if( input_cbs->fmflags & II_research && GlobalFlags.firstpass ) {
        show_ifcb( "do xx", cb );
    }
    scan_restart = scan_stop + 1;
    return;
}
Example #14
0
void    scr_if( void )
{
    ifcb            *   cb;             // if stack ptr

    condcode        cct1;
    condcode        cct2;
    condcode        ccrelop;
    termcb          t1;                 // first argument
    termcb          t2;                 // second argument
    relop           relation;           // the relation between t1 and t2
    logop           logical;            // if more than 1 condition
    bool            ifcond;             // current condition
    bool            totalcondition;     // resultant condition
    bool            firstcondition;     // first comparison .if
    char            linestr[MAX_L_AS_STR];

    scan_err = false;

    firstcondition = true;              // first 2 terms to compare
    garginit();                         // find end of control word

    cb = input_cbs->if_cb;              // get .if control block
    cb->if_flags[cb->if_level].ifcwif = false;  // reset cwif switch

    for( ;; ) {                         // evaluate if conditions

        cct1    = gargterm( &t1 );      // get term 1
        ccrelop = gargrelop( &relation );   // get relation operator
        cct2    = gargterm( &t2 );      // get term 2

        if( (cct1 == no) || (cct2 == no) ) {
            scan_err = true;
            err_count++;
            g_err( err_if_term );
            if( input_cbs->fmflags & II_macro ) {
                ultoa( input_cbs->s.m->lineno, linestr, 10 );
                g_info( inf_mac_line, linestr, input_cbs->s.m->mac->name );
            } else {
                ultoa( input_cbs->s.f->lineno, linestr, 10 );
                g_info( inf_file_line, linestr, input_cbs->s.f->filename );
            }
            show_include_stack();
            return;
        }
        if( ccrelop != pos ) {
            scan_err = true;
            err_count++;
            g_err( err_if_relop );
            if( input_cbs->fmflags & II_macro ) {
                ultoa( input_cbs->s.m->lineno, linestr, 10 );
                g_info( inf_mac_line, linestr, input_cbs->s.m->mac->name );
            } else {
                ultoa( input_cbs->s.f->lineno, linestr, 10 );
                g_info( inf_file_line, linestr, input_cbs->s.f->filename );
            }
            show_include_stack();
            return;
        }

        // terms and operator ok now compare
        ifcond = ifcompare( &t1, relation, &t2 );
        mem_free( t1.term_string );     // don't need the strings anymore
        mem_free( t2.term_string );
        if( firstcondition ) {
            firstcondition = false;
            if( cb->if_level < MAX_IF_LEVEL ) {
                cb->if_level++;
                memset( &cb->if_flags[cb->if_level], '\0',
                        sizeof( cb->if_flags[cb->if_level] ) );
                cb->if_flags[cb->if_level].iflast = true;
                cb->if_flags[cb->if_level].ifcwte = false;  // no .th .el yet
                cb->if_flags[cb->if_level].iftrue = false;  // cond not yet true
                cb->if_flags[cb->if_level].iffalse = false; // cond not yet false
            } else {
                scan_err = true;
                g_err( err_if_nesting );
                if( input_cbs->fmflags & II_macro ) {
                    ultoa( input_cbs->s.m->lineno, linestr, 10 );
                    g_info( inf_mac_line, linestr, input_cbs->s.m->mac->name );
                } else {
                    ultoa( input_cbs->s.f->lineno, linestr, 10 );
                    g_info( inf_file_line, linestr, input_cbs->s.f->filename );
                }
                show_include_stack();
                err_count++;
                return;
            }
            totalcondition = ifcond;
        } else {
            // resultant condition
            if( logical == AND ) {
                totalcondition &= ifcond;
            } else {
                totalcondition |= ifcond;
            }
        }

        if( totalcondition ) {          // set if true / false flags
            cb->if_flags[cb->if_level].iftrue = true;
            cb->if_flags[cb->if_level].iffalse = false;
        } else {
            cb->if_flags[cb->if_level].iffalse = true;
            cb->if_flags[cb->if_level].iftrue = false;
        }

        while( *scan_start == ' ' ) {
            scan_start++;
        }

/*
 * test logical condition if not line end
 *         .if a = b or c GT d
 *                   ^^
 */
        if( *scan_start ) {
            if( *scan_start == SCR_char ) {
                break;                  // .xx can't be logical operator
            }
            if( *(scan_start + 1) == ' ' ) {// single char + blank
                if( *scan_start  == '&' ) {
                    logical = AND;
                    scan_start += 2;
                    continue;           // do next conditions
                } else if( *scan_start == '|' ) {
                    logical = OR;
                    scan_start += 2;
                    continue;           // do next conditions
                }
            } else {
                if( !strnicmp( scan_start, "and ", 4 ) ) {
                    logical = AND;
                    scan_start += 4;
                    continue;           // do next conditions
                } else if( !strnicmp( scan_start, "or ", 3 ) ) {
                        logical = OR;
                        scan_start += 3;
                        continue;       // do next conditions
                }
            }

        }
        break;                          // no more operators / conditions
    }


    if( cb->if_level > 1 ) {            // nested if
        if( cb->if_flags[cb->if_level - 1].ifthen ) { // object of .th
            if( cb->if_flags[cb->if_level - 1].iffalse ) {// last .if false

                cb->if_flags[cb->if_level].iftrue = true;// process nothing
                cb->if_flags[cb->if_level].iffalse = true;
            }
        } else {
            if( cb->if_flags[cb->if_level - 1].ifelse // object of .el
                && cb->if_flags[cb->if_level - 1].iftrue ) {// last .if true

                cb->if_flags[cb->if_level].iftrue = true;// process nothing
                cb->if_flags[cb->if_level].iffalse = true;
            }
        }
    }
    if( input_cbs->fmflags & II_research && GlobalFlags.firstpass ) {
          show_ifcb( "if", cb );
#if 0
          out_msg( "\t.if is %s Level %d\n"
                 "\t.ifcb iftrue %d, iffalse %d\n",
                 totalcondition ? "true " : "false",
                 cb->if_level,
                 cb->if_flags[cb->if_level].iftrue,
                 cb->if_flags[cb->if_level].iffalse );
#endif
    }

    if( *scan_start ) {                 // rest of line is not empty
        split_input(  buff2, scan_start, false );   // split and process next
    }
    scan_restart = scan_stop + 1;
    return;
}
Example #15
0
gboolean
ToolsCore_LoadPlugins(ToolsServiceState *state)
{
   gboolean pluginDirExists;
   gboolean ret = FALSE;
   gchar *pluginRoot;
   guint i;
   GPtrArray *plugins = NULL;

#if defined(sun) && defined(__x86_64__)
   const char *subdir = "/amd64";
#else
   const char *subdir = "";
#endif

#if defined(OPEN_VM_TOOLS)
   pluginRoot = g_strdup(VMTOOLSD_PLUGIN_ROOT);
#else
   char *instPath = GuestApp_GetInstallPath();
   pluginRoot = g_strdup_printf("%s%cplugins", instPath, DIRSEPC);
   vm_free(instPath);
#endif

   ASSERT(g_module_supported());

#ifdef USE_APPLOADER
   {
      Bool ret = FALSE;
      GModule *mainModule = g_module_open(NULL, G_MODULE_BIND_LAZY);
      ASSERT(mainModule);

      ret = g_module_symbol(mainModule, "AppLoader_LoadLibraryDependencies",
                            (gpointer *)&LoadDependencies);
      g_module_close(mainModule);

      if (!ret) {
         g_critical("Unable to locate library dependency loading function.\n");
         goto exit;
      }
   }
#endif

   plugins = g_ptr_array_new();

   /*
    * First, load plugins from the common directory. The common directory
    * is not required to exist unless provided on the command line.
    */
   if (state->commonPath == NULL) {
      state->commonPath = g_strdup_printf("%s%s%c%s",
                                          pluginRoot,
                                          subdir,
                                          DIRSEPC,
                                          TOOLSCORE_COMMON);
   } else if (!g_file_test(state->commonPath, G_FILE_TEST_IS_DIR)) {
      g_warning("Common plugin path is not a directory: %s\n", state->commonPath);
      goto exit;
   }

   if (g_file_test(state->commonPath, G_FILE_TEST_IS_DIR) &&
       !ToolsCoreLoadDirectory(&state->ctx, state->commonPath, plugins)) {
      goto exit;
   }

   /*
    * Load the container-specific plugins. Ignore if the plugin directory
    * doesn't exist when running in debug mode.
    */

   if (state->pluginPath == NULL) {
      state->pluginPath = g_strdup_printf("%s%s%c%s",
                                          pluginRoot,
                                          subdir,
                                          DIRSEPC,
                                          state->name);
   }

   pluginDirExists = g_file_test(state->pluginPath, G_FILE_TEST_IS_DIR);
   if (state->debugPlugin == NULL && !pluginDirExists) {
      g_warning("Plugin path is not a directory: %s\n", state->pluginPath);
      goto exit;
   }

   if (pluginDirExists &&
       !ToolsCoreLoadDirectory(&state->ctx, state->pluginPath, plugins)) {
      goto exit;
   }


   /*
    * All plugins are loaded, now initialize them.
    */

   state->plugins = g_ptr_array_new();

   for (i = 0; i < plugins->len; i++) {
      ToolsPlugin *plugin = g_ptr_array_index(plugins, i);

      plugin->data = plugin->onload(&state->ctx);

      if (plugin->data == NULL) {
         g_info("Plugin '%s' didn't provide deployment data, unloading.\n",
                plugin->fileName);
         ToolsCoreFreePlugin(plugin);
      } else if (state->ctx.errorCode != 0) {
         /* Break early if a plugin has requested the container to quit. */
         ToolsCoreFreePlugin(plugin);
         break;
      } else {
         ASSERT(plugin->data->name != NULL);
         g_module_make_resident(plugin->module);
         g_ptr_array_add(state->plugins, plugin);
         VMTools_BindTextDomain(plugin->data->name, NULL, NULL);
         g_message("Plugin '%s' initialized.\n", plugin->data->name);
      }
   }


   /*
    * If there is a debug plugin, see if it exports standard plugin registration
    * data too.
    */
   if (state->debugData != NULL && state->debugData->debugPlugin->plugin != NULL) {
      ToolsPluginData *data = state->debugData->debugPlugin->plugin;
      ToolsPlugin *plugin = g_malloc(sizeof *plugin);
      plugin->fileName = NULL;
      plugin->module = NULL;
      plugin->data = data;
      VMTools_BindTextDomain(data->name, NULL, NULL);
      g_ptr_array_add(state->plugins, plugin);
   }

   ret = TRUE;

exit:
   if (plugins != NULL) {
      g_ptr_array_free(plugins, TRUE);
   }
   g_free(pluginRoot);
   return ret;
}
Example #16
0
static gboolean
ToolsCoreLoadDirectory(ToolsAppCtx *ctx,
                       const gchar *pluginPath,
                       GPtrArray *regs)
{
   gboolean ret = FALSE;
   const gchar *staticEntry;
   guint i;
   GDir *dir = NULL;
   GError *err = NULL;
   GPtrArray *plugins;

   dir = g_dir_open(pluginPath, 0, &err);
   if (dir == NULL) {
      g_warning("Error opening dir: %s\n", err->message);
      goto exit;
   }

   plugins = g_ptr_array_new();

   /*
    * Load plugins in alphabetical order, so the load order is the same
    * regardless of how the filesystem returns entries.
    */
   while ((staticEntry = g_dir_read_name(dir)) != NULL) {
      if (g_str_has_suffix(staticEntry, "." G_MODULE_SUFFIX)) {
         g_ptr_array_add(plugins, g_strdup(staticEntry));
      }
   }

   g_dir_close(dir);

   g_ptr_array_sort(plugins, ToolsCoreStrPtrCompare);

   for (i = 0; i < plugins->len; i++) {
      gchar *entry;
      gchar *path;
      GModule *module = NULL;
      ToolsPlugin *plugin = NULL;
      ToolsPluginOnLoad onload;

      entry = g_ptr_array_index(plugins, i);
      path = g_strdup_printf("%s%c%s", pluginPath, DIRSEPC, entry);

      if (!g_file_test(path, G_FILE_TEST_IS_REGULAR)) {
         g_warning("File '%s' is not a regular file, skipping.\n", entry);
         goto next;
      }

#ifdef USE_APPLOADER
      /* Trying loading the plugins with system libraries */
      if (!LoadDependencies(path, FALSE)) {
         g_warning("Loading of library dependencies for %s failed.\n", entry);
         goto next;
      }
#endif

      module = g_module_open(path, G_MODULE_BIND_LOCAL);
#ifdef USE_APPLOADER
      if (module == NULL) {
         g_info("Opening plugin '%s' with system libraries failed: %s\n",
                   entry, g_module_error());
         /* Falling back to the shipped libraries */
         if (!LoadDependencies(path, TRUE)) {
            g_warning("Loading of shipped library dependencies for %s failed.\n",
                     entry);
            goto next;
         }
         module = g_module_open(path, G_MODULE_BIND_LOCAL);
      }
#endif
      if (module == NULL) {
         g_warning("Opening plugin '%s' failed: %s.\n", entry, g_module_error());
         goto next;
      }

      if (!g_module_symbol(module, "ToolsOnLoad", (gpointer *) &onload)) {
         g_warning("Lookup of plugin entry point for '%s' failed.\n", entry);
         goto next;
      }

      plugin = g_malloc(sizeof *plugin);
      plugin->fileName = entry;
      plugin->data = NULL;
      plugin->module = module;
      plugin->onload = onload;
      g_ptr_array_add(regs, plugin);

   next:
      g_free(path);
      if (plugin == NULL && module != NULL) {
         if (!g_module_close(module)) {
            g_warning("Error unloading plugin '%s': %s\n", entry, g_module_error());
         }
      }
   }

   g_ptr_array_free(plugins, TRUE);
   ret = TRUE;

exit:
   return ret;
}
Example #17
0
static void onLowMemory(ANativeActivity* activity) {
    struct android_app* android_app = (struct android_app*)activity->instance;
    g_info("LowMemory: %p\n", activity);
    //android_app_write_cmd(android_app, APP_CMD_LOW_MEMORY);
}
Example #18
0
void histo_destroy_walk(gpointer data, gpointer user_data)
{
  g_info("Walk destroy GUI Histogram Control Flow Viewer");
  guihistocontrolflow_destructor_full((HistoControlFlowData*)data);
}
Example #19
0
static void onNativeWindowRedrawNeeded(ANativeActivity* activity, ANativeWindow* window) {
    g_info("NativeWindowRedrawNeeded: %p -- %p\n", activity, window);
    //android_app_wait_redraw((struct android_app*)activity->instance);
}
Example #20
0
G_GNUC_COLD void
map_test(void)
{
	sha1_t *keys;
	map_t *mh, *mp;
	int i;
	size_t count;
	int tests;
	struct {
		unsigned insertion, contains, removal;
	} faster = { 0, 0, 0};
	bool verbose = common_stats > 1;

	if (common_stats <= 0)
		return;

	XMALLOC_ARRAY(keys, ITEM_COUNT);

	for (i = 0; i < ITEM_COUNT; i++)
		random_bytes(keys[i].data, SHA1_RAW_SIZE);

	mh = map_create_hash(sha1_hash, sha1_eq);
	mp = map_create_patricia(KEYBITS);

	timeit(test_map_insert, mh, keys, ITEM_COUNT,
		LOOPS, "map hash insertion", verbose);

	timeit(test_map_insert, mp, keys, ITEM_COUNT,
		LOOPS, "map PATRICIA insertion", verbose);

	map_destroy(mh);
	map_destroy(mp);

	for (tests = 0, count = ITEM_COUNT; count > 1; count /= 10) {
		double htime;
		double ptime;

		tests++;

		mh = map_create_hash(sha1_hash, sha1_eq);
		mp = map_create_patricia(KEYBITS);

		htime = timeit(test_map_insert, mh, keys, count,
			1, "map hash reloading", verbose);

		ptime = timeit(test_map_insert, mp, keys, count,
			1, "map PATRICIA reloading", verbose);

		if (verbose)
			g_info("PATRICIA insertion %s than hash with %zu items",
				ptime < htime ? "faster" : "slower", count);

		if (ptime < htime)
			faster.insertion++;

		htime = timeit(test_map_contains, mh, keys, count,
			LOOPS, "map hash contains", verbose);

		ptime = timeit(test_map_contains, mp, keys, count,
			LOOPS, "map PATRICIA contains", verbose);

		if (verbose)
			g_info("PATRICIA contains %s than hash with %zu items",
				ptime < htime ? "faster" : "slower", count);

		if (ptime < htime)
			faster.contains++;

		htime = timeit(test_map_remove, mh, keys, count,
			1, "map hash remove", verbose);

		ptime = timeit(test_map_remove, mp, keys, count,
			1, "map PATRICIA remove", verbose);

		if (verbose)
			g_info("PATRICIA remove %s than hash with %zu items",
				ptime < htime ? "faster" : "slower", count);

		if (ptime < htime)
			faster.removal++;

		map_destroy(mh);
		map_destroy(mp);
	}

	if (faster.insertion)
		g_info("PATRICIA insert was faster than hash in %d out of %d tests",
			faster.insertion, tests);
	if (faster.contains)
		g_info(
			"PATRICIA contains was faster than hash in %d out of %d tests",
			faster.contains, tests);
	if (faster.removal)
		g_info("PATRICIA remove was faster than hash in %d out of %d tests",
			faster.removal, tests);

	XFREE_NULL(keys);
}
Example #21
0
/**
 *  Set up pcap listener for the given interfaces and protocols.
 *  @return a properly configured pcap_t* object for listening for the given protocols - NULL on error
 *  @see pcap_protocols
 */
pcap_t*
create_pcap_listener(const char * dev		///<[in] Device name to listen on
,		     gboolean blocking		///<[in] TRUE if this is a blocking connection
,		     unsigned listenmask	///<[in] Bit mask of protocols to listen for
						///< (see @ref pcap_protocols "list of valid bits")
,		     struct bpf_program*prog)	///<[out] Compiled PCAP program
{
	pcap_t*			pcdescr = NULL;
	bpf_u_int32		maskp = 0;
	bpf_u_int32		netp = 0;
	char			errbuf[PCAP_ERRBUF_SIZE];
	char *			expr = NULL;
	int			filterlen = 1;
	unsigned		j;
	int			cnt=0;
	int			rc;
	const char ORWORD [] = " or ";
	gboolean		need_promisc = FALSE;

	BINDDEBUG(pcap_t);
//	setbuf(stdout, NULL);
	setvbuf(stdout, NULL, _IONBF, 0);
	errbuf[0] = '\0';

	// Search the list of valid bits so we can construct the libpcap filter
	// for the given set of protocols on the fly...
	// On this pass we just compute the amount of memory we'll need...
	for (j = 0, cnt = 0; j < DIMOF(filterinfo); ++j) {
		if (listenmask & filterinfo[j].filterbit) {
			++cnt;
			if (cnt > 1) {
				filterlen += sizeof(ORWORD);
			}
			filterlen += strlen(filterinfo[j].filter);
		}
	}
	
	if (filterlen < 2) {
		g_warning("Constructed filter is too short - invalid mask argument.");
		return NULL;
	}
	if (NULL == (expr = malloc(filterlen))) {
		g_error("Out of memory!");
		return NULL;
	}
	// Same song, different verse...
	// This time around, we construct the filter
	expr[0] = '\0';
	for (j = 0, cnt = 0; j < DIMOF(filterinfo); ++j) {
		if (listenmask & filterinfo[j].filterbit) {
			++cnt;
			if (cnt > 1) {
				g_strlcat(expr, ORWORD, filterlen);
			}
			g_strlcat(expr, filterinfo[j].filter, filterlen);
		}
	}
	if (pcap_lookupnet(dev, &netp, &maskp, errbuf) != 0) {
		// This is not a problem for non-IPv4 protocols...
		// It just looks up the ipv4 address - which we mostly don't care about.
		g_info("%s.%d: pcap_lookupnet(\"%s\") failed: [%s]"
		,	__FUNCTION__, __LINE__, dev, errbuf);
	}
	
	if (NULL == (pcdescr = pcap_create(dev, errbuf))) {
		g_warning("pcap_create failed: [%s]", errbuf);
		goto oopsie;
	}
	//pcap_set_promisc(pcdescr, FALSE);
	for (j = 0; j < DIMOF(filterinfo); ++j) {
		if (listenmask & filterinfo[j].filterbit) {
			const char * addrstring = filterinfo[j].mcastaddr;
			if (addrstring && !_enable_mcast_address(addrstring, dev, TRUE)) {
				need_promisc = TRUE;
			}
		}
	}
	pcap_set_promisc(pcdescr, need_promisc);
#ifdef HAVE_PCAP_SET_RFMON
	pcap_set_rfmon(pcdescr, FALSE);
#endif
	pcap_setdirection(pcdescr, PCAP_D_IN);
	// Weird bug - returns -3 and doesn't show an error message...
	// And pcap_getnonblock also returns -3... Neither should happen AFAIK...
	errbuf[0] = '\0';
	if ((rc = pcap_setnonblock(pcdescr, !blocking, errbuf)) < 0 && errbuf[0] != '\0') {
		g_warning("pcap_setnonblock(%d) failed: [%s] [rc=%d]", !blocking, errbuf, rc);
		g_warning("Have no idea why this happens - current blocking state is: %d."
		,	pcap_getnonblock(pcdescr, errbuf));
	}
	pcap_set_snaplen(pcdescr, 1500);
	/// @todo deal with pcap_set_timeout() call here.
	if (blocking) {
		pcap_set_timeout(pcdescr, 240*1000);
	}else{
		pcap_set_timeout(pcdescr, 1);
	}
	//pcap_set_buffer_size(pcdescr, 1500);
      
	if (pcap_activate(pcdescr) != 0) {
		g_warning("pcap_activate failed: [%s]", pcap_geterr(pcdescr));
		goto oopsie;
	}
	if (pcap_compile(pcdescr, prog, expr, FALSE, maskp) < 0) {
		g_warning("pcap_compile of [%s] failed: [%s]", expr, pcap_geterr(pcdescr));
		goto oopsie;
	}
	if (pcap_setfilter(pcdescr, prog) < 0) {
		g_warning("pcap_setfilter on [%s] failed: [%s]", expr, pcap_geterr(pcdescr));
		goto oopsie;
	}
	DEBUGMSG1("Compile of [%s] worked!", expr);
	g_info("Compile of [%s] worked! Returning %p", expr, pcdescr);
	free(expr); expr = NULL;
	return(pcdescr);

oopsie:	// Some kind of failure - free things up and return NULL

	g_warning("%s.%d: Could not set up PCAP on %s"
	,	__FUNCTION__, __LINE__, dev);
	if (expr) {
		free(expr);
		expr = NULL;
	}
	if (pcdescr) {
		close_pcap_listener(pcdescr, dev, listenmask);
		pcdescr = NULL;
	}
	return NULL;
}
Example #22
0
condcode    scr_substr( parm parms[MAX_FUN_PARMS], size_t parmcount, char * * result, int32_t ressize )
{
    char            *   pval;
    char            *   pend;
    condcode            cc;
    int                 k;
    int                 n;
    int                 stringlen;
    int                 len;
    getnum_block        gn;
    char                padchar;
    char                linestr[MAX_L_AS_STR];

    if( (parmcount < 2) || (parmcount > 4) ) {
        return( neg );
    }

    pval = parms[0].a;
    pend = parms[0].e;

    unquote_if_quoted( &pval, &pend );

    stringlen = pend - pval + 1;        // length of string
    padchar = ' ';                      // default padchar
    len = 0;

    n = 0;                              // default start pos
    gn.ignore_blanks = false;

    if( parmcount > 1 ) {               // evalute start pos
        if( parms[1].e >= parms[1].a ) {// start pos specified
            gn.argstart = parms[1].a;
            gn.argstop  = parms[1].e;
            cc = getnum( &gn );
            if( (cc != pos) || (gn.result == 0) ) {
                if( !ProcFlags.suppress_msg ) {
                    g_err( err_func_parm, "2 (startpos)" );
                    if( input_cbs->fmflags & II_macro ) {
                        ultoa( input_cbs->s.m->lineno, linestr, 10 );
                        g_info( inf_mac_line, linestr, input_cbs->s.m->mac->name );
                    } else {
                        ultoa( input_cbs->s.f->lineno, linestr, 10 );
                        g_info( inf_file_line, linestr, input_cbs->s.f->filename );
                    }
                    err_count++;
                    show_include_stack();
                }
                return( cc );
            }
            n = gn.result - 1;
        }
    }

    if( parmcount > 2 ) {               // evalute length
        if( parms[2].e >= parms[2].a ) {// length specified
            gn.argstart = parms[2].a;
            gn.argstop  = parms[2].e;
            cc = getnum( &gn );
            if( (cc != pos) || (gn.result == 0) ) {
                if( !ProcFlags.suppress_msg ) {
                    g_err( err_func_parm, "3 (length)" );
                    if( input_cbs->fmflags & II_macro ) {
                        ultoa( input_cbs->s.m->lineno, linestr, 10 );
                        g_info( inf_mac_line, linestr, input_cbs->s.m->mac->name );
                    } else {
                        ultoa( input_cbs->s.f->lineno, linestr, 10 );
                        g_info( inf_file_line, linestr, input_cbs->s.f->filename );
                    }
                    err_count++;
                    show_include_stack();
                }
                return( cc );
            }
            len = gn.result;
        }
    }

    if( parmcount > 3 ) {               // isolate padchar
        if( parms[3].e >= parms[3].a ) {
            char *  pa = parms[3].a;
            char *  pe = parms[3].e;

            unquote_if_quoted( &pa, &pe );
            padchar = *pa;
        }
    }

    pval += n;                          // position to startpos
    if( len == 0 ) {                    // no length specified
        len = pend - pval + 1;          // take rest of string
        if( len < 0 ) {                 // if there is one
            len = 0;
        }
    }
    for( k = 0; k < len; k++ ) {
        if( (pval > pend) || (ressize <= 0) ) {
            break;
        }
        **result = *pval++;
        *result += 1;
        ressize--;
    }
    for( ; k < len; k++ ) {
        if( ressize <= 0 ) {
            break;
        }
        **result = padchar;
        *result += 1;
        ressize--;
    }

    **result = '\0';

    return( pos );
}
Example #23
0
void gmpv_mpv_initialize(GmpvMpv *mpv)
{
	GSettings *main_settings = g_settings_new(CONFIG_ROOT);
	gchar *config_dir = get_config_dir_path();
	gchar *mpvopt = NULL;
	gchar *current_vo = NULL;
	gchar *mpv_version = NULL;

	const struct
	{
		const gchar *name;
		const gchar *value;
	}
	options[] = {	{"osd-level", "1"},
			{"softvol", "yes"},
			{"force-window", "yes"},
			{"input-default-bindings", "yes"},
			{"audio-client-name", ICON_NAME},
			{"title", "${media-title}"},
			{"autofit-larger", "75%"},
			{"window-scale", "1"},
			{"pause", "no"},
			{"ytdl", "yes"},
			{"osd-bar", "no"},
			{"input-cursor", "no"},
			{"cursor-autohide", "no"},
			{"softvol-max", "100"},
			{"config", "yes"},
			{"screenshot-template", "gnome-mpv-shot%n"},
			{"config-dir", config_dir},
			{NULL, NULL} };

	g_assert(mpv->mpv_ctx);

	for(gint i = 0; options[i].name; i++)
	{
		g_debug(	"Applying default option --%s=%s",
				options[i].name,
				options[i].value );

		mpv_set_option_string(	mpv->mpv_ctx,
					options[i].name,
					options[i].value );
	}

	if(g_settings_get_boolean(main_settings, "mpv-config-enable"))
	{
		gchar *mpv_conf
			= g_settings_get_string
				(main_settings, "mpv-config-file");

		g_info("Loading config file: %s", mpv_conf);
		mpv_load_config_file(mpv->mpv_ctx, mpv_conf);

		g_free(mpv_conf);
	}

	if(g_settings_get_boolean(main_settings, "mpv-input-config-enable"))
	{
		gchar *input_conf
			= g_settings_get_string
				(main_settings, "mpv-input-config-file");

		g_info("Loading input config file: %s", input_conf);
		load_input_conf(mpv, input_conf);

		g_free(input_conf);
	}
	else
	{
		load_input_conf(mpv, NULL);
	}

	mpvopt = g_settings_get_string(main_settings, "mpv-options");

	g_debug("Applying extra mpv options: %s", mpvopt);

	/* Apply extra options */
	if(apply_args(mpv->mpv_ctx, mpvopt) < 0)
	{
		const gchar *msg
			= _("Failed to apply one or more MPV options.");

		g_signal_emit_by_name(mpv, "mpv-error", msg);
	}

	if(mpv->force_opengl || mpv->wid <= 0)
	{
		g_info("Forcing --vo=opengl-cb");
		mpv_set_option_string(mpv->mpv_ctx, "vo", "opengl-cb");

	}
	else
	{
		g_debug(	"Attaching mpv window to wid %#x",
				(guint)mpv->wid );

		mpv_set_option(mpv->mpv_ctx, "wid", MPV_FORMAT_INT64, &mpv->wid);
	}

	mpv_observe_property(mpv->mpv_ctx, 0, "aid", MPV_FORMAT_INT64);
	mpv_observe_property(mpv->mpv_ctx, 0, "chapters", MPV_FORMAT_INT64);
	mpv_observe_property(mpv->mpv_ctx, 0, "core-idle", MPV_FORMAT_FLAG);
	mpv_observe_property(mpv->mpv_ctx, 0, "fullscreen", MPV_FORMAT_FLAG);
	mpv_observe_property(mpv->mpv_ctx, 0, "pause", MPV_FORMAT_FLAG);
	mpv_observe_property(mpv->mpv_ctx, 0, "length", MPV_FORMAT_DOUBLE);
	mpv_observe_property(mpv->mpv_ctx, 0, "media-title", MPV_FORMAT_STRING);
	mpv_observe_property(mpv->mpv_ctx, 0, "playlist-pos", MPV_FORMAT_INT64);
	mpv_observe_property(mpv->mpv_ctx, 0, "track-list", MPV_FORMAT_NODE);
	mpv_observe_property(mpv->mpv_ctx, 0, "volume", MPV_FORMAT_DOUBLE);
	mpv_set_wakeup_callback(mpv->mpv_ctx, wakeup_callback, mpv);
	mpv_check_error(mpv_initialize(mpv->mpv_ctx));


	mpv_version = gmpv_mpv_get_property_string(mpv, "mpv-version");
	current_vo = gmpv_mpv_get_property_string(mpv, "current-vo");

	g_info("Using %s", mpv_version);

	if(current_vo && !GDK_IS_X11_DISPLAY(gdk_display_get_default()))
	{
		g_info(	"The chosen vo is %s but the display is not X11; "
			"forcing --vo=opengl-cb and resetting",
			current_vo );

		mpv->force_opengl = TRUE;
		mpv->state.paused = FALSE;

		gmpv_mpv_reset(mpv);
	}
	else
	{
		GSettings *win_settings;
		gdouble volume;

		win_settings = g_settings_new(CONFIG_WIN_STATE);
		volume = g_settings_get_double(win_settings, "volume")*100;

		g_debug("Setting volume to %f", volume);
		mpv_set_property(	mpv->mpv_ctx,
					"volume",
					MPV_FORMAT_DOUBLE,
					&volume );

		/* The vo should be opengl-cb if current_vo is NULL*/
		if(!current_vo)
		{
			mpv->opengl_ctx =	mpv_get_sub_api
						(	mpv->mpv_ctx,
							MPV_SUB_API_OPENGL_CB );
		}

		gmpv_mpv_opt_handle_msg_level(mpv);
		gmpv_mpv_opt_handle_fs(mpv);
		gmpv_mpv_opt_handle_geometry(mpv);

		mpv->force_opengl = FALSE;
		mpv->state.ready = TRUE;
		g_signal_emit_by_name(mpv, "mpv-init");

		g_clear_object(&win_settings);
	}

	g_clear_object(&main_settings);
	g_free(config_dir);
	g_free(mpvopt);
	mpv_free(current_vo);
	mpv_free(mpv_version);
}
Example #24
0
void    gml_hdref( const gmltag * entry )
{
    char    *   p;
    char    *   pa;
    char    *   pe;
    char    *   idp;
    char        quote;
    char        c;
    bool        idseen;
    bool        pageseen;
    bool        withpage;
    size_t      len;
    char        buf64[64];
    ref_entry   *   re;
    static char undefid[] = "\"Undefined Heading\" on page XXX";


    idseen = false;
    pageseen = false;
    withpage = false;
    p = scan_start;
    re = NULL;

    /***********************************************************************/
    /*  Scan attributes  for :HDREF                                        */
    /*  id=                                                                */
    /*  page=                                                              */
    /***********************************************************************/

    for( ;; ) {
        while( *p == ' ' ) {
            p++;
        }
        if( *p == '\0' || *p == '.'  ) {
            break;                      // tag end found
        }

        if( !strnicmp( "page=", p, 5 ) ) {
            p += 5;
            while( *p == ' ' ) {
                p++;
            }
            pa = p;
            if( !strnicmp( "yes", p, 3 ) ) {
                pageseen = true;
                withpage = true;
                p += 3;
            } else {
                if( !strnicmp( "no", p, 2 ) ) {
                    pageseen = true;
                    withpage = false;
                    p += 2;
                } else {
                   g_err( err_inv_att_val );
                   file_mac_info();
                   err_count++;
                   while( *p && (*p != '.') && (*p != ' ') ) p++;
                }
            }
            scan_start = p;
            continue;
        }

        if( !strnicmp( "refid=", p, 6 ) ) {
            p += 6;
            while( *p == ' ' ) {
                p++;
            }
            if( is_quote_char( *p ) ) {
                quote = *p;
                p++;
            } else {
                quote = '\0';
            }
            pa = p;
            while( *p && is_id_char( *p ) ) {
                p++;
            }
            len = __min( ID_LEN, p - pa );// restrict length as in ghx.c

            if( len > 0 ) {
                idseen = true;          // valid id attribute found
                pe = pa + len;
                c = *pe;
                *pe = '\0';
                re = find_refid( ref_dict, strlwr( pa ) );
                if( re != NULL ) {      // id found in ref dict
                    idp = mem_alloc( 4 + strlen( re->text_cap ) );
                    *idp = '"';         // decorate with quotes
                    strcpy( idp + 1, re->text_cap );
                    strcat( idp, "\"" );
                } else {
                    if( GlobalFlags.lastpass ) {
                        g_warn( wng_id_xxx, pa );
                        g_info( inf_id_unknown );
                        file_mac_info();
                        wng_count++;
                    }
                }
                *pe = c;
            }
            if( *p && (quote == *p) ) {
                p++;
            }

            scan_start = p;
            continue;
        }

        /*******************************************************************/
        /* no more valid attributes                                        */
        /*******************************************************************/
        break;
    }
    if( *p == '.' ) {                   // tag end ?
        p++;
    }
    if( idseen ) {                      // id attribute was specified
        bool concatsave = ProcFlags.concat;

        ProcFlags.concat = true;        // make process_text add to line
        if( re == NULL ) {              // undefined refid
            process_text( undefid, g_curr_font_num );
        } else {
            process_text( idp, g_curr_font_num );
            if( withpage || (!pageseen && (page != re->pageno)) ) {
                sprintf_s( buf64, sizeof( buf64 ), "on page %d", re->pageno );
                process_text( buf64, g_curr_font_num );
            }
            mem_free( idp );
        }
        ProcFlags.concat = concatsave;
    } else {
        g_err( err_att_missing );       // id attribute missing
        file_mac_info();
        err_count++;
    }

    scan_start = p;
    return;
}
Example #25
0
void emulate_thread(gpointer data, gpointer user_data)
{
	struct emu_emulate_ctx *ctx = user_data;
	struct emu_config *conf = ctx->config;
	struct emu *e = ctx->emu;
	struct emu_env *env = ctx->env;
	int ret;

	g_mutex_lock(&ctx->mutex);

	if( ctx->state == waiting )
		ctx->state = running;


	if( ctx->time == NULL )
		ctx->time = g_timer_new();
	else
		g_timer_continue(ctx->time);

	while( ctx->state == running )
	{
		if( (ctx->steps % (1024*1024)) == 0 )
		{
			g_debug("steps %li", ctx->steps);
			if( ctx->steps > conf->limits.steps )
			{
				g_info("shellcode took too many steps ... (%li steps)",  ctx->steps);
				ctx->state = failed;
				break;
			}
			if( conf->limits.cpu > 0. )
			{
				double elapsed = g_timer_elapsed(ctx->time, NULL);
				if( elapsed > conf->limits.cpu )
				{
					g_info("shellcode took too long ... (%f seconds)",  elapsed);
					ctx->state = failed;
					break;
				}
			}
		}
		ctx->steps++;
		struct emu_env_hook *hook = NULL;
		hook = emu_env_w32_eip_check(env);

		if( hook != NULL )
		{
			if( hook->hook.win->fnhook == NULL )
			{
				g_critical("unhooked call to %s", hook->hook.win->fnname);
				break;
			} else
				if( ctx->state == waiting )
				/* for now, we stop!
				 * had a blocking io call
				 * callback from main will come at a given point
				 * and requeue us to the threadpool
				 */
				goto unlock_and_return;
		} else
		{
			ret = emu_cpu_parse(emu_cpu_get(e));
			struct emu_env_hook *hook =NULL;
			if( ret != -1 )
			{
				hook = emu_env_linux_syscall_check(env);
				if( hook == NULL )
				{
					ret = emu_cpu_step(emu_cpu_get(e));
				} else
				{
					if( hook->hook.lin->fnhook != NULL )
					{
						hook->hook.lin->fnhook(env, hook);
						if( ctx->state == waiting )
							/* stop 
							 * as mentioned previously
							 */
							goto unlock_and_return;
					}
				}
			}

			if( ret == -1 )
			{
				g_debug("cpu error %s", emu_strerror(e));
				break;
			}
		}
	}

	g_timer_stop(ctx->time);

	if( ctx->state == failed )
		g_debug("emulating shellcode failed");

	g_mutex_unlock(&ctx->mutex);

#ifdef DEBUG
	double elapsed = g_timer_elapsed(ctx->time, NULL);
	g_debug("shellcode took %f seconds on cpu, %li steps", elapsed, ctx->steps);
#endif

	GAsyncQueue *aq = g_async_queue_ref(g_dionaea->threads->cmds);
	g_async_queue_push(aq, async_cmd_new(emulate_ctx_free, ctx));
	g_async_queue_unref(aq);
	ev_async_send(g_dionaea->loop, &g_dionaea->threads->trigger);
	return;


	unlock_and_return:
	g_timer_stop(ctx->time);
	g_mutex_unlock(&ctx->mutex);
}
Example #26
0
condcode    scr_index( parm parms[MAX_FUN_PARMS], size_t parmcount, char * * result, int32_t ressize )
{
    char            *   pneedle;
    char            *   pneedlend;
    char            *   phay;
    char            *   phayend;
    condcode            cc;
    int                 index;
    int                 n;
    int                 hay_len;
    int                 needle_len;
    getnum_block        gn;
    char            *   ph;
    char            *   pn;
    char                linestr[MAX_L_AS_STR];

    if( (parmcount < 2) || (parmcount > 3) ) {
        cc = neg;
        return( cc );
    }

    phay = parms[0].a;
    phayend = parms[0].e;

    unquote_if_quoted( &phay, &phayend );
    hay_len = phayend - phay + 1;       // haystack length

    pneedle = parms[1].a;
    pneedlend = parms[1].e;

    unquote_if_quoted( &pneedle, &pneedlend );
    needle_len = pneedlend - pneedle + 1;   // needle length

    n   = 0;                            // default start pos
    gn.ignore_blanks = false;

    if( parmcount > 2 ) {               // evalute start pos
        if( parms[2].e >= parms[2].a ) {// start pos specified
            gn.argstart = parms[2].a;
            gn.argstop  = parms[2].e;
            cc = getnum( &gn );
            if( (cc != pos) || (gn.result == 0) ) {
                if( !ProcFlags.suppress_msg ) {
                    g_err( err_func_parm, "3 (startpos)" );
                    if( input_cbs->fmflags & II_macro ) {
                        utoa( input_cbs->s.m->lineno, linestr, 10 );
                        g_info( inf_mac_line, linestr, input_cbs->s.m->mac->name );
                    } else {
                        utoa( input_cbs->s.f->lineno, linestr, 10 );
                        g_info( inf_file_line, linestr, input_cbs->s.f->filename );
                    }
                    err_count++;
                    show_include_stack();
                }
                return( cc );
            }
            n = gn.result - 1;
        }
    }

    if( (hay_len <= 0) ||               // null string nothing to do
        (needle_len <= 0) ||            // needle null nothing to do
        (needle_len > hay_len) ||       // needle longer haystack
        (n + needle_len > hay_len) ) {  // startpos + needlelen > haystack
                                        // ... match impossible

        **result = '0';                 // return index zero
        *result += 1;
        **result = '\0';
        return( pos );
    }

    ph = phay + n;                      // startpos in haystack
    pn = pneedle;
    index = 0;

    for( ph = phay + n; ph <= phayend - needle_len + 1; ph++ ) {
        pn = pneedle;
        while( (*ph == *pn) && (pn <= pneedlend)) {
            ph++;
            pn++;
        }
        if( pn > pneedlend ) {
            index = ph - phay - needle_len + 1; // found, set index
            break;
        }
    }

    *result += sprintf( *result, "%d", index );

    return( pos );
}
Example #27
0
File: main.c Project: Legun/cockpit
int
main (int argc,
      char *argv[])
{
  gint ret = 1;
  CockpitWebServer *server = NULL;
  GOptionContext *context;
  CockpitHandlerData data;
  GTlsCertificate *certificate = NULL;
  GError *local_error = NULL;
  GError **error = &local_error;
  gchar **roots = NULL;
  gchar *cert_path = NULL;
  GMainLoop *loop;

  signal (SIGPIPE, SIG_IGN);
  g_setenv ("GSETTINGS_BACKEND", "memory", TRUE);
  g_setenv ("GIO_USE_PROXY_RESOLVER", "dummy", TRUE);
  g_setenv ("GIO_USE_VFS", "local", TRUE);

  /* Any interaction with a krb5 ccache should be explicit */
  g_setenv ("KRB5CCNAME", "FILE:/dev/null", TRUE);

  g_type_init ();
  ssh_init ();

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

  context = g_option_context_new (NULL);
  g_option_context_add_main_entries (context, cmd_entries, NULL);

  if (!g_option_context_parse (context, &argc, &argv, error))
    {
      goto out;
    }

  cockpit_set_journal_logging (!isatty (2));

  if (opt_no_tls)
    {
      /* no certificate */
    }
  else
    {
      cert_path = cockpit_certificate_locate (FALSE, error);
      if (cert_path != NULL)
        certificate = cockpit_certificate_load (cert_path, error);
      if (certificate == NULL)
        goto out;
      g_info ("Using certificate: %s", cert_path);
    }

  if (opt_uninstalled)
    {
      roots = cockpit_web_server_resolve_roots (SRCDIR "/src/static", SRCDIR "/lib", NULL);
      cockpit_ws_bridge_program = BUILDDIR "/cockpit-bridge";
      cockpit_ws_session_program = BUILDDIR "/cockpit-session";
    }
  else
    {
      roots = cockpit_web_server_resolve_roots (DATADIR "/cockpit/static", NULL);
    }

  data.auth = cockpit_auth_new ();
  data.static_roots = (const gchar **)roots;

  server = cockpit_web_server_new (opt_port,
                                   certificate,
                                   NULL,
                                   NULL,
                                   error);
  if (server == NULL)
    {
      g_prefix_error (error, "Error starting web server: ");
      goto out;
    }

  /* Ignores stuff it shouldn't handle */
  g_signal_connect (server,
                    "handle-stream",
                    G_CALLBACK (cockpit_handler_socket),
                    &data);

  g_signal_connect (server,
                    "handle-resource::/login",
                    G_CALLBACK (cockpit_handler_login),
                    &data);

  /* Don't redirect to TLS for /ping */
  g_object_set (server, "ssl-exception-prefix", "/ping", NULL);
  g_signal_connect (server, "handle-resource::/ping",
                    G_CALLBACK (cockpit_handler_ping), &data);

  g_signal_connect (server,
                    "handle-resource::/",
                    G_CALLBACK (cockpit_handler_index),
                    &data);

  g_signal_connect (server, "handle-resource::/static/",
                    G_CALLBACK (cockpit_handler_static), &data);
  g_signal_connect (server, "handle-resource::/cockpit/",
                    G_CALLBACK (cockpit_handler_resource), &data);

  /* Files that cannot be cache-forever, because of well known names */
  g_signal_connect (server, "handle-resource::/favicon.ico",
                    G_CALLBACK (cockpit_handler_root), &data);
  g_signal_connect (server, "handle-resource::/apple-touch-icon.png",
                    G_CALLBACK (cockpit_handler_root), &data);

  g_info ("HTTP Server listening on port %d", opt_port);

  loop = g_main_loop_new (NULL, FALSE);
  g_main_loop_run (loop);
  g_main_loop_unref (loop);

  ret = 0;

out:
  if (local_error)
    {
      g_printerr ("cockpit-ws: %s\n", local_error->message);
      g_error_free (local_error);
    }
  g_clear_object (&server);
  g_clear_object (&data.auth);
  g_clear_object (&certificate);
  g_free (cert_path);
  g_strfreev (roots);
  return ret;
}
Example #28
0
int
main (int argc,
      char **argv)
{
  GError *error;
  GOptionContext *opt_context;
  GIOChannel *channel;
  guint name_owner_id = 0;
  gint ret;

  ret = 1;
  loop = NULL;
  opt_context = NULL;

  #if !GLIB_CHECK_VERSION(2,36,0)
  g_type_init ();
  #endif

  /* See glib/gio/gsocket.c */
  signal (SIGPIPE, SIG_IGN);

  /* avoid gvfs and gsettings: https://bugzilla.gnome.org/show_bug.cgi?id=767183 */
  g_assert (g_setenv ("GIO_USE_VFS", "local", TRUE));
  g_assert (g_setenv ("GSETTINGS_BACKEND", "memory", TRUE));

  opt_context = g_option_context_new ("rpm-ostreed -- rpm-ostree daemon");
  g_option_context_add_main_entries (opt_context, opt_entries, NULL);
  error = NULL;
  if (!g_option_context_parse (opt_context, &argc, &argv, &error))
    {
      g_printerr ("Error parsing options: %s\n", error->message);
      g_error_free (error);
      goto out;
    }

  if (opt_debug)
    {
      g_log_set_handler (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG | G_LOG_LEVEL_INFO, on_log_debug, NULL);
      g_log_set_always_fatal (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING);

      /* When in debug mode (often testing) we exit when stdin closes */
      channel = g_io_channel_unix_new (0);
      g_io_add_watch (channel, G_IO_HUP, on_stdin_close, NULL);
      g_io_channel_unref (channel);
    }
  else
    {
      /* When not in debug mode, send all logging to syslog */
      g_log_set_default_handler (on_log_handler, NULL);
    }

  g_info ("rpm-ostreed starting");

  loop = g_main_loop_new (NULL, FALSE);

  g_unix_signal_add (SIGINT, on_sigint, NULL);
  g_unix_signal_add (SIGTERM, on_sigint, NULL);

  if (service_dbus_fd == -1)
    {
      GBusType bus_type;

      /* To facilitate testing, use whichever message bus activated
       * this process.  If the process was started directly, assume
       * the system bus. */
      if (g_getenv ("DBUS_STARTER_BUS_TYPE") != NULL)
        bus_type = G_BUS_TYPE_STARTER;
      else if (g_getenv ("RPMOSTREE_USE_SESSION_BUS") != NULL)
        bus_type = G_BUS_TYPE_SESSION;
      else
        bus_type = G_BUS_TYPE_SYSTEM;

      name_owner_id = g_bus_own_name (bus_type,
                                      DBUS_NAME,
                                      G_BUS_NAME_OWNER_FLAGS_NONE,
                                      on_bus_acquired,
                                      on_name_acquired,
                                      on_name_lost,
                                      NULL, (GDestroyNotify) NULL);
    }
  else if (!connect_to_peer (service_dbus_fd))
    {
      ret = 1;
      goto out;
    }

  g_debug ("Entering main event loop");

  g_main_loop_run (loop);

  if (name_owner_id > 0)
    {
      g_bus_unown_name (name_owner_id);
      name_owner_id = 0;
    }

  g_clear_object (&rpm_ostree_daemon);

  ret = 0;

out:
  if (loop != NULL)
    g_main_loop_unref (loop);

  if (opt_context != NULL)
    g_option_context_free (opt_context);

  g_info ("rpm-ostreed exiting");

  return ret;
}
Example #29
0
int
main (int argc,
      char *argv[])
{
  gint ret = 1;
  CockpitWebServer *server = NULL;
  GOptionContext *context;
  CockpitHandlerData data;
  GError *local_error = NULL;
  GError **error = &local_error;
  GMainLoop *loop;

  g_type_init ();

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

  context = g_option_context_new (NULL);
  g_option_context_add_main_entries (context, cmd_entries, NULL);

  if (!g_option_context_parse (context, &argc, &argv, error))
    {
      goto out;
    }

  if (!opt_debug)
    cockpit_set_journal_logging ();

  if (opt_http_root == NULL)
    opt_http_root = g_strdup (PACKAGE_DATA_DIR "/cockpit/content");

  if (opt_no_tls)
    {
      /* no certificate */
    }
  else
    {
      if (!load_cert (&data.certificate, error))
        goto out;
    }

  if (!opt_disable_auth)
    data.auth = cockpit_auth_new ();

  data.system_bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, error);
  if (data.system_bus == NULL)
    {
      g_prefix_error (error, "Error getting system bus: ");
      goto out;
    }

  server = cockpit_web_server_new (opt_port,
                                   data.certificate,
                                   opt_http_root,
                                   NULL,
                                   error);
  if (server == NULL)
    {
      g_prefix_error (error, "Error starting web server: ");
      goto out;
    }

  /* Ignores stuff it shouldn't handle */
  g_signal_connect (server,
                    "handle-resource",
                    G_CALLBACK (cockpit_handler_socket),
                    &data);

  g_signal_connect (server,
                    "handle-resource::/login",
                    G_CALLBACK (cockpit_handler_login),
                    &data);
  g_signal_connect (server,
                    "handle-resource::/logout",
                    G_CALLBACK (cockpit_handler_logout),
                    &data);

  g_signal_connect (server,
                    "handle-resource::/cockpitdyn.js",
                    G_CALLBACK (cockpit_handler_cockpitdyn),
                    &data);

  g_info ("HTTP Server listening on port %d", opt_port);

  loop = g_main_loop_new (NULL, FALSE);
  g_main_loop_run (loop);
  g_main_loop_unref (loop);

  ret = 0;

out:
  g_free (opt_http_root);
  if (local_error)
    {
      g_printerr ("%s (%s, %d)\n", local_error->message, g_quark_to_string (local_error->domain), local_error->code);
      g_error_free (local_error);
    }
  g_clear_object (&server);
  g_clear_object (&data.auth);
  g_clear_object (&data.system_bus);
  g_clear_object (&data.certificate);
  return ret;
}
Example #30
0
/**
 * Initialize version string.
 */
void G_COLD
version_init(void)
{
	time_t now;

	version_string = ostrdup_readonly(version_build_string());
	now = tm_time();

	{
		bool ok;
		const char *end;

		ok = version_parse(version_string, &our_version, &end);
		g_assert(ok);
		ok = version_ext_parse(end, &our_ext_version);
		g_assert(ok);
	}

	g_info("%s", version_string);

	version_stamp(version_string, &our_version);
	g_assert(our_version.timestamp != 0);

	{
		char buf[128];

		str_bprintf(buf, sizeof(buf),
			"%s/%s%s (%s)",
			product_name(), product_version(),
			product_build_full(), product_date());

		version_short_string = ostrdup_readonly(buf);
	}

	last_rel_version = our_version;			/* struct copy */
	last_dev_version = our_version;			/* struct copy */
	our_ext_version.version = our_version;	/* struct copy */

	/*
	 * The version code is a one-byte encoding of the year/month, since
	 * what matters is not much the version number as to the age of the
	 * servent...  The version code is transmitted in pongs via GGEP "VC".
	 */

	if (our_version.timestamp) {
		struct tm *tmp = localtime(&our_version.timestamp);
		version_code =
			(((tmp->tm_year + 1900 - 2000) & 0x0f) << 4) | (tmp->tm_mon + 1);
	} else
		version_code = 0;

	/*
	 * The property system is not up when this is called, but we need
	 * to set this variable correctly.
	 */

	if (
		tok_is_ancient(now) ||
		delta_time(now, our_version.timestamp) > VERSION_ANCIENT_WARN
	) {
		*deconstify_bool(&GNET_PROPERTY(ancient_version)) = TRUE;
	}
}