Exemplo n.º 1
0
/* static */
string FontUtils::BestFonts(const unordered_map<char32, inT64>& ch_map,
                            vector<pair<const char*, vector<bool> > >* fonts) {
  const double kMinOKFraction = 0.99;
  // Weighted fraction of characters that must be renderable in a font to make
  // it OK even if the raw count is not good.
  const double kMinWeightedFraction = 0.99995;

  fonts->clear();
  vector<vector<bool> > font_flags;
  vector<int> font_scores;
  vector<int> raw_scores;
  int most_ok_chars = 0;
  int best_raw_score = 0;
  const vector<string>& font_names = FontUtils::ListAvailableFonts();
  for (int i = 0; i < font_names.size(); ++i) {
    vector<bool> ch_flags;
    int raw_score = 0;
    int ok_chars = FontScore(ch_map, font_names[i], &raw_score, &ch_flags);
    most_ok_chars = MAX(ok_chars, most_ok_chars);
    best_raw_score = MAX(raw_score, best_raw_score);

    font_flags.push_back(ch_flags);
    font_scores.push_back(ok_chars);
    raw_scores.push_back(raw_score);
  }

  // Now select the fonts with a score above a threshold fraction
  // of both the raw and weighted best scores. To prevent bogus fonts being
  // selected for CJK, we require a high fraction (kMinOKFraction = 0.99) of
  // BOTH weighted and raw scores.
  // In low character-count scripts, the issue is more getting enough fonts,
  // when only 1 or 2 might have all those rare dingbats etc in them, so we
  // allow a font with a very high weighted (coverage) score
  // (kMinWeightedFraction = 0.99995) to be used even if its raw score is poor.
  int least_good_enough = static_cast<int>(most_ok_chars * kMinOKFraction);
  int least_raw_enough = static_cast<int>(best_raw_score * kMinOKFraction);
  int override_enough = static_cast<int>(most_ok_chars * kMinWeightedFraction);

  string font_list;
  for (int i = 0; i < font_names.size(); ++i) {
    int score = font_scores[i];
    int raw_score = raw_scores[i];
    if ((score >= least_good_enough && raw_score >= least_raw_enough) ||
        score >= override_enough) {
      fonts->push_back(make_pair(font_names[i].c_str(), font_flags[i]));
      tlog(1, "OK font %s = %.4f%%, raw = %d = %.2f%%\n",
           font_names[i].c_str(),
           100.0 * score / most_ok_chars,
           raw_score, 100.0 * raw_score / best_raw_score);
      font_list += font_names[i];
      font_list += "\n";
    } else if (score >= least_good_enough || raw_score >= least_raw_enough) {
      tlog(1, "Runner-up font %s = %.4f%%, raw = %d = %.2f%%\n",
           font_names[i].c_str(),
           100.0 * score / most_ok_chars,
           raw_score, 100.0 * raw_score / best_raw_score);
    }
  }
  return font_list;
}
Exemplo n.º 2
0
/* Pickup on activity and process it.  Processing may mean a number of things:
 *  - to try an accept() on a server socket (ignoring it upon EAGAIN)
 *  - to trigger a thread that is hoping writing after EAGAIN
 *  - to read a message and further process it
 */
void process_activity (int sox, int soxidx, struct soxinfo *soxi, short int revents) {
	if (revents & POLLOUT) {
		//TODO// signal waiting thread that it may continue
		tlog (TLOG_UNIXSOCK, LOG_CRIT, "Eekk!!  Could send a packet?!?  Unregistering client");
		unregister_client_socket_byindex (soxidx);
		close (sox);
	}
	if (revents & POLLIN) {
		if (soxi->flags & SOF_SERVER) {
			struct sockaddr sa;
			socklen_t salen = sizeof (sa);
			int newsox = accept (sox, &sa, &salen);
			if (newsox != -1) {
				tlog (TLOG_UNIXSOCK, LOG_NOTICE, "Received incoming connection.  Registering it");
				register_client_socket (newsox);
			}
		}
		if (soxi->flags & SOF_CLIENT) {
			struct command *cmd = allocate_command_for_clientfd (sox);
			if (receive_command (sox, cmd)) {
				process_command (cmd);
			} else {
				tlog (TLOG_UNIXSOCK, LOG_ERR, "Failed to receive command request");
			}
		}
	}
}
Exemplo n.º 3
0
/* Receive a command.  Return nonzero on success, zero on failure. */
int receive_command (int sox, struct command *cmd) {
	int newfd;
	char anc [CMSG_SPACE (sizeof (int))];
	struct iovec iov;
	struct msghdr mh = { 0 };
	struct cmsghdr *cmsg;

	iov.iov_base = &cmd->cmd;
	iov.iov_len = sizeof (cmd->cmd);
	mh.msg_iov = &iov;
	mh.msg_iovlen = 1;
	mh.msg_control = anc;
	mh.msg_controllen = sizeof (anc);

	cmd->passfd = -1;
	if (recvmsg (sox, &mh, 0) == -1) {
		//TODO// Differentiate behaviour based on errno?
		perror ("Failed to receive command");
		return 0;
	}
	tlog (TLOG_UNIXSOCK, LOG_DEBUG, "Received command request code 0x%08x with cbid=%d over fd=%d", cmd->cmd.pio_cmd, cmd->cmd.pio_cbid, sox);

	cmsg = CMSG_FIRSTHDR (&mh);
	if (cmsg && (cmsg->cmsg_len == CMSG_LEN (sizeof (int)))) {
		if ((cmsg->cmsg_level == SOL_SOCKET) && (cmsg->cmsg_type == SCM_RIGHTS)) {
			cmd->passfd = * (int *) CMSG_DATA (cmsg);
			tlog (TLOG_UNIXSOCK, LOG_DEBUG, "Received file descriptor as %d", cmd->passfd);
		}
	}

	return 1;
}
Exemplo n.º 4
0
/**
    @brief
    Function Resolve the hostname to ip
*/
bool turbotrace::resolve_host(wxString host)
{
    //Get hostname as a char pointer
    char *target = strdup( (char*) host.ToAscii().data());

    log( _("Will now resolve : ") + wxString(target , wxConvUTF8) );

    //Is it just a simple IP
	if( inet_addr( target ) != INADDR_NONE)
	{
		dest_ip.s_addr = inet_addr( target );
		tlog(_("Valid IP provided"));
	}
	//Domain name , resolve it
	else
	{
		char *ip = iputils::hostname_to_ip( (char*) target );

		if(ip != NULL)
		{
			tlog( wxString(target , wxConvUTF8) + _(" resolved to ") + wxString(ip , wxConvUTF8));

			//Convert domain name to IP
			dest_ip.s_addr = inet_addr( ip );
		}
		else
		{
			tlog( _("Unable to resolve hostname : ") + wxString(target , wxConvUTF8) );
			return false;
		}
	}
	return true;
}
Exemplo n.º 5
0
Arquivo: main.c Projeto: jnow-87/foo
/* global functions */
int main(int argc, char **argv){
	int log;
	unsigned int passed, failed;
	test_case_t *tc;


	/* init */
	passed = 0;
	failed = 0;

	if(argc != 2){
		printf("usage: %s <log-file>\n", argv[0]);
		return 1;
	}

	log = open(argv[1], O_CREAT | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);

	if(log < 0){
		printf("open log-file \"%s\" failed \"%s\"\n", argv[1], strerror(errno));
		return 1;
	}

	/* iterate through test cases */
	tc = __start_testcases;

	while(tc != __stop_testcases){
		printf("run test case: %s... ", tc->desc);
		tlog(log, " === test case: %s ===\n\n", tc->desc);


		if((tc->hdlr)(log) == 0){
			printf(FG_GREEN "passed\n" RESET_ATTR);
			tlog(log, "\n === test case: %s passed ===\n\n\n", tc->desc);

			passed++;
		}
		else{
			printf(FG_RED "failed\n" RESET_ATTR);
			tlog(log, "\n === test case: %s failed ===\n\n\n", tc->desc);

			failed++;
		}

		tc++;
	}

	/* summary */
	printf(FG_VIOLETT "\nsummary" RESET_ATTR " (cf. %s)\n"
		   FG_VIOLETT "    total:" RESET_ATTR " %u\n"
		   FG_GREEN "    passed:" RESET_ATTR " %u\n"
		   FG_RED "    failed:" RESET_ATTR " %u\n\n"
		   ,
		   argv[1],
		   passed + failed,
		   passed,
		   failed
	);

	return 0;
}
Exemplo n.º 6
0
/* Desire a callback and in the process of doing so, send a callback response.
 * This must be called from another thread than the main TLS pool thread.
 *
 * The code below and the signaling post_callback call claim the cbfree_mutex
 * as a condition to protect (keep atomic) the conditioning and signaling.
 * The condition awaited for which the callback's condition presents a hint
 * is the setting of the followup pointer in the callback structure, which
 * links in the command that responds to the callback placed.
 */
struct command *send_callback_and_await_response (struct command *cmdresp) {
	struct callback *cb;
	struct command *followup;
	pthread_mutex_lock (&cbfree_mutex);
	cb = cbfree;
	if (!cb) {
		//TODO// Allocate more...
		tlog (TLOG_UNIXSOCK, LOG_CRIT, "Ran out of callback structures.  Crashing as a coward");
		exit (1);
	}
	//TODO// It's simpler to administer index numbers and not pointers
	cbfree = cb->next;
	cmdresp->cmd.pio_cbid = 1 + (((intptr_t) cb) - ((intptr_t) cblist)) / ((intptr_t) sizeof (struct callback));
	cb->fd = cmdresp->clientfd;
	cb->followup = NULL;
	cb->next = NULL; //TODO// Enqueue in fd-queue
	send_command (cmdresp, -1);
	do {
		//TODO// pthread_cond_timedwait?
		tlog (TLOG_UNIXSOCK, LOG_DEBUG, "Waiting with fd=%d and cbid=%d on semaphone 0x%08x", cb->fd, cmdresp->cmd.pio_cbid, cb);
		pthread_cond_wait (&cb->semaphore, &cbfree_mutex);
		followup = cb->followup;
	} while (!followup);
	//TODO// Remove cb from the fd's cblist
	cb->next = cbfree;
	cbfree = cb;
	pthread_mutex_unlock (&cbfree_mutex);
	return followup;
}
Exemplo n.º 7
0
 void run(int){
     tlog("run() invoked. this="<<this);
     ThreadBase::sleep(1000);
     while (true) {
         tlog("["<<id<<"] is alive");
         ThreadBase::sleep(800);
     }
 }
Exemplo n.º 8
0
 void consume(int sleep){
     tlog("Started to consume");
     while (active){
         int obj;
         if (mainQueue->timedPop(obj, 50000)){
             tlog("Consuming: "<<obj);
         }else{
             tlog("Nothing to consume!");
         }
         ThreadBase::sleep(sleep);
     }
 }
Exemplo n.º 9
0
 void produce(int sleep){
     tlog("Started to produce");
     int prod = nextNum();
     while (active){
         if (mainQueue->timedPush(prod, 50000)){
             prod++;
             tlog("Produced: "<<prod);
         } else {
             tlog("Full. Can't produce!");
         }
         ThreadBase::sleep(sleep);
     }
 }
Exemplo n.º 10
0
    bool tearDownWorld(){
      tlog("\n\n" );
      tlog("//==========================================================\n" );
      tlog("//                       -=[ Log end ]=-                    \n" );
      tlog("//==========================================================\n" );

#if defined (N_LOG_FILE)
      fclose(log_stream());
#endif
      log_stream()=stdout;
      
      return true;
    }
Exemplo n.º 11
0
/* Allocate the structures for handling a sequence of expressions
 * to be combined with AND.  Expand the structure into a series of
 * cases.  Do not start the computations yet, but prepare them.
 * The sequence of expressions is considered a NULL-terminated
 * array of NUL-terminated strings.
 *
 * This routine returns NULL in case of error, and will log the
 * expression that caused the failure.  In case of success, an
 * expanded expression is returned, that should be cleaned up
 * with free() as soon as it is ready.
 */
static struct valexp *allocate_valexp (char **and_expressions) {
	int allcases = 1;
	char **andexp;
	struct valexp *retval = NULL;
	int memsz;
	//
	// Count the individual expressions' sizes, and compute the total
	for (andexp=and_expressions; (*andexp) != NULL; andexp++) {
		int explen = strlen (*andexp);
		int parsed;
		int newcases = count_cases (*andexp, explen, 0, &parsed);
		if ((newcases == -1) || (parsed != explen)) {
			//TODO// Expression will not be the same anymore
			tlog (TLOG_USER, LOG_NOTICE, "Syntax error in logic expression, treat as False: %s", *andexp);
			return NULL;
		}
		allcases = allcases * newcases;
	}
	//
	// Allocate memory for the overal expression
	// Since all cases are initialised to all-zeroes, they represent
	// TRUE in all these cases.  Expansion should add restrictions.
	memsz = sizeof (struct valexp) + sizeof (struct valexp_case) * (allcases - 1);
	retval = (struct valexp *) malloc (memsz);
	if (retval == NULL) {
		//TODO// Expression will not be the same anymore
		tlog (TLOG_TLS, LOG_NOTICE, "Out of memory expanding logic expressions");
		return NULL;
	}
	memset (retval, 0, memsz);
	retval->numcases = allcases;
	retval->numcases_incomplete = allcases;
	//
	// Expand the expressions to the form (OR (AND ... ~...) (AND ...) ...)
	// This relies on:
	//  - De Morgan to fold inversion inward
	//  - Distribution laws for AND / OR
	//  - Rewriting of ? to a combination and AND / OR
	//  - No cases as the zero element of OR to represent FALSE
	//  - A complete case to represent TRUE
	// Note that the and_expressions are pushed into each' OR caselist
	// Note that all cases are initialised AND-ready (they're all TRUE)
	for (andexp=and_expressions; *andexp != NULL; andexp++) {
		//TODO// EXPAND_EXPRESSION_INTO_EXISTING_WITH_AND
	}
	//
	// Return successfully.
	return retval;
}
Exemplo n.º 12
0
int main(){
    ThreadPool<Counter, int>* pool = ThreadPool<Counter, int>::createThreadPool(2,2);
    Counter c;
    pool->start();
    tlog("Pool started!");
    for (int i=0; i<5; i++){
        pool->execute(&c, &Counter::run, i);
        tlog("done executing #"<<i);
    }
    
    ThreadBase::sleep(3000);
    
    tlog("Destroying Pool");
    delete pool;
}
Exemplo n.º 13
0
 ~ProdCons(){
     active = false;
     tlog("Destroying ...");
     for (std::vector<Thread<ProdCons, int>*>::iterator it=producers.begin();
                 it != producers.end(); it++){
         delete *it;
         tlog("Kill one producer");
     }
     for (std::vector<Thread<ProdCons, int>*>::iterator it=consumers.begin();
                 it != consumers.end(); it++){
         delete *it;
         tlog("Kill one consumer");
     }
     delete mainQueue;
 }
Exemplo n.º 14
0
int PangoFontInfo::DropUncoveredChars(string* utf8_text) const {
  PangoFont* font = ToPangoFont();
  PangoCoverage* coverage = pango_font_get_coverage(font, NULL);
  int num_dropped_chars = 0;
  // Maintain two iterators that point into the string. For space efficiency, we
  // will repeatedly copy one covered UTF8 character from one to the other, and
  // at the end resize the string to the right length.
  char* out = const_cast<char*>(utf8_text->c_str());
  const UNICHAR::const_iterator it_begin =
      UNICHAR::begin(utf8_text->c_str(), utf8_text->length());
  const UNICHAR::const_iterator it_end =
      UNICHAR::end(utf8_text->c_str(), utf8_text->length());
  for (UNICHAR::const_iterator it = it_begin; it != it_end; ++it) {
    // Skip bad utf-8.
    if (!it.is_legal())
      continue;  // One suitable error message will still be issued.
    if (!IsWhitespace(*it) && !pango_is_zero_width(*it) &&
        pango_coverage_get(coverage, *it) != PANGO_COVERAGE_EXACT) {
      if (TLOG_IS_ON(2)) {
        char tmp[5];
        int len = it.get_utf8(tmp);
        tmp[len] = '\0';
        tlog(2, "'%s' (U+%x) not covered by font\n", tmp, *it);
      }
      ++num_dropped_chars;
      continue;
    }
    strncpy(out, it.utf8_data(), it.utf8_len());
    out += it.utf8_len();
  }
  utf8_text->resize(out - utf8_text->c_str());
  return num_dropped_chars;
}
Exemplo n.º 15
0
static struct command *allocate_command_for_clientfd (int fd) {
	static int cmdpool_pos = 0;
	int pos;
	struct command *cmd;
	if (!cmdpool) {
		cmdpool = (struct command *) calloc (1000, sizeof (struct command));
		if (!cmdpool) {
			tlog (TLOG_UNIXSOCK, LOG_CRIT, "Failed to allocate command pool");
			exit (1);
		}
		bzero (cmdpool, 1000 * sizeof (struct command));
	}
	pos = cmdpool_pos;
	while (cmdpool [pos].claimed) {
		pos++;
		if (pos >= cmdpool_len) {
			cmdpool = 0;
		}
		if (pos == cmdpool_pos) {
			/* A full rotation -- delay of 10ms */
			usleep (10000);
		}
	}
	cmdpool [pos].clientfd = fd;
	cmdpool [pos].handler = pthread_self ();	// Not fit for cancel
	cmdpool [pos].claimed = 1;
	return &cmdpool [pos];
}
Exemplo n.º 16
0
/* Process a command packet that entered on a TLS pool socket
 */
static void process_command (struct command *cmd) {
	tlog (TLOG_UNIXSOCK, LOG_DEBUG, "Processing command 0x%08x", cmd->cmd.pio_cmd);
	union pio_data *d = &cmd->cmd.pio_data;
	if (is_callback (cmd)) {
		post_callback (cmd);
		return;
	}
	switch (cmd->cmd.pio_cmd) {
	case PIOC_PING_V1:
		strcpy (d->pioc_ping.YYYYMMDD_producer, TLSPOOL_IDENTITY_V1);
		send_command (cmd, -1);
		return;
	case PIOC_STARTTLS_CLIENT_V1:
		starttls_client (cmd);
		return;
	case PIOC_STARTTLS_SERVER_V1:
		starttls_server (cmd);
		return;
	case PIOC_PINENTRY_V1:
		register_pinentry_command (cmd);
		return;
	default:
		send_error (cmd, ENOSYS, "Command not implemented");
		return;
	}
}
Exemplo n.º 17
0
 NOINLINE_DECL void msgasserted(int msgid, const char *msg) {
     assertionCount.condrollover( ++assertionCount.warning );
     tlog() << "Assertion: " << msgid << ":" << msg << endl;
     raiseError(msgid,msg && *msg ? msg : "massert failure");
     breakpoint();
     printStackTrace();
     throw MsgAssertionException(msgid, msg);
 }
Exemplo n.º 18
0
page_t *
file_get(md5_digest_t *dir, md5_digest_t *file)
{
  char path[71 + strlen(cfg.base_dir)]; //2*len(md5)+len('/')s+'\0' = 2*32+6+1
  file_path(path, dir, file);
  tlog(DEBUG, "file_read_path(%s)", path);
  return file_read_path(path);
}
Exemplo n.º 19
0
 NOINLINE_DECL void msgasserted(int msgid, const char *msg) {
     assertionCount.condrollover( ++assertionCount.warning );
     tlog() << "Assertion: " << msgid << ":" << msg << endl;
     setLastError(msgid,msg && *msg ? msg : "massert failure");
     //breakpoint();
     logContext();
     throw MsgAssertionException(msgid, msg);
 }
Exemplo n.º 20
0
            bool run(const string& , BSONObj& cmdObj, string& errmsg, BSONObjBuilder& result, bool){
                ShardConnection::sync();

                Timer t;
                string ns = cmdObj.firstElement().valuestrsafe();
                if ( ns.size() == 0 ){
                    errmsg = "no ns";
                    return false;
                }

                DBConfigPtr config = grid.getDBConfig( ns );
                if ( ! config->isSharded( ns ) ){
                    errmsg = "ns not sharded.  have to shard before can move a chunk";
                    return false;
                }

                BSONObj find = cmdObj.getObjectField( "find" );
                if ( find.isEmpty() ){
                    errmsg = "need to specify find.  see help";
                    return false;
                }

                string toString = cmdObj["to"].valuestrsafe();
                if ( ! toString.size()  ){
                    errmsg = "you have to specify where you want to move the chunk";
                    return false;
                }
                
                Shard to = Shard::make( toString );

                // so far, chunk size serves test purposes; it may or may not become a supported parameter
                long long maxChunkSizeBytes = cmdObj["maxChunkSizeBytes"].numberLong();
                if ( maxChunkSizeBytes == 0 ) {
                    maxChunkSizeBytes = Chunk::MaxChunkSize;
                }

                tlog() << "CMD: movechunk: " << cmdObj << endl;

                ChunkManagerPtr info = config->getChunkManager( ns );
                ChunkPtr c = info->findChunk( find );
                const Shard& from = c->getShard();

                if ( from == to ){
                    errmsg = "that chunk is already on that shard";
                    return false;
                }
                
                BSONObj res;
                if ( ! c->moveAndCommit( to , maxChunkSizeBytes , res ) ){
                    errmsg = "move failed";
                    result.append( "cause" , res );
                    return false;
                }

                result.append( "millis" , t.millis() );
                return true;
            }
Exemplo n.º 21
0
/* Present a callback command request to the thread that is waiting for it.
 * This must be called from the main thread of the TLS pool, and it will
 * spark life to the thread that is awaiting the callback.
 */
static void post_callback (struct command *cmd) {
	uint16_t cbid = cmd->cmd.pio_cbid - 1;
	cblist [cbid].fd = -1;
	cblist [cbid].followup = cmd;
	pthread_mutex_lock (&cbfree_mutex);
	tlog (TLOG_UNIXSOCK, LOG_DEBUG, "Signaling on the semaphore of callback 0x%08x", &cblist [cbid]);
	pthread_cond_signal (&cblist [cbid].semaphore);
	pthread_mutex_unlock (&cbfree_mutex);
}
Exemplo n.º 22
0
 void msgasserted(int msgid, const char *msg) {
     assertionCount.condrollover( ++assertionCount.warning );
     tlog() << "Assertion: " << msgid << ":" << msg << endl;
     lastAssert[2].set(msg, getDbContext().c_str(), "", 0);
     raiseError(msgid,msg && *msg ? msg : "massert failure");
     breakpoint();
     printStackTrace();
     throw MsgAssertionException(msgid, msg);
 }
 void run(int){
     LineReader reader(conn);
     LineWriter writer(conn);
     while (true) {
         std::string line = randomString();
         writer.writeLine(line);
         std::string recd = reader.readLine();
         if (recd != line){
             tlog("<ERROR> ["<<clientId<<"]\n\tSent: "<<line<<
                                       "\n\tRecd: "<<recd);
             return;
         }else{
             tlog("<OK> ["<<clientId<<"]\n\tSent: "<<line<<
                                       "\n\tRecd: "<<recd);
         }
         ThreadBase::sleep(200 + rand()%100);
     }
 }
Exemplo n.º 24
0
/* static */
bool FontUtils::IsAvailableFont(const char* input_query_desc) {
  string query_desc(input_query_desc);
  if (PANGO_VERSION <= 12005) {
    // Strip commas and any ' Medium' substring in the name.
    query_desc.erase(std::remove(query_desc.begin(), query_desc.end(), ','),
                     query_desc.end());
    const string kMediumStr = " Medium";
    std::size_t found = query_desc.find(kMediumStr);
    if (found != std::string::npos) {
      query_desc.erase(found, kMediumStr.length());
    }
  }

  PangoFontDescription *desc = pango_font_description_from_string(
      query_desc.c_str());
  PangoFont* selected_font = NULL;
  {
    InitFontconfig();
    PangoFontMap* font_map = pango_cairo_font_map_get_default();
    PangoContext* context = pango_context_new();
    pango_context_set_font_map(context, font_map);
    {
      DISABLE_HEAP_LEAK_CHECK;
      selected_font = pango_font_map_load_font(font_map, context, desc);
    }
    g_object_unref(context);
  }
  PangoFontDescription* selected_desc = pango_font_describe(selected_font);

  bool equal = pango_font_description_equal(desc, selected_desc);
  tlog(3, "query weight = %d \t selected weight =%d\n",
       pango_font_description_get_weight(desc),
       pango_font_description_get_weight(selected_desc));

  char* selected_desc_str = pango_font_description_to_string(selected_desc);
  tlog(2, "query_desc: '%s' Selected: 's'\n", query_desc.c_str(),
       selected_desc_str);

  g_free(selected_desc_str);
  pango_font_description_free(selected_desc);
  pango_font_description_free(desc);
  return equal;
}
Exemplo n.º 25
0
bool
http_post(const char *url, http_response_t *resp, int pairs, ...)
{
    CURL *curl;
    CURLcode res;

    int i, len=0;
    char *k[pairs], *v[pairs], *vv[pairs];
    va_list params;
    va_start(params, pairs);
    for (i=0; i<pairs; i++) {
        k[i] = va_arg(params, char *);
        v[i] = va_arg(params, char *);
        vv[i]= curl_easy_escape(curl, v[i], 0);
        tlog(DEBUG, "http post: %s = %s(%s)", k[i], v[i], vv[i]);
        len += 4+strlen(k[i])+strlen(vv[i]);
    }
    va_end(params);

    char data[len];
    memset(data, 0, len);
    for (i=0; i<pairs; i++) {
        strcat(data, "&");
        strcat(data, k[i]);
        strcat(data, "=");
        strcat(data, vv[i]);
        curl_free(vv[i]);
    }
    tlog(DEBUG, "http post: data = %s", data);

    curl = curl_easy_init();
    if (curl != NULL) {
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_POST, 1);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_memory_cb);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)resp);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        return res==CURLE_OK;
    }
    return false;
}
Exemplo n.º 26
0
/*
 Receive sequence -- see if expected response comes return success
 (or failure) in got_it
*/ 
static 
recvSeq()  {
   
    char *e, got[7], trace[SBUFL];
    int i, l;
    
	sequenc();
	l = strlen(e=seq_buf);		/* no more than 7 chars allowed */
	if (l > 7) {
	    e += l-7;
	    l = 7;
	}
	tlog(F111,"expecting sequence",e,(long) l);
	if (l == 0) {		/* null sequence, just delay a little */
	    sleep (NULL_EXP);
	    got_it = 1;
	    tlog(F100,"got it (null sequence)","",0l);
	    return;
	}
	*trace = '\0';
	for (i=0; i<7; i++) got[i]='\0';

	signal(SIGALRM,scrtime);	/* did we get it? */
	if (!setjmp(alrmRng)) {	/* not timed out yet */
	    alarm(EXP_ALRM);
	    while (!got_it) {
		for (i=0; i<(l-1); i++) got[i] = got[i+1]; /* shift over one */
		got[l-1] = ttinc(0) & 0177;		/* next char */
		if (seslog) 		/* Log in session log */
		  zchout(ZSFILE,got[l-1]);
		if (strlen(trace) < sizeof(trace)-2 ) 
		  strcat(trace,chstr(got[l-1]));
		got_it = (!strncmp(seq_buf, got, l) ) ;
	    }
	} else got_it = 0;		/* timed out here */

	alarm(0);
	signal(SIGALRM,SIG_IGN);
	tlog(F110,"received sequence: ",trace,0l);
	tlog(F101,"returning with got-it code","",(long) got_it);
	return;
}
 void onIncomingConnection(Connection c){
     tlog("Got incoming Connection: "<<c.getRemoteAddress().first<<":"
                 <<c.getRemoteAddress().second);
     LineReader reader(c);
     LineWriter writer(c);
     while (true) {
         std::string in(reader.readLine());
         //tlog("<< "<<in);
         writer.writeLine(in);
     }
 }
Exemplo n.º 28
0
 /* must call when a btree bucket going away.
    note this is potentially slow
 */
 void ClientCursor::informAboutToDeleteBucket(const DiskLoc& b) {
     recursive_scoped_lock lock(ccmutex);
     Database *db = cc().database();
     CCByLoc& bl = db->ccByLoc;
     RARELY if ( bl.size() > 70 ) {
         log() << "perf warning: byLoc.size=" << bl.size() << " in aboutToDeleteBucket\n";
     }
     if( bl.size() == 0 ) { 
         DEV tlog() << "debug warning: no cursors found in informAboutToDeleteBucket()" << endl;
     }
     for ( CCByLoc::iterator i = bl.begin(); i != bl.end(); i++ )
         i->second->_c->aboutToDeleteBucket(b);
 }
Exemplo n.º 29
0
    bool setUpWorld(){
      const char *logOut="stdout";
#if defined(N_LOG_FILE)
      // log to file
      logOut=N_LOG_FILE;
      log_stream()=fopen(logOut, "w");
#else
      // log to stdout.
      tlog("\n");
#endif
      time_t curr=time(NULL);
      tlog("//==========================================================\n"
           "/**\n"
           " \\file         %s\n"
           " \\date:        %s"
           "*/\n"
           "//==========================================================\n",
           logOut,
           ctime(&curr)
           );
      return true;
    }
Exemplo n.º 30
0
string LigatureTable::AddLigatures(const string& str,
                                   const PangoFontInfo* font) const {
  string result;
  int len = str.size();
  int step = 0;
  int i = 0;
  for (i = 0; i < len - min_norm_length_ + 1; i += step) {
    step = 0;
    for (int liglen = max_norm_length_; liglen >= min_norm_length_; --liglen) {
      if (i + liglen <= len) {
        string lig_cand = str.substr(i, liglen);
        LigHash::const_iterator it = norm_to_lig_table_.find(lig_cand);
        if (it != norm_to_lig_table_.end()) {
          tlog(3, "Considering %s -> %s\n", lig_cand.c_str(),
               it->second.c_str());
          if (font) {
            // Test for renderability.
            if (!font->CanRenderString(it->second.data(), it->second.length()))
              continue;  // Not renderable
          }
          // Found a match so convert it.
          step = liglen;
          result += it->second;
          tlog(2, "Substituted %s -> %s\n", lig_cand.c_str(),
               it->second.c_str());
          break;
        }
      }
    }
    if (step == 0) {
      result += str[i];
      step = 1;
    }
  }
  result += str.substr(i, len - i);
  return result;
}