Esempio n. 1
0
/* Add (flagadd=1) or remove (flagadd=0) userhost from the subscriber
 * database table. Comment is e.g. the subscriber from line or name. It
 * is added to the log. Event is the action type, e.g. "probe",
 * "manual", etc. The direction (sub/unsub) is inferred from
 * flagadd. Returns 1 on success, 0 on failure. If forcehash is >=0 it
 * is used in place of the calculated hash. This makes it possible to
 * add addresses with a hash that does not exist. forcehash has to be
 * 0..99.  For unsubscribes, the address is only removed if forcehash
 * matches the actual hash. This way, ezmlm-manage can be prevented from
 * touching certain addresses that can only be removed by
 * ezmlm-unsub. Usually, this would be used for sublist addresses (to
 * avoid removal) and sublist aliases (to prevent users from subscribing
 * them (although the cookie mechanism would prevent the resulting
 * duplicate message from being distributed. */
static int _subscribe(struct subdbinfo *info,
                      const char *table,
                      const char *userhost,
                      int flagadd,
                      const char *comment,
                      const char *event,
                      int forcehash)
{
    sqlite3_stmt *stmt;
    char *cpat;
    char szhash[3] = "00";
    int res;

    unsigned int j;
    unsigned char ch;

    domain.len = 0;			/* clear domain */
    /* lowercase and check address */
    if (!stralloc_copys(&addr,userhost)) die_nomem();
    if (addr.len > 255)			/* this is 401 in std ezmlm. 255 */
        /* should be plenty! */
        strerr_die2x(100,FATAL,MSG(ERR_ADDR_LONG));
    j = byte_rchr(addr.s,addr.len,'@');
    if (j == addr.len)
        strerr_die2x(100,FATAL,MSG(ERR_ADDR_AT));
    cpat = addr.s + j;
    case_lowerb(cpat + 1,addr.len - j - 1);
    if (!stralloc_copy(&quoted, &addr)) die_nomem();
    /* stored unescaped, so it should be ok if quoted.len is >255, as */
    /* long as addr.len is not */

    if (forcehash < 0) {
        if (!stralloc_copy(&lcaddr,&addr)) die_nomem();
        case_lowerb(lcaddr.s,j);		/* make all-lc version of address */
        ch = subhashsa(&lcaddr);
    } else
        ch = (forcehash % 100);

    szhash[0] = '0' + ch / 10;		/* hash for sublist split */
    szhash[1] = '0' + (ch % 10);

    if (flagadd) {
        if (!stralloc_copys(&line,"SELECT address FROM ")) die_nomem();
        if (!stralloc_cat_table(&line,info,table)) die_nomem();
        if (!stralloc_cats(&line," WHERE address LIKE '")) die_nomem();
        if (!stralloc_cat(&line,&quoted)) die_nomem();	/* addr */
        if (!stralloc_cats(&line,"'")) die_nomem();
        if (!stralloc_0(&line)) die_nomem();

        if ((stmt = _sqlquery(info, &line)) == NULL)
            strerr_die2x(111,FATAL,sqlite3_errmsg((sqlite3*)info->conn));

        res = sqlite3_step(stmt);
        sqlite3_finalize(stmt);

        if (res == SQLITE_ROW)
            return 0;						/* there */
        else if (res != SQLITE_DONE)
        {
            strerr_die2x(111,FATAL,sqlite3_errmsg((sqlite3*)info->conn));
        } else {							/* not there */
            if (!stralloc_copys(&line,"INSERT INTO ")) die_nomem();
            if (!stralloc_cat_table(&line,info,table)) die_nomem();
            if (!stralloc_cats(&line," (address,hash) VALUES ('"))
                die_nomem();
            if (!stralloc_cat(&line,&quoted)) die_nomem();	/* addr */
            if (!stralloc_cats(&line,"',")) die_nomem();
            if (!stralloc_cats(&line,szhash)) die_nomem();	/* hash */
            if (!stralloc_cats(&line,")")) die_nomem();
            if (!stralloc_0(&line)) die_nomem();

            if ((stmt = _sqlquery(info, &line)) == NULL)
                strerr_die2x(111,FATAL,sqlite3_errmsg((sqlite3*)info->conn));

            if (sqlite3_step(stmt) != SQLITE_DONE)
                strerr_die2x(111,FATAL,sqlite3_errmsg((sqlite3*)info->conn));

            sqlite3_finalize(stmt);
        }
    } else {							/* unsub */
        if (!stralloc_copys(&line,"DELETE FROM ")) die_nomem();
        if (!stralloc_cat_table(&line,info,table)) die_nomem();
        if (!stralloc_cats(&line," WHERE address LIKE '")) die_nomem();
        if (!stralloc_cat(&line,&quoted)) die_nomem();	/* addr */
        if (forcehash >= 0) {
            if (!stralloc_cats(&line,"' AND hash=")) die_nomem();
            if (!stralloc_cats(&line,szhash)) die_nomem();
        } else {
            if (!stralloc_cats(&line,"' AND hash BETWEEN 0 AND 52"))
                die_nomem();
        }

        if (!stralloc_0(&line)) die_nomem();

        if ((stmt = _sqlquery(info, &line)) == NULL)
            strerr_die2x(111,FATAL,sqlite3_errmsg((sqlite3*)info->conn));

        if (sqlite3_step(stmt) != SQLITE_DONE)
            strerr_die2x(111,FATAL,sqlite3_errmsg((sqlite3*)info->conn));

        sqlite3_finalize(stmt);

        if (sqlite3_changes((sqlite3*)info->conn) == 0)
            return 0;				/* address wasn't there*/
    }

    /* log to subscriber log */
    /* INSERT INTO t_slog (address,edir,etype,fromline) */
    /* VALUES('address',{'+'|'-'},'etype','[comment]') */

    if (!stralloc_copys(&logline,"INSERT INTO ")) die_nomem();
    if (!stralloc_cat_table(&logline,info,table)) die_nomem();
    if (!stralloc_cats(&logline,
                       "_slog (tai,address,edir,etype,fromline) VALUES ("))
        die_nomem();
    if (!stralloc_catb(&logline,strnum,fmt_ulong(strnum,now()))) die_nomem();
    if (!stralloc_cats(&logline,",'")) die_nomem();
    if (!stralloc_cat(&logline,&quoted)) die_nomem();
    if (flagadd) {						/* edir */
        if (!stralloc_cats(&logline,"','+','")) die_nomem();
    } else {
        if (!stralloc_cats(&logline,"','-','")) die_nomem();
    }
    if (*(event + 1))	/* ezmlm-0.53 uses '' for ezmlm-manage's work */
        if (!stralloc_catb(&logline,event+1,1)) die_nomem();	/* etype */
    if (!stralloc_cats(&logline,"','")) die_nomem();
    if (comment && *comment) {
        j = str_len(comment);
        if (!stralloc_copys(&quoted, comment)) die_nomem();	/* from */
        if (!stralloc_cat(&logline,&quoted)) die_nomem();
    }
    if (!stralloc_cats(&logline,"')")) die_nomem();
    if (!stralloc_0(&logline)) die_nomem();

    if ((stmt = _sqlquery(info, &logline)) != NULL)
    {
        sqlite3_step(stmt);			/* log (ignore errors) */
        sqlite3_finalize(stmt);
    }

    if (!stralloc_0(&addr))
        ;				/* ignore errors */
    logaddr(table,event,addr.s,comment);	/* also log to old log */
    return 1;					/* desired effect */
}
void ComTdbFastExtract::displayContents(Space *space, ULng32 flag)
{
  ComTdb::displayContents(space, flag & 0xFFFFFFFE);

  if (flag & 0x00000008)
  {
    const size_t sz = sizeof(short);
    char buf[512];

    str_sprintf(buf, "\nFor ComTdbFastExtract :");
    space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);

    Lng32 lowFlags = (Lng32) (flags_ % 65536);
    Lng32 highFlags = (Lng32) ((flags_ - lowFlags) / 65536);
    str_sprintf(buf, "flags = %b%b", highFlags, lowFlags);
    space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);

    str_sprintf(buf, "requestRowLength = %d ", requestRowLen_);
    space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);

    str_sprintf(buf, "outputRowLen = %d ", outputRowLen_);
    space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);

    str_sprintf(buf, "childTuppIndex = %d ", (Int32) childDataTuppIndex_);
    space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);

    if (targetName_)
   {
	 char *s = targetName_;
	 str_sprintf(buf, "targetName = %s", s);
	 space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);
   }

    if (hdfsHostName_)
   {
	 char *s = hdfsHostName_;
	 str_sprintf(buf, "hdfsHostName = %s", s);
	 space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);
   }
    
   str_sprintf(buf,"hdfsPortNum = %d", hdfsPortNum_);
   space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(UInt16));

   if (delimiter_)
   {
	 char *s = delimiter_;
	 str_sprintf(buf, "delimiter = %s", s);
	 space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);
   }

   if (header_)
   {
	 char *s = header_;
	 str_sprintf(buf, "header = %s", s);
	 space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);
   }

   if (nullString_)
   {
	 char *s = nullString_;
	 str_sprintf(buf, "nullString = %s", s);
	 space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);
   }

   if (recordSeparator_)
   {
	 char *s = recordSeparator_;
	 str_sprintf(buf, "recordSeparator = %s", s);
	 space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);
   }

   str_sprintf(buf,"numIOBuffers = %d", numIOBuffers_);
   space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sizeof(UInt16));

  } // if (flag & 0x00000008)

   displayExpression(space,flag);
   displayChildren(space,flag);

}
Esempio n. 3
0
int dcps_get_local_publication_data (DDS_PublicationBuiltinTopicData *dp,
				     Writer_t                        *wp)
{
	size_t		size, psize;
	char		*xp;
	UniQos_t	*uqp;

	size = str_len (wp->w_topic->name);
	size += str_len (wp->w_topic->type->type_name);
	if (wp->w_qos->qos.user_data) {
		ROUND_LEN (size);
		size += str_len (wp->w_qos->qos.user_data);
	}
	if (wp->w_publisher->qos.partition) {
		ROUND_LEN (size);
		psize = partition_size (wp->w_publisher->qos.partition);
		size += psize;
	}
	if (wp->w_topic->qos->qos.topic_data) {
		ROUND_LEN (size);
		size += str_len (wp->w_topic->qos->qos.topic_data);
	}
	if (wp->w_publisher->qos.group_data) {
		ROUND_LEN (size);
		size += str_len (wp->w_publisher->qos.group_data);
	}
	xp = xmalloc (size);
	if (!xp)
		return (DDS_RETCODE_OUT_OF_RESOURCES);

	dp->topic_name = xp;
	dp->key.value [0] = wp->w_publisher->domain->participant.p_guid_prefix.w [0];
	dp->key.value [1] = wp->w_publisher->domain->participant.p_guid_prefix.w [1];
	dp->key.value [2] = wp->w_entity_id.w;
	memcpy (&dp->participant_key,
		&wp->w_publisher->domain->participant.p_guid_prefix,
		sizeof (DDS_BuiltinTopicKey_t));
	memcpy (xp, str_ptr (wp->w_topic->name),
						str_len (wp->w_topic->name));
	xp += str_len (wp->w_topic->name);
	dp->type_name = xp;
	memcpy (xp, str_ptr (wp->w_topic->type->type_name),
				     str_len (wp->w_topic->type->type_name));
	xp += str_len (wp->w_topic->type->type_name);
	uqp = &wp->w_qos->qos;
	dp->durability.kind = uqp->durability_kind;
#ifdef DURABILITY_SERVICE
	dp->durability_service.service_cleanup_delay = uqp->ds_cleanup_delay;
	dp->durability_service.history_kind = uqp->ds_history_kind;
	dp->durability_service.history_depth = uqp->ds_history_depth;
	dp->durability_service.max_samples = uqp->ds_limits.max_samples;
	dp->durability_service.max_instances = uqp->ds_limits.max_instances;
	dp->durability_service.max_samples_per_instance = uqp->ds_limits.max_samples_per_instance;
#else
	dp->durability_service = qos_def_writer_qos.durability_service;
#endif
	dp->deadline = uqp->deadline;
	dp->latency_budget = uqp->latency_budget;
	dp->liveliness.kind = uqp->liveliness_kind;
	dp->liveliness.lease_duration = uqp->liveliness_lease_duration;
	dp->reliability.kind = uqp->reliability_kind;
	dp->reliability.max_blocking_time = uqp->reliability_max_blocking_time;
	dp->lifespan = uqp->lifespan;
	if (uqp->user_data)
		ROUND_PTR (xp);
	oseq_set (&dp->user_data.value, uqp->user_data, (unsigned char *) xp);
	xp += DDS_SEQ_LENGTH (dp->user_data.value);
	dp->ownership.kind = uqp->ownership_kind;
	dp->ownership_strength = uqp->ownership_strength;
	dp->destination_order.kind = uqp->destination_order_kind;
	dp->presentation.access_scope = uqp->presentation_access_scope;
	dp->presentation.coherent_access = uqp->presentation_coherent_access;
	dp->presentation.ordered_access = uqp->presentation_ordered_access;
	if (uqp->partition)
		ROUND_PTR (xp);
	xp += partition_set (&dp->partition.name, wp->w_publisher->qos.partition, (unsigned char *) xp);
	if (wp->w_topic->qos->qos.topic_data)
		ROUND_PTR (xp);
	oseq_set (&dp->topic_data.value, wp->w_topic->qos->qos.topic_data, (unsigned char *) xp);
	xp += DDS_SEQ_LENGTH (dp->topic_data.value);
	if (wp->w_publisher->qos.group_data)
		ROUND_PTR (xp);
	oseq_set (&dp->group_data.value, wp->w_publisher->qos.group_data, (unsigned char *) xp);
	return (DDS_RETCODE_OK);
}
Esempio n. 4
0
int main(int argc, char **argv) {
  unsigned int i, done;
  char *x;

  progname =*argv;
  for (i =str_len(*argv); i; --i) if ((*argv)[i -1] == '/') break;
  *argv +=i;
  optprogname =progname =*argv;
  service =argv;
  services =1;
  lsb =(str_diff(progname, "sv"));
  if ((x =env_get("SVDIR"))) varservice =x;
  if ((x =env_get("SVWAIT"))) scan_ulong(x, &wait);
  while ((i =getopt(argc, (const char* const*)argv, "w:vV")) != opteof) {
    switch(i) {
    case 'w': scan_ulong(optarg, &wait);
    case 'v': verbose =1; break;
    case 'V': strerr_warn1(VERSION, 0);
    case '?': usage();
    }
  }
  argv +=optind; argc -=optind;
  if (!(action =*argv++)) usage(); --argc;
  if (!lsb) { service =argv; services =argc; }
  if (!*service) usage();

  taia_now(&tnow); tstart =tnow;
  if ((curdir =open_read(".")) == -1)
    fatal("unable to open current directory");

  act =&control; acts ="s";
  if (verbose) cbk =&check;
  switch (*action) {
  case 'x': case 'e':
    acts ="x"; break;
  case 'X': case 'E':
    acts ="x"; kll =1; cbk =&check; break;
  case 'D':
    acts ="d"; kll =1; cbk =&check; break;
  case 'T':
    acts ="tc"; kll =1; cbk =&check; break;
  case 'c':
    if (!str_diff(action, "check")) { act =0; acts ="C"; cbk =&check; break; }
  case 'u': case 'd': case 'o': case 't': case 'p': case 'h':
  case 'a': case 'i': case 'k': case 'q': case '1': case '2':
    action[1] =0; acts =action; break;
  case 's':
    if (!str_diff(action, "shutdown")) { acts ="x"; cbk =&check; break; }
    if (!str_diff(action, "start")) { acts ="u"; cbk =&check; break; }
    if (!str_diff(action, "stop")) { acts ="d"; cbk =&check; break; }
    if (lsb && str_diff(action, "status")) usage();
    act =&status; cbk =0; break;
  case 'r':
    if (!str_diff(action, "restart")) { acts ="tcu"; cbk =&check; break; }
    usage();
  case 'f':
    if (!str_diff(action, "force-reload"))
      { acts ="tc"; kll =1; cbk =&check; break; }
    if (!str_diff(action, "force-restart"))
      { acts ="tcu"; kll =1; cbk =&check; break; }
    if (!str_diff(action, "force-shutdown"))
      { acts ="x"; kll =1; cbk =&check; break; }
    if (!str_diff(action, "force-stop"))
      { acts ="d"; kll =1; cbk =&check; break; }
  default:
    usage();
  }

  servicex =service;
  for (i =0; i < services; ++i) {
    if ((**service != '/') && (**service != '.') && **service &&
        ((*service)[str_len(*service) -1] != '/')) {
      if ((chdir(varservice) == -1) || (chdir(*service) == -1)) {
        fail("unable to change to service directory");
        *service =0;
      }
    }
    else
      if (chdir(*service) == -1) {
        fail("unable to change to service directory");
        *service =0;
      }
    if (*service) if (act && (act(acts) == -1)) *service =0;
    if (fchdir(curdir) == -1) fatal("unable to change to original directory");
    service++;
  }

  if (*cbk)
    for (;;) {
      taia_sub(&tdiff, &tnow, &tstart);
      service =servicex; done =1;
      for (i =0; i < services; ++i, ++service) {
        if (!*service) continue;
        if ((**service != '/') && (**service != '.')) {
          if ((chdir(varservice) == -1) || (chdir(*service) == -1)) {
            fail("unable to change to service directory");
            *service =0;
          }
        }
        else
          if (chdir(*service) == -1) {
            fail("unable to change to service directory");
            *service =0;
          }
        if (*service) { if (cbk(acts) != 0) *service =0; else done =0; }
        if (*service && taia_approx(&tdiff) > wait) {
          kll ? outs(KILL) : outs(TIMEOUT);
          if (svstatus_get() > 0) { svstatus_print(*service); ++rc; }
          flush("\n");
          if (kll) control("k");
          *service =0;
        }
        if (fchdir(curdir) == -1)
          fatal("unable to change to original directory");
      }
      if (done) break;
      usleep(420000);
      taia_now(&tnow);
    }
  return(rc > 99 ? 99 : rc);
}
Esempio n. 5
0
int postings_addword(struct postings *post, char *term, 
  unsigned long int wordno) {
    unsigned int hash,
                 len,
                 bytes;
    struct postings_node** prev,
                        * node;

    if (post->stem) {
        post->stem(post->stem_opaque, term);
        /* do nothing for 0 length terms (occur sometimes because stemming 
         * removes entire word :o( ) */
        if (!term[0]) {
            return 1;
        }
    }

    assert(!iscntrl(term[0]));
    hash = str_hash(term) & bit_lmask(post->tblbits);
    prev = &post->hash[hash]; 
    node = *prev;

    while (node) {
        if (!str_cmp(term, node->term)) {
            /* found previous entry, perform move to front on hash chain */
            *prev = node->next;
            node->next = post->hash[hash];
            post->hash[hash] = node;
            break;
        }
        prev = &node->next;
        node = *prev;
    }

    if (!node) {
        /* couldn't find a previous entry, need to add a new one */
        len = str_len(term);
        assert(len);
        if ((node = objalloc_malloc(post->node_mem, sizeof(*node)))
          && (node->term = poolalloc_memalign(post->string_mem, len + 1, 1))
          && (node->vec.pos = node->vecmem = malloc(INITVECLEN))) {

            node->vec.end = node->vec.pos + INITVECLEN;

            str_cpy(node->term, term);

            node->last_docno = -1;
            node->last_offset = -1;
            node->last_count = node->vecmem;
            node->next = post->hash[hash];
            node->docs = node->offsets = node->occurs = 0;
            /* insert into table */
            post->hash[hash] = node;
            post->dterms++;
            post->size += len + 1;
        } else if (node->vecmem) {
            free(node->vecmem);
            post->err = ENOMEM;
            return 0;
        /* don't need to check others because they come from mem pools */
        } else {
            post->err = ENOMEM;
            return 0;
        }
    }

    assert(node);

    /* mark document as changed */
    if (!node->offsets) {
        node->update = post->update;
        post->update = node;

        /* write d-gap */
        while (!(bytes 
          = vec_vbyte_write(&node->vec, 
            post->docno - (node->last_docno + 1)))) {

            /* need to expand the node */
            if (!postings_node_expand(node)) {
                return 0;
            }
        }
        post->size += bytes + 1;

        /* save current position in case we need to overwrite it later, and
         * write in a count of 1 */
        node->last_count = node->vec.pos;
        assert(node->last_count > node->vecmem);
        while (!(bytes = vec_vbyte_write(&node->vec, 1))) {
            /* need to expand the node */
            if (!postings_node_expand(node)) {
                return 0;
            }
        }
    }

    /* encode new offset */
    assert((wordno > node->last_offset) || (node->last_offset == -1));
    while (!(bytes 
      = vec_vbyte_write(&node->vec, wordno - (node->last_offset + 1)))) {
         /* need to expand the node */
         if (!postings_node_expand(node)) {
             return 0;
         }
    }
    post->size += bytes;
    node->last_offset = wordno;
    node->offsets++;
    post->terms++;
    return 1;
}
Esempio n. 6
0
char* json_rpc_handle_request(json_rpc_instance_t* self, json_rpc_data_t* request_data)
{
    char* res = 0;
    rpc_request_info_t request_info;
    json_token_info_t next_req_token;
    json_token_info_t next_mem_token;

    int curr_pos = 0;
    int next_r_pos = 0;

    int next_req_max_pos = 0;

    int obj_id = -1;
    int fcn_id = -2;

    request_info.data = request_data;
    if(request_data->response && request_data->response_len)
    {
        *request_data->response = 0; // null
    }

    next_r_pos = skip_all_of(request_data->request, 0, " \n\r\t", 0);

    reset_token_info(&next_req_token);
    next_req_token.values_start = next_r_pos;
    next_req_token.values_len = request_data->request_len-next_r_pos;

    // skip [] bracket for a batch..
    if(json_next_member_is_list(request_data->request, &next_req_token))
    {
        next_r_pos = skip_all_of(request_data->request, next_r_pos+1, " \n\r\t", 0);
        if(request_data->response && request_data->response_len)
        {
            append_str(request_data->response, "[");
        }
    }

    while(next_r_pos < request_data->request_len)
    {
        // reset some of the request info data
        request_info.id_start = -1;
        request_info.info_flags = 0;
        fcn_id = -2;
        obj_id = -1;


        // extract next request (there can be a batch of them)
        next_r_pos = json_find_next_member(next_r_pos, request_data->request, request_data->request_len, &next_req_token);
        if(json_next_member_is_object(request_data->request, &next_req_token))
        {
            curr_pos = next_req_token.values_start+1; // move past this next object
        }
        else
        {
            curr_pos = next_req_token.values_start;
        }

        // skip the whitespace
        curr_pos = skip_all_of(request_data->request, curr_pos, " \n\r\t", 0);

        next_req_max_pos = next_req_token.values_start+next_req_token.values_len;
        while(curr_pos < next_req_max_pos)
        {
            curr_pos = json_find_next_member(curr_pos,
                                             request_data->request,
                                             next_req_max_pos, &next_mem_token);

            if (next_mem_token.name_start > 0)
            {
                obj_id = get_obj_id(request_data->request, &next_mem_token);
                switch (obj_id)
                {
                    case jsonrpc:
                        if(str_are_equal(request_data->request + next_mem_token.values_start, "2.0"))
                        {
                            request_info.info_flags |= rpc_request_is_rpc_20;
                        }
                        break;

                    case method:
                        fcn_id = get_fcn_id(self, request_data->request, &next_mem_token);
                        if(fcn_id >= 0)
                        {
                            request_info.info_flags |= rpc_request_is_notification; // assume it is notification
                        }
                        break;

                    case params:
                        request_info.params_start = next_mem_token.values_start;
                        request_info.params_len = next_mem_token.values_len;
                        break;

                    case request_id:
                        if(!str_are_equal(request_data->request + next_mem_token.values_start, "none") &&
                           !str_are_equal(request_data->request + next_mem_token.values_start, "null"))
                        {
                            request_info.info_flags &= ~rpc_request_is_notification;
                            request_info.id_start = next_mem_token.values_start;
                            request_info.id_len = next_mem_token.values_len;
                        }
                        break;
                }
            }
            else
            {
                break;
            }
        }

        if(fcn_id < 0)
        {
            if(fcn_id == -1)
            {
                res = json_rpc_create_error(json_rpc_err_method_not_found, &request_info);
            }
            else
            {
                res = json_rpc_create_error(json_rpc_err_invalid_request, &request_info);
            }
        }
        else if(request_info.params_start < 0)
        {
            res = json_rpc_create_error(json_rpc_err_invalid_request, &request_info);
        }
        else
        {
            res = self->handlers[fcn_id].handler(&request_info); // everything OK, can call a handler
        }
    }

    if(request_data->response && request_data->response_len &&
       request_data->response[0] == '[')
    {
        append_str(request_data->response+str_len(request_data->response), "]");
    }

    return res;
}
Esempio n. 7
0
/* Private functions ------------------------------------------------------- */
static int json_find_member_value(int start_from, const char* input, struct json_token_info* info)
{
    int curr_pos = start_from;
    int max_len = str_len(input);

    int in_quotes = 0;
    int in_object = 0;
    int in_array = 0;
    char curr;
    int values_end = 0;

    curr_pos = skip_all_of(input, curr_pos, "\n\r\t :", 0); // whitespace & colon: we'll be searching for a value
    info->values_start = curr_pos;

    // find value(s) for this object
    while(curr_pos < max_len)
    {
        curr = input[curr_pos];
        switch(curr)
        {
        case '\"':
            in_quotes = ~in_quotes;
            curr_pos++;
            continue;

        case '[':
            if(!in_quotes)
            {
                in_array++;
            }
            curr_pos++;
            continue;

        case '{':
            if(!in_quotes)
            {
                in_object++;
            }
            curr_pos++;
            continue;

        case ']':
            curr_pos++;
            if(!in_quotes)
            {
                in_array--;
                if(in_array <= 0)
                {
                    if(!in_object)
                    {
                        values_end = curr_pos;
                        break;
                    }
                }
            }
            continue;

        case '}':
            curr_pos++;
            if(!in_quotes)
            {
                in_object--;
                if(in_object <= 0)
                {
                    if(!in_array)
                    {
                        values_end = curr_pos;
                        break;
                    }
                }
            }
            continue;
        }

        if(values_end > 0 ||
          ( curr == ',' && !in_object && !in_array && !in_quotes ))
        {
             // in_object or in_array will have negative values if a whole object and / or array
             // was extracted, so adjust for this
             values_end = curr_pos + in_object + in_array;
             curr_pos++;
             break;
        }
        curr_pos++;
    }

    if(input[info->values_start] == '\"' && input[values_end-1] == '\"')
    {
        info->values_start++;
        values_end--;
    }
    else
    {
        info->values_start = skip_all_of(input, info->values_start, " \t\n\r", 0);
        values_end = skip_all_of(input, values_end, " \t\n\r", 1);
    }

    info->values_len = (values_end >= info->values_start) ? values_end - info->values_start : 0;
    return curr_pos;
}
Esempio n. 8
0
//
// This is the LmUtility.nativeUtils method. It takes one string as
// input and produces one string as output. The output string gets
// written to the first element of the String[] array object passed in
// as the jobjectArray parameter.
//
// Although we do not document this method for customers, there is
// nothing preventing customer code from calling this method. So don't
// put anything in the method that you wouldn't want customers
// doing. Currently this function just serves as an entry point to
// various systems calls such as TMF operations and getting/setting
// environment variables. There is nothing here that customers could
// not do on their own if they wanted to.
//
JNIEXPORT void JNICALL Java_org_trafodion_sql_udr_LmUtility_nativeUtils
(JNIEnv * env, jclass jc, jstring js, jobjectArray joa)
{
  const char *input = env->GetStringUTFChars(js, NULL);
  if (input == NULL)
  {
    // OutOfMemory error already thrown
    return;
  }

  NAString action(input);
  TrimNAStringSpace(action);

  short error;
  NAString result("OK");

  static MXStatement staticStmt;

  if (action.compareTo("GetTxName", NAString::ignoreCase) == 0)
  {
    Int64 transid;
    error = GETTRANSID((short *) &transid);
    if (error)
    {
      if (error == 75)
      {
        result = "No active transaction";
      }
      else
      {
        result = "GETTRANSID returned ";
        result += LongToNAString((Lng32) error);
      }
      Throw(env, result.data());
    }
    else
    {
      short actualLen;
      char text[256];
      error = TRANSIDTOTEXT(transid, text, 255, &actualLen);
      if (error)
      {
        result = "TRANSIDTOTEXT returned ";
        result += LongToNAString((Lng32) error);
        Throw(env, result);
      }
      else
      {
        text[actualLen] = 0;
        result = text;
      }
    }
  } // GetTxName

  else if (action.compareTo("BeginTx", NAString::ignoreCase) == 0)
  {
    Int32 tag;
    error = BEGINTRANSACTION(&tag);
    if (error)
    {
      result = "BEGINTRANSACTION returned ";
      result += LongToNAString((Lng32) error);
      Throw(env, result);
    }
  } // BeginTx

  else if (action.compareTo("CommitTx", NAString::ignoreCase) == 0)
  {
    error = ENDTRANSACTION();
    if (error)
    {
      if (error == 75)
      {
        result = "No active transaction";
      }
      else
      {
        result = "ENDTRANSACTION returned ";
        result += LongToNAString((Lng32) error);
      }
      Throw(env, result);
    }
  } // CommitTx

  else if (action.compareTo("RollbackTx", NAString::ignoreCase) == 0)
  {
    error = ABORTTRANSACTION();
    if (error)
    {
      if (error == 75)
      {
        result = "No active transaction";
      }
      else
      {
        result = "ABORTTRANSACTION returned ";
        result += LongToNAString((Lng32) error);
      }
      Throw(env, result);
    }
  } // RollbackTx

  else if (action.compareTo("GetProcessId", NAString::ignoreCase) == 0)
  {
    Lng32 pid = GETPID();
    result = LongToNAString(pid);
  } // GetProcessId

  else if (action.index("GetEnv ", 0, NAString::ignoreCase) == 0)
  {
    NAString name = action;
    name.remove(0, str_len("GetEnv "));
    TrimNAStringSpace(name);
    char *value = getenv(name.data());
    if (value != NULL)
    {
      result = value;
    }
    else
    {
      result = "";
    }
  } // GetEnv

  else if (action.index("PutEnv ", 0, NAString::ignoreCase) == 0)
  {
    NAString nameAndValue = action;
    nameAndValue.remove(0, str_len("PutEnv "));
    TrimNAStringSpace(nameAndValue);
    Int32 retcode = putenv((char *) nameAndValue.data());
    if (retcode != 0)
    {
      result = "putenv returned ";
      result += LongToNAString((Lng32) retcode);
      Throw(env, result);
    }
  } // PutEnv

  else if (action.index("LmDebug ", 0, NAString::ignoreCase) == 0)
  {
    NAString name = action;
    name.remove(0, str_len("LmDebug "));
    LM_DEBUG0(name.data());
  } // LmDebug

  else if (action.index("ExecSql ", 0, NAString::ignoreCase) == 0)
  {
    NAString stmtText = action.remove(0, str_len("ExecSql "));

    MXStatement s;
    const char *status = "OK";
    Lng32 retcode = 0;

    retcode = s.init(status);
  
    if (retcode == 0)
    {
      retcode = s.prepare(stmtText.data());
      if (retcode != 0)
      {
        status = "PREPARE failed";
      }
    }
  
    if (retcode == 0)
    {
      retcode = s.execute();
      if (retcode != 0)
      {
        status = "EXECUTE failed";
      }
    }
  
    if (retcode == 0)
    {
      retcode = s.fetchEOD();
      if (retcode != 0)
      {
        status = "FETCH failed";
      }
    }
  
    if (retcode == 0)
    {
      retcode = s.close();
      if (retcode != 0)
      {
        status = "CLOSE failed";
      }
    }

    if (retcode != 0)
    {
      char msg[256];
      sprintf(msg, "[UdrSqlException %d] %s", retcode, status);
      Throw(env, msg);
    }
  
  } // ExecSql

  else if (action.index("FetchSql ", 0, NAString::ignoreCase) == 0)
  {
    // The incoming string is SQL statement text. The code below will
    // prepare and execute the statement then fetch only the first
    // row. It will build one long multi-line string containing all
    // column values, one on each line. The multi-line string can be
    // split by the Java caller into an array of Strings with the
    // split("\n") method.

    Lng32 i;
    NAString stmtText = action.remove(0, str_len("FetchSql "));

    MXStatement s;
    const char *status = "OK";
    Lng32 retcode = 0;

    retcode = s.init(status);
  
    if (!retcode)
    {
      retcode = s.prepare(stmtText.data());
      if (retcode)
        status = "PREPARE failed";
    }
  
    if (!retcode)
    {
      retcode = s.execute();
      if (retcode)
        status = "EXECUTE failed";
    }

    Lng32 numOutColumns = s.getNumOutColumns();
    NABoolean stringsAllocated = FALSE;
    char **argv = NULL;

    if (!retcode && numOutColumns > 0)
    {
      argv = new char *[numOutColumns];
      Lng32 bufLen = 1000;
      for (i = 0; i < numOutColumns; i++)
        argv[i] = new char[bufLen + 1];

      stringsAllocated = TRUE;

      retcode = s.fetchStrings(argv, bufLen);
      if (retcode)
        status = "FETCH STRINGS failed";

      if (!retcode)
      {
        result = argv[0];
        for (i = 1; i < numOutColumns; i++)
        {
          result += "\n";
          result += argv[i];
        }
      }
    }
  
    if (!retcode)
    {
      retcode = s.fetchEOD();
      if (retcode)
        status = "FETCH EOD failed";
    }
  
    if (!retcode)
    {
      retcode = s.close();
      if (retcode)
        status = "CLOSE failed";
    }

    if (stringsAllocated)
    {
      for (i = 0; i < numOutColumns; i++)
        delete [] argv[i];
      delete [] argv;
    }

    if (retcode)
    {
      char msg[256];
      sprintf(msg, "[UdrSqlException %d] %s", retcode, status);
      Throw(env, msg);
    }
  
  } // FetchSql

  else if (action.index("Prepare ", 0, NAString::ignoreCase) == 0)
  {
    NAString stmtText = action.remove(0, str_len("Prepare "));

    const char *status = "OK";
    Lng32 retcode = 0;

    retcode = staticStmt.init(status);
  
    if (retcode == 0)
    {
      retcode = staticStmt.prepare(stmtText.data());
      if (retcode != 0)
      {
        status = "PREPARE failed";
      }
    }
  
    if (retcode)
    {
      char msg[256];
      sprintf(msg, "[UdrSqlException %d] %s", retcode, status);
      Throw(env, msg);
    }

  } // Prepare
  
  else if (action.index("ExecUsingString ", 0, NAString::ignoreCase) == 0)
  {
    NAString data = action.remove(0, str_len("ExecUsingString "));

    const char *status = "OK";
    Lng32 retcode = 0;

    if (retcode == 0)
    {
      retcode = staticStmt.executeUsingString(data.data(),
                                              (Lng32) data.length());
      if (retcode != 0)
      {
        status = "EXECUTE failed";
      }
    }
  
    if (retcode == 0)
    {
      retcode = staticStmt.fetchEOD();
      if (retcode != 0)
      {
        status = "FETCH failed";
      }
    }
  
    if (retcode == 0)
    {
      retcode = staticStmt.close();
      if (retcode != 0)
      {
        status = "CLOSE failed";
      }
    }

    if (retcode != 0)
    {
      char msg[256];
      sprintf(msg, "[UdrSqlException %d] %s", retcode, status);
      Throw(env, msg);
    }
  
  } // ExecUsingString

  else if (action.index("FetchUsingString ", 0, NAString::ignoreCase) == 0)
  {
    NAString data = action.remove(0, str_len("FetchUsingString "));
    const char *status = "OK";
    Lng32 retcode = 0;
    Int32 i = 0;

    if (!retcode)
    {
      retcode = staticStmt.executeUsingString(data.data(),
                                              (Lng32) data.length());
      if (retcode)
        status = "EXECUTE failed";
    }

    Lng32 numOutColumns = staticStmt.getNumOutColumns();
    NABoolean stringsAllocated = FALSE;
    char **argv = NULL;

    if (!retcode && numOutColumns > 0)
    {
      argv = new char *[numOutColumns];
      Lng32 bufLen = 1000;
      for (i = 0; i < numOutColumns; i++)
        argv[i] = new char[bufLen + 1];

      stringsAllocated = TRUE;

      retcode = staticStmt.fetchStrings(argv, bufLen);
      if (retcode)
        status = "FETCH STRINGS failed";

      if (!retcode)
      {
        result = argv[0];
        for (i = 1; i < numOutColumns; i++)
        {
          result += "\n";
          result += argv[i];
        }
      }
    }
  
    if (!retcode)
    {
      retcode = staticStmt.fetchEOD();
      if (retcode)
        status = "FETCH EOD failed";
    }
  
    if (!retcode)
    {
      retcode = staticStmt.close();
      if (retcode)
        status = "CLOSE failed";
    }

    if (stringsAllocated)
    {
      for (i = 0; i < numOutColumns; i++)
        delete [] argv[i];
      delete [] argv;
    }

    if (retcode)
    {
      char msg[256];
      sprintf(msg, "[UdrSqlException %d] %s", retcode, status);
      Throw(env, msg);
    }
  
  } // FetchUsingString

  else
  {
    //
    // Over time other operations can be supported
    //
    result = "Invalid action: ";
    result += action;
    Throw(env, result);
  }

  //
  // Create the Java output string
  //
  if (env->ExceptionCheck() == JNI_FALSE)
  {
    jobject j = env->NewStringUTF(result.data());
    env->SetObjectArrayElement(joa, 0, j);
  }

}
Esempio n. 9
0
File: s6-svc.c Progetto: 8l/s6
int main (int argc, char const *const *argv, char const *const *envp)
{
  char data[DATASIZE+1] = "-" ;
  unsigned int datalen = 1 ;
  unsigned int timeout = 0 ;
  char updown[3] = "-\0" ;
  PROG = "s6-svc" ;
  {
    subgetopt_t l = SUBGETOPT_ZERO ;
    for (;;)
    {
      register int opt = subgetopt_r(argc, argv, "abqhkti12pcoduxOXyT:w:", &l) ;
      if (opt == -1) break ;
      switch (opt)
      {
        case 'a' :
        case 'b' :
        case 'q' :
        case 'h' :
        case 'k' :
        case 't' :
        case 'i' :
        case '1' :
        case '2' :
        case 'p' :
        case 'c' :
        case 'o' :
        case 'd' :
        case 'u' :
        case 'x' :
        case 'O' :
        case 'X' :
        case 'y' :
        {
          if (datalen >= DATASIZE) strerr_dief1x(100, "too many commands") ;
          data[datalen++] = opt ;
          break ;
        }
        case 'T' : if (!uint0_scan(l.arg, &timeout)) dieusage() ; break ;
        case 'w' :
        {
          if (byte_chr("dDuUrR", 6, l.arg[0]) >= 6) dieusage() ;
          updown[1] = l.arg[0] ;
          break ;
        }
        default : dieusage() ;
      }
    }
    argc -= l.ind ; argv += l.ind ;
  }
  if (!argc) dieusage() ;
  if (argc > 1) strerr_warn1x("ignoring extra arguments") ;

  if (datalen <= 1) return 0 ;
  if (updown[1] == 'U' || updown[1] == 'R')
  {
    unsigned int arglen = str_len(argv[0]) ;
    char fn[arglen + 17] ;
    byte_copy(fn, arglen, argv[0]) ;
    byte_copy(fn + arglen, 17, "/notification-fd") ;
    if (access(fn, F_OK) < 0)
    {
      if (errno != ENOENT) strerr_diefu2sys(111, "access ", fn) ;
      updown[1] = updown[1] == 'U' ? 'u' : 'r' ;
      strerr_warnw2x(fn, " not present - ignoring request for readiness notification") ;
    }
  }

  if (updown[1])
  {
    char const *newargv[11] ;
    unsigned int m = 0 ;
    char fmt[UINT_FMT] ;
    newargv[m++] = S6_BINPREFIX "s6-svlisten1" ;
    newargv[m++] = updown ;
    if (timeout)
    {
      fmt[uint_fmt(fmt, timeout)] = 0 ;
      newargv[m++] = "-t" ;
      newargv[m++] = fmt ;
    }
    newargv[m++] = "--" ;
    newargv[m++] = argv[0] ;
    newargv[m++] = S6_BINPREFIX "s6-svc" ;
    newargv[m++] = data ;
    newargv[m++] = "--" ;
    newargv[m++] = argv[0] ;
    newargv[m++] = 0 ;
    pathexec_run(newargv[0], newargv, envp) ;
    strerr_dieexec(111, newargv[0]) ;
  }
  else
  {
    register int r = s6_svc_writectl(argv[0], S6_SUPERVISE_CTLDIR, data + 1, datalen - 1) ;
    if (r < 0) strerr_diefu2sys(111, "control ", argv[0]) ;
    else if (!r) strerr_diefu3x(100, "control ", argv[0], ": supervisor not listening") ;
  }
  return 0 ;
}
Esempio n. 10
0
static int
virtual_config_parse_line(struct virtual_parse_context *ctx, const char *line,
			  const char **error_r)
{
	struct mail_user *user = ctx->mbox->storage->storage.user;
	struct virtual_backend_box *bbox;
	const char *name;

	if (*line == ' ' || *line == '\t') {
		/* continues the previous search rule */
		if (ctx->rule_idx == array_count(&ctx->mbox->backend_boxes)) {
			*error_r = "Search rule without a mailbox";
			return -1;
		}
		while (*line == ' ' || *line == '\t') line++;
		str_append_c(ctx->rule, ' ');
		str_append(ctx->rule, line);
		return 0;
	}
	/* if there is no rule yet, it means we want the previous mailboxes
	   to use the rule that comes later */
	if (str_len(ctx->rule) > 0) {
		if (virtual_config_add_rule(ctx, error_r) < 0)
			return -1;
	}

	/* new mailbox. the search args are added to it later. */
	bbox = p_new(ctx->pool, struct virtual_backend_box, 1);
	if (strcasecmp(line, "INBOX") == 0)
		line = "INBOX";
	bbox->name = p_strdup(ctx->pool, line);
	if (*line == '-' || *line == '+' || *line == '!') line++;
	bbox->ns = strcasecmp(line, "INBOX") == 0 ?
		mail_namespace_find_inbox(user->namespaces) :
		mail_namespace_find(user->namespaces, line);
	if (!uni_utf8_str_is_valid(bbox->name)) {
		*error_r = t_strdup_printf("Mailbox name not UTF-8: %s",
					   bbox->name);
		return -1;
	}
	if (bbox->ns == NULL) {
		*error_r = t_strdup_printf("Namespace not found for %s",
					   bbox->name);
		return -1;
	}
	if (bbox->name[0] == '+') {
		bbox->name++;
		bbox->clear_recent = TRUE;
	}

	if (strchr(bbox->name, '*') != NULL ||
	    strchr(bbox->name, '%') != NULL) {
		name = bbox->name[0] == '-' ? bbox->name + 1 : bbox->name;
		bbox->glob = imap_match_init(ctx->pool, name, TRUE, ctx->sep);
		ctx->have_wildcards = TRUE;
	} else if (bbox->name[0] == '!') {
		/* save messages here */
		if (ctx->mbox->save_bbox != NULL) {
			*error_r = "Multiple save mailboxes defined";
			return -1;
		}
		bbox->name++;
		ctx->mbox->save_bbox = bbox;
	}
	if (strcmp(bbox->name, ctx->mbox->box.vname) == 0) {
		*error_r = "Virtual mailbox can't point to itself";
		return -1;
	}
	ctx->have_mailbox_defines = TRUE;
	array_append(&ctx->mbox->backend_boxes, &bbox, 1);
	return 0;
}
Esempio n. 11
0
int mailbox_list_delete_mailbox_nonrecursive(struct mailbox_list *list,
					     const char *name, const char *path,
					     bool rmdir_path)
{
	DIR *dir;
	struct dirent *d;
	string_t *full_path;
	unsigned int dir_len;
	bool mailbox_dir, unlinked_something = FALSE;

	if (mailbox_list_check_root_delete(list, name, path) < 0)
		return -1;

	dir = opendir(path);
	if (dir == NULL) {
		if (errno == ENOENT) {
			mailbox_list_set_error(list, MAIL_ERROR_NOTFOUND,
				T_MAIL_ERR_MAILBOX_NOT_FOUND(name));
		} else {
			if (!mailbox_list_set_error_from_errno(list)) {
				mailbox_list_set_critical(list,
					"opendir(%s) failed: %m", path);
			}
		}
		return -1;
	}

	full_path = t_str_new(256);
	str_append(full_path, path);
	str_append_c(full_path, '/');
	dir_len = str_len(full_path);

	for (errno = 0; (d = readdir(dir)) != NULL; errno = 0) {
		if (d->d_name[0] == '.') {
			/* skip . and .. */
			if (d->d_name[1] == '\0')
				continue;
			if (d->d_name[1] == '.' && d->d_name[2] == '\0')
				continue;
		}

		mailbox_dir = list->v.is_internal_name != NULL &&
			list->v.is_internal_name(list, d->d_name);

		str_truncate(full_path, dir_len);
		str_append(full_path, d->d_name);

		if (mailbox_dir) {
			if (unlink_directory(str_c(full_path), TRUE) < 0) {
				mailbox_list_set_critical(list,
					"unlink_directory(%s) failed: %m",
					str_c(full_path));
			} else {
				unlinked_something = TRUE;
			}
			continue;
		}

		/* trying to unlink() a directory gives either EPERM or EISDIR
		   (non-POSIX). it doesn't really work anywhere in practise,
		   so don't bother stat()ing the file first */
		if (unlink(str_c(full_path)) == 0)
			unlinked_something = TRUE;
		else if (errno != ENOENT && errno != EISDIR && errno != EPERM) {
			mailbox_list_set_critical(list,
				"unlink_directory(%s) failed: %m",
				str_c(full_path));
		}
	}
	if (errno != 0)
		mailbox_list_set_critical(list, "readdir(%s) failed: %m", path);
	if (closedir(dir) < 0) {
		mailbox_list_set_critical(list, "closedir(%s) failed: %m",
					  path);
	}

	if (rmdir_path) {
		if (rmdir(path) == 0)
			unlinked_something = TRUE;
		else if (errno != ENOENT &&
			 errno != ENOTEMPTY && errno != EEXIST) {
			mailbox_list_set_critical(list, "rmdir(%s) failed: %m",
						  path);
			return -1;
		}
	}

	if (!unlinked_something) {
		mailbox_list_set_error(list, MAIL_ERROR_NOTPOSSIBLE,
				       "Mailbox has children, can't delete it");
		return -1;
	}
	return 0;
}
Esempio n. 12
0
void run_command() {
	is_cmd = 1;
	int size = str_len(command);
	if(str_startswith(command, "hlt") == 1) {
		text_color(BLACK, BLACK);
		clear_screen();
		halt();
	} else if(str_startswith(command, "println")) {
		putslns(command, 8, size);
	} else if(str_startswith(command, "printvln")) {
		if(letti(command[9]) != -1)
			putnumln(reg[letti(command[9])]);
	} else if(str_startswith(command, "printv")) {
		if(letti(command[7]) != -1)
			putnum(reg[letti(command[7])]);
	} else if(str_startswith(command, "print")) {
		putss(command, 6, size);
	} else if (str_startswith(command, "clear")) {
		clear_screen();
		index = 0;
    } else if(str_startswith(command, "setv")) {
		if(letti(command[5]) != -1) {
			int r = letti(command[5]);
			
			int i = 0;
			while(i < 7) {
				command[i] = ' ';
				i++;
			}
			
			reg[r] = atoi(command);
		}
	} else if(str_startswith(command, "add")) {
		if(letti(command[4])!=-1 && letti(command[6])!=-1)
			reg[letti(command[4])] += reg[letti(command[6])];
	} else if(str_startswith(command, "sub")) {
		if(letti(command[4])!=-1 && letti(command[6])!=-1)
			reg[letti(command[4])] -= reg[letti(command[6])];
	} else if(str_startswith(command, "mul")) {
		if(letti(command[4])!=-1 && letti(command[6])!=-1)
			reg[letti(command[4])] *= reg[letti(command[6])];
	} else if(str_startswith(command, "div")) {
		if(letti(command[4])!=-1 && letti(command[6])!=-1)
			reg[letti(command[4])] /= reg[letti(command[6])];
	} else if(str_startswith(command, "mod")) {
		if(letti(command[4])!=-1 && letti(command[6])!=-1)
			reg[letti(command[4])] %= reg[letti(command[6])];
	} else if(str_startswith(command, "cc") == 1) {
		if(str_startswith(command, "cc help")) {
			putsln("Colors:");
			putsln(">>> BLACK       :: 0");
			putsln(">>> BLUE        :: 1");
			putsln(">>> GREEN       :: 2");
			putsln(">>> CYAN        :: 3");
			putsln(">>> RED         :: 4");
			putsln(">>> MAGENTA     :: 5");
			putsln(">>> BROWN       :: 6");
			putsln(">>> LT GRAY     :: 7");
			putsln(">>> DK GRAY     :: 8");
			putsln(">>> LT BLUE     :: 9");
			putsln(">>> LT GREEN    :: A");
			putsln(">>> LT CYAN     :: B");
			putsln(">>> LT RED      :: C");
			putsln(">>> LT MAGENTA  :: D");
			putsln(">>> LT BROWN    :: E");
			putsln(">>> WHITE       :: F");
		} else {
			char b = command[4];
			char f = command[3];
			if(f > '@' && b > '@')
				text_color(f - '0', b - 55);
			else if(f > '@')
				text_color(f - 55, b - '0');
			else if(b > '@')
				text_color(f - '0', b - 55);
			else
				text_color(f - '0', b - '0');
		}
	} else if(str_startswith(command, "help") == 1) {
		putsln("Commands:");
		putsln(">>> hlt          :: halts cpu");
		putsln(">>> cc fb|help   :: change text color - (fore, back)");
		putsln(">>> print text   :: print out a piece of text");
		putsln(">>> printv let   :: print out the value of variable let");
		putsln(">>> printvln let :: print out the value of variable let with a line after");
		putsln(">>> println text :: print out a piece of text with a line");
		putsln(">>> clear        :: Clears the screen");
		putsln(">>> setv let val :: set variable let to val");
		putsln(">>> add base set :: adds base to set and stores in base");
		putsln(">>> sub base set :: subtracts base from set and stores in base");
		putsln(">>> mul base set :: multiplies base by set and stores in base");
		putsln(">>> div base set :: divides base by set and stores in set");
		putsln(">>> mod base set :: divides base by set and stores remainder in set");
		putsln(">>> println text :: print out a piece of text with a line");
		putsln(">>> help         :: show help command");
	} else {
		puts(">>> Unknown command: ");
		putsln(command);
		putsln(">>> Try help.");
	}
	clear_command();
	
	is_cmd = 0;
}
main()
{
	str_len();
}
Esempio n. 14
0
int imap_proxy_parse_line(struct client *client, const char *line)
{
	struct imap_client *imap_client = (struct imap_client *)client;
	struct ostream *output;
	string_t *str;
	const unsigned char *data;
	size_t data_len;
	const char *error;
	int ret;

	i_assert(!client->destroyed);

	output = login_proxy_get_ostream(client->login_proxy);
	if (!imap_client->proxy_seen_banner) {
		/* this is a banner */
		imap_client->proxy_rcvd_state = IMAP_PROXY_RCVD_STATE_BANNER;
		imap_client->proxy_seen_banner = TRUE;
		if (proxy_input_banner(imap_client, output, line) < 0) {
			client_proxy_failed(client, TRUE);
			return -1;
		}
		return 0;
	} else if (*line == '+') {
		/* AUTHENTICATE started. finish it. */
		if (client->proxy_sasl_client == NULL) {
			/* used literals with LOGIN command, just ignore. */
			return 0;
		}
		imap_client->proxy_sent_state &= ~IMAP_PROXY_SENT_STATE_AUTHENTICATE;
		imap_client->proxy_rcvd_state = IMAP_PROXY_RCVD_STATE_AUTH_CONTINUE;

		str = t_str_new(128);
		if (line[1] != ' ' ||
		    base64_decode(line+2, strlen(line+2), NULL, str) < 0) {
			client_log_err(client,
				"proxy: Server sent invalid base64 data in AUTHENTICATE response");
			client_proxy_failed(client, TRUE);
			return -1;
		}
		ret = dsasl_client_input(client->proxy_sasl_client,
					 str_data(str), str_len(str), &error);
		if (ret == 0) {
			ret = dsasl_client_output(client->proxy_sasl_client,
						  &data, &data_len, &error);
		}
		if (ret < 0) {
			client_log_err(client, t_strdup_printf(
				"proxy: Server sent invalid authentication data: %s",
				error));
			client_proxy_failed(client, TRUE);
			return -1;
		}
		i_assert(ret == 0);

		str_truncate(str, 0);
		base64_encode(data, data_len, str);
		str_append(str, "\r\n");

		imap_client->proxy_sent_state |= IMAP_PROXY_SENT_STATE_AUTH_CONTINUE;
		o_stream_nsend(output, str_data(str), str_len(str));
		return 0;
	} else if (str_begins(line, "S ")) {
		imap_client->proxy_sent_state &= ~IMAP_PROXY_SENT_STATE_STARTTLS;
		imap_client->proxy_rcvd_state = IMAP_PROXY_RCVD_STATE_STARTTLS;

		if (!str_begins(line, "S OK ")) {
			/* STARTTLS failed */
			client_log_err(client, t_strdup_printf(
				"proxy: Remote STARTTLS failed: %s",
				str_sanitize(line + 5, 160)));
			client_proxy_failed(client, TRUE);
			return -1;
		}
		/* STARTTLS successful, begin TLS negotiation. */
		if (login_proxy_starttls(client->login_proxy) < 0) {
			client_proxy_failed(client, TRUE);
			return -1;
		}
		/* i/ostreams changed. */
		output = login_proxy_get_ostream(client->login_proxy);
		str = t_str_new(128);
		if (proxy_write_login(imap_client, str) < 0) {
			client_proxy_failed(client, TRUE);
			return -1;
		}
		o_stream_nsend(output, str_data(str), str_len(str));
		return 1;
	} else if (str_begins(line, "L OK ")) {
		/* Login successful. Send this line to client. */
		imap_client->proxy_sent_state &= ~IMAP_PROXY_SENT_STATE_LOGIN;
		imap_client->proxy_rcvd_state = IMAP_PROXY_RCVD_STATE_LOGIN;
		str = t_str_new(128);
		client_send_login_reply(imap_client, str, line + 5);
		o_stream_nsend(client->output, str_data(str), str_len(str));

		client_proxy_finish_destroy_client(client);
		return 1;
	} else if (str_begins(line, "L ")) {
		imap_client->proxy_sent_state &= ~IMAP_PROXY_SENT_STATE_LOGIN;
		imap_client->proxy_rcvd_state = IMAP_PROXY_RCVD_STATE_LOGIN;

		line += 2;
		if (client->set->auth_verbose) {
			const char *log_line = line;

			if (strncasecmp(log_line, "NO ", 3) == 0)
				log_line += 3;
			client_proxy_log_failure(client, log_line);
		}
#define STR_NO_IMAP_RESP_CODE_AUTHFAILED "NO ["IMAP_RESP_CODE_AUTHFAILED"]"
		if (str_begins(line, STR_NO_IMAP_RESP_CODE_AUTHFAILED)) {
			/* the remote sent a generic "authentication failed"
			   error. replace it with our one, so that in case
			   the remote is sending a different error message
			   an attacker can't find out what users exist in
			   the system. */
			client_send_reply_code(client, IMAP_CMD_REPLY_NO,
					       IMAP_RESP_CODE_AUTHFAILED,
					       AUTH_FAILED_MSG);
		} else if (str_begins(line, "NO [")) {
			/* remote sent some other resp-code. forward it. */
			client_send_raw(client, t_strconcat(
				imap_client->cmd_tag, " ", line, "\r\n", NULL));
		} else {
			/* there was no [resp-code], so remote isn't Dovecot
			   v1.2+. we could either forward the line as-is and
			   leak information about what users exist in this
			   system, or we could hide other errors than password
			   failures. since other errors are pretty rare,
			   it's safer to just hide them. they're still
			   available in logs though. */
			client_send_reply_code(client, IMAP_CMD_REPLY_NO,
					       IMAP_RESP_CODE_AUTHFAILED,
					       AUTH_FAILED_MSG);
		}

		client->proxy_auth_failed = TRUE;
		client_proxy_failed(client, FALSE);
		return -1;
	} else if (strncasecmp(line, "* CAPABILITY ", 13) == 0) {
		i_free(imap_client->proxy_backend_capability);
		imap_client->proxy_backend_capability = i_strdup(line + 13);
		return 0;
	} else if (str_begins(line, "C ")) {
		/* Reply to CAPABILITY command we sent */
		imap_client->proxy_sent_state &= ~IMAP_PROXY_SENT_STATE_CAPABILITY;
		imap_client->proxy_rcvd_state = IMAP_PROXY_RCVD_STATE_CAPABILITY;
		if (str_begins(line, "C OK ") &&
		    client->proxy_password != NULL) {
			/* pipelining was disabled, send the login now. */
			str = t_str_new(128);
			if (proxy_write_login(imap_client, str) < 0)
				return -1;
			o_stream_nsend(output, str_data(str), str_len(str));
			return 1;
		}
		return 0;
	} else if (strncasecmp(line, "I ", 2) == 0) {
		/* Reply to ID command we sent, ignore it unless
		   pipelining is disabled, in which case send
		   either STARTTLS or login */
		imap_client->proxy_sent_state &= ~IMAP_PROXY_SENT_STATE_ID;
		imap_client->proxy_rcvd_state = IMAP_PROXY_RCVD_STATE_ID;

		if (client->proxy_nopipelining) {
			str = t_str_new(128);
			if ((ret = proxy_write_starttls(imap_client, str)) < 0) {
				return -1;
			} else if (ret == 0) {
				if (proxy_write_login(imap_client, str) < 0)
					return -1;
			}
			o_stream_nsend(output, str_data(str), str_len(str));
			return 1;
		}
		return 0;
	} else if (strncasecmp(line, "* ID ", 5) == 0) {
		/* Reply to ID command we sent, ignore it */
		return 0;
	} else if (str_begins(line, "* ")) {
		/* untagged reply. just forward it. */
		client_send_raw(client, t_strconcat(line, "\r\n", NULL));
		return 0;
	} else {
		/* tagged reply, shouldn't happen. */
		client_log_err(client, t_strdup_printf(
			"proxy: Unexpected input, ignoring: %s",
			str_sanitize(line, 160)));
		return 0;
	}
}
Esempio n. 15
0
int main(int argc,char* argv[]) {
  static critbit0_tree t;
  assert(critbit0_insert(&t,"fnord")==2);
  assert(critbit0_insert(&t,"fnord2")==2);
  assert(critbit0_insert(&t,"fnord2")==1);
  assert(critbit0_contains(&t,"foo")==0);
  assert(critbit0_contains(&t,"fnord")==1);
  assert(critbit0_allprefixed(&t,"fnord",ret1,NULL)==1);
  assert(critbit0_allprefixed(&t,"fnord",ret0,NULL)==0);
  assert(critbit0_delete(&t,"fnord2")==1);
  assert(critbit0_delete(&t,"foo")==0);
#if 0
  int s = socket_tcp6();
#endif
#if 0
  iarray i;
  iarray_init(&i,sizeof(size_t));
  printf("%p\n",iarray_get(&i,0));
  printf("%p\n",iarray_allocate(&i,0));
  printf("%p\n",iarray_allocate(&i,0));
  printf("%p\n",iarray_get(&i,0));
#endif
#if 0
  char buf[1024];
  size_t l;
  unsigned char c;
  (void)writecb;
  printf("%d\n",(c=scan_fromhex('.')));
  (void)argc;
  (void)argv;
  assert(fmt_jsonescape(buf,"foo\nbar\\",8)==14 && byte_equal(buf,14,"foo\\u000abar\\\\"));
  memset(buf,0,sizeof(buf));
  assert(scan_jsonescape("foo\\u000abar\\\\",buf,&l)==14 && l==8 && byte_equal(buf,8,"foo\nbar\\"));
  memset(buf,0,sizeof(buf));
  /* example from the json spec: G clef U+1D11E encoded using UTF-16 surrogates*/
  assert(scan_jsonescape("\\uD834\\uDD1Exyz",buf,&l)==15 && l==7 && byte_equal(buf,7,"\xf4\x8d\x84\x9exyz"));

/*
	 1D11E -> 0001 1101 0001 0001 1110
	       -> ______00 __011101 __000100 __011110
	 as utf8: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
	          11110000 10011101 10000100 10011110
		  f   0    9   d    8   4    9   e
*/

#endif
#if 0
  static size_t x;
  x=23;
  atomic_add(&x,3);
  printf("%u\n",x);
  printf("%u\n",atomic_add_return(&x,-3));
  printf("%u\n",compare_and_swap(&x,26,17));
  printf("%u\n",compare_and_swap(&x,23,17));
#endif

#if 0
  atomic_add(&x,3); printf("%u\n",x);
  x=23;
  atomic_add(&x,3); assert(x==26);
  atomic_or(&x,1); assert(x==27);
  atomic_and(&x,-2); assert(x==26);
#endif

#if 0
  iarray a;
  char* c;
  iarray_init(&a,sizeof(io_entry));
  printf("15 -> %p\n",c=iarray_allocate(&a,15));
  printf("23 -> %p\n",c=iarray_allocate(&a,23));
  printf("1234567 -> %p\n",c=iarray_allocate(&a,1234567));
  printf("23 -> %p\n",iarray_get(&a,23));
#endif
#if 0
  io_batch* b=iob_new(1234);
  int64 fd=open("t.c",0);
  iob_addbuf(b,"fnord",5);
  iob_addfile_close(b,fd,0,7365);
  iob_write(1,b,writecb);
#endif
#if 0
  char dest[1024];
  unsigned long len;
  scan_urlencoded2("libstdc++.tar.gz",dest,&len);
  buffer_putmflush(buffer_1,dest,"\n");
#endif
#if 0
  static stralloc sa;
  stralloc_copym(&sa,"foo ","bar ","baz.\n");
  write(1,sa.s,sa.len);
#endif
#if 0
  buffer_putmflush(buffer_1,"foo ","bar ","baz.\n");
#endif
#if 0
  char* c="fnord";
  int fd=open_read(c);
  errmsg_iam(argv[0]);
  carp("could not open file `",c,"'");
  diesys(23,"could not open file `",c,"'");
#endif
#if 0
  errmsg_warn("could not open file `",c,"'",0);
  errmsg_warnsys("could not open file `",c,"'",0);
#endif
#if 0
  char buf[100]="/usr/bin/sh";
  int len=str_len(buf);
  assert(byte_rchr(buf,len,'/')==8);
  assert(byte_rchr(buf,len,'@')==len);
  assert(byte_rchr(buf,len,'h')==len-1);
  printf("%d\n",byte_rchr("x",1,'x'));
#endif
#if 0
  char buf[IP6_FMT+100];
  int i;
  char ip[16];
  uint32 scope_id;
  char* s="fec0::1:220:e0ff:fe69:ad92%eth0/64";
  char blubip[16]="\0\0\0\0\0\0\0\0\0\0\xff\xff\x7f\0\0\001";
  i=scan_ip6if(s,ip,&scope_id);
  assert(s[i]=='/');
  buffer_put(buffer_1,buf,fmt_ip6if(buf,ip,scope_id));
  buffer_putnlflush(buffer_1);
  buffer_put(buffer_1,buf,fmt_ip6ifc(buf,blubip,scope_id));
  buffer_putnlflush(buffer_1);
  scan_ip6("2001:7d0:0:f015:0:0:0:1",ip);
  buffer_put(buffer_1,buf,fmt_ip6(buf,ip));
  buffer_putnlflush(buffer_1);
#endif
#if 0
  char buf[100];
  int i;
  printf("%d\n",i=fmt_pad(buf,"fnord",5,7,10));
  buf[i]=0;
  puts(buf);
#endif
#if 0
  char ip[16];
  char buf[32];
  printf("%d (expect 2)\n",scan_ip6("::",ip));
  printf("%d (expect 3)\n",scan_ip6("::1",ip));
  printf("%d (expect 16)\n",scan_ip6("fec0:0:0:ffff::1/0",ip));
  printf("%.*s\n",fmt_ip6(buf,ip),buf);
#endif
#if 0
  static stralloc s,t;
  stralloc_copys(&s,"fnord");
  stralloc_copys(&t,"abc"); printf("%d\n",stralloc_diff(&s,&t));
  stralloc_copys(&t,"fnor"); printf("%d\n",stralloc_diff(&s,&t));
  stralloc_copys(&t,"fnord"); printf("%d\n",stralloc_diff(&s,&t));
  stralloc_copys(&t,"fnordh"); printf("%d\n",stralloc_diff(&s,&t));
  stralloc_copys(&t,"hausen"); printf("%d\n",stralloc_diff(&s,&t));
#endif
#if 0
  static stralloc s;
  stralloc_copys(&s,"fnord");
  printf("%d\n",stralloc_diffs(&s,"abc"));
  printf("%d\n",stralloc_diffs(&s,"fnor"));
  printf("%d\n",stralloc_diffs(&s,"fnord"));
  printf("%d\n",stralloc_diffs(&s,"fnordh"));
  printf("%d\n",stralloc_diffs(&s,"hausen"));
#endif
#if 0
  printf("%d\n",case_starts("fnordhausen","FnOrD"));
  printf("%d\n",case_starts("fnordhausen","blah"));
#endif
#if 0
  char buf[]="FnOrD";
  case_lowers(buf);
  puts(buf);
#endif
#if 0
  char buf[100]="foo bar baz";
  printf("%d (expect 7)\n",byte_rchr(buf,11,' '));
#endif
#if 0
  unsigned long size;
  char* buf=mmap_read(argv[1],&size);
  if (buf) {
    unsigned int x=fmt_yenc(0,buf,size);
    unsigned int y;
    char* tmp=malloc(x+1);
    y=fmt_yenc(tmp,buf,size);
    write(1,tmp,x);
  }
#endif
#if 0
  char buf[100];
  char buf2[100];
  unsigned int len,len2;
  buf[fmt_yenc(buf,"http://localhost/~fefe",22)]=0;
  buffer_puts(buffer_1,buf);
  buffer_putsflush(buffer_1,"\n");
  if ((buf[len2=scan_yenc(buf,buf2,&len)])!='\n') {
    buffer_putsflush(buffer_2,"parse error!\n");
    return 1;
  }
  buffer_put(buffer_1,buf2,len2);
  buffer_putsflush(buffer_1,"\n");
  return 0;
#endif
#if 0
  char buf[100];
  char buf2[100];
  unsigned int len,len2;
  buf[fmt_base64(buf,"foo:bar",7)]=0;
  buffer_puts(buffer_1,buf);
  buffer_putsflush(buffer_1,"\n");
  if ((buf[len2=scan_base64(buf,buf2,&len)])!=0) {
    buffer_putsflush(buffer_2,"parse error!\n");
    return 1;
  }
  buffer_put(buffer_1,buf2,len2);
  buffer_putsflush(buffer_1,"\n");
  return 0;
#endif
#if 0
  unsigned long size;
  char* buf=mmap_read(argv[1],&size);
  if (buf) {
    unsigned int x=fmt_uuencoded(0,buf,size);
    unsigned int y;
    char* tmp=malloc(x+1);
    y=fmt_uuencoded(tmp,buf,size);
    write(1,tmp,x);
  }
#endif
#if 0
  char buf[]="00000000000000000000000000000001";
  char ip[16];
  if (scan_ip6_flat(buf,ip) != str_len(buf))
    buffer_putsflush(buffer_2,"parse error!\n");
#endif
#if 0
  int fd=open_read("t.c");
  buffer b;
  char buf[1024];
  char line[20];
  int i;
  buffer_init(&b,read,fd,buf,1024);
  i=buffer_getline(&b,line,19);
  buffer_puts(buffer_1,"getline returned ");
  buffer_putulong(buffer_1,i);
  buffer_puts(buffer_1,"\n");
  buffer_puts(buffer_1,line);
  buffer_flush(buffer_1);
#endif
#if 0
  buffer_putulong(buffer_1,23);
//  buffer_putspace(buffer_1);
  buffer_putsflush(buffer_1,"\n");
//  buffer_flush(buffer_1);
#endif
#if 0
  long a,b,c;
  char buf[4096];
  char buf2[4096];
  memcpy(buf,buf2,4096);
  byte_copy(buf,4096,buf2);
  rdtscl(a);
  memcpy(buf,buf2,4096);
  rdtscl(b);
  byte_copy(buf,4096,buf2);
  rdtscl(c);
  printf("memcpy: %d - byte_copy: %d\n",b-a,c-b);
#endif
#if 0
  char ip[16];
  int i;
  if ((i=scan_ip6(argv[1],ip))) {
    char buf[128];
    buf[fmt_ip6(buf,ip)]=0;
    puts(buf);
  }
#endif
#if 0
  char buf[100];
  strcpy(buf,"foobarbaz");
  buf[fmt_fill(buf,3,5,100)]=0;
  printf("\"%s\"\n",buf);
#endif
#if 0
  unsigned long len;
  char *c=mmap_read("/etc/passwd",&len);
  printf("got map %p of len %lu\n",c,len);
#endif
#if 0
  char c;
  printf("%d\n",buffer_getc(buffer_0,&c));
  printf("%c\n",c);
#endif
#if 0
  char buf[100]="01234567890123456789012345678901234567890123456789";
  long a,b,c;
#endif
#if 0
  buf[ip4_fmt(buf,ip4loopback)]=0;
  buffer_puts(buffer_1small,buf);
  buffer_flush(buffer_1small);
#endif

#if 0
  buf[0]=0;
  buf[fmt_8long(buf,0)]=0;
  puts(buf);
  rdtscl(a);
  c=str_len(buf);
  rdtscl(b);
  /*byte_zero_djb(buf,j); */
//  printf("\n%lu %d\n",b-a,c);
#endif
#if 0
  buffer_puts(buffer_1small,"hello, world\n");
  buffer_flush(buffer_1small);
#endif
#if 0
  int s=socket_tcp4();
  char ip[4]={127,0,0,1};
  int t=socket_connect4(s,ip,80);
#endif
#if 0
  char buf[100]="foo bar baz fnord   ";
  char buf2[100]="foo braz fnord";
  long a,b,c;
  long i=0,j=0,k=0;
  double d;
  uint32 l,m,n;
  stralloc sa={0};
  stralloc_copys(&sa,"fnord");
  stralloc_catlong0(&sa,-23,5);
  stralloc_append(&sa,"\n");
  printf("%d %d\n",str_equal("fnord","fnord1"),str_equal("fnord1","fnord"));
  write(1,sa.s,sa.len);
  printf("%d %d\n",stralloc_starts(&sa,"fnord"),stralloc_starts(&sa,"fnord\na"));

  l=0xdeadbeef;
  uint32_pack_big((char*)&m,l);
  uint32_unpack_big((char*)&m,&n);
  printf("%x %x %x\n",l,m,n);

  rdtscl(a);
/*  i=scan_double("3.1415",&d); */
  rdtscl(b);
  /*byte_zero_djb(buf,j); */
  rdtscl(c);
  printf("%lu %lu\n",b-a,c-b);
#endif
#if 0
  size_t size;
  char* buf=mmap_read(argv[1],&size);
  if (buf) {
    unsigned int x=fmt_urlencoded2(0,buf,size,"x");
    unsigned int y;
    char* tmp=malloc(x+1);
    y=fmt_urlencoded2(tmp,buf,size,"x");
    write(1,tmp,x);
  }
#endif
#if 0
  printf("%d %d\n",strcmp("foo","bar"),str_diff("foo","bar"));
  printf("%d %d\n",strcmp("foo","\xfcar"),str_diff("foo","\xfcar"));
#endif
#if 0
  {
    int16 a;
    int32 b;
    int64 c;
    assert(imult16(4,10000,&a)==0);
    assert(imult16(-4,10000,&a)==0);
    assert(imult16(5,10,&a)==1 && a==50);
    assert(imult16(-3,10000,&a)==1 && a==-30000);

    assert(imult32(0x40000000,2,&b)==0);
    assert(imult32(0x3fffffff,2,&b)==1 && b==0x7ffffffe);

    assert(imult64(0x4000000000000000ll,2,&c)==0);
    assert(imult64(0x3fffffffffffffffll,2,&c)==1 && c==0x7ffffffffffffffell);
  }
#endif
#if 0
  stralloc a;
  printf("%d\n",stralloc_copym(&a,"fnord",", ","foo"));
#endif

  return 0;
}
Esempio n. 16
0
static int http_client_request_send_real(struct http_client_request *req,
					 const char **error_r)
{
	struct http_client_connection *conn = req->conn;
	struct ostream *output = conn->conn.output;
	string_t *rtext = t_str_new(256);
	struct const_iovec iov[3];
	int ret = 0;

	i_assert(!req->conn->output_locked);
	i_assert(req->payload_output == NULL);

	/* create request line */
	str_append(rtext, req->method);
	str_append(rtext, " ");
	str_append(rtext, req->target);
	str_append(rtext, " HTTP/1.1\r\n");

	/* create special headers implicitly if not set explicitly using
	   http_client_request_add_header() */
	if (!req->have_hdr_host) {
		str_append(rtext, "Host: ");
		str_append(rtext, req->authority);
		str_append(rtext, "\r\n");
	}
	if (!req->have_hdr_date) {
		str_append(rtext, "Date: ");
		str_append(rtext, http_date_create(req->date));
		str_append(rtext, "\r\n");
	}
	if (!req->have_hdr_user_agent && req->client->set.user_agent != NULL) {
		str_printfa(rtext, "User-Agent: %s\r\n",
			    req->client->set.user_agent);
	}
	if (!req->have_hdr_expect && req->payload_sync) {
		str_append(rtext, "Expect: 100-continue\r\n");
	}
	if (req->payload_chunked) {
		// FIXME: can't do this for a HTTP/1.0 server
		if (!req->have_hdr_body_spec)
			str_append(rtext, "Transfer-Encoding: chunked\r\n");
		req->payload_output =
			http_transfer_chunked_ostream_create(output);
	} else if (req->payload_input != NULL) {
		/* send Content-Length if we have specified a payload,
		   even if it's 0 bytes. */
		if (!req->have_hdr_body_spec) {
			str_printfa(rtext, "Content-Length: %"PRIuUOFF_T"\r\n",
				req->payload_size);
		}
		req->payload_output = output;
		o_stream_ref(output);
	}
	if (!req->have_hdr_connection && req->host_url == &req->origin_url) {
		/* https://tools.ietf.org/html/rfc2068
		     Section 19.7.1:

		   A client MUST NOT send the Keep-Alive connection token to a proxy
		   server as HTTP/1.0 proxy servers do not obey the rules of HTTP/1.1
		   for parsing the Connection header field.
		 */
		str_append(rtext, "Connection: Keep-Alive\r\n");
	}

	/* request line + implicit headers */
	iov[0].iov_base = str_data(rtext);
	iov[0].iov_len = str_len(rtext);	
	/* explicit headers */
	if (req->headers != NULL) {
		iov[1].iov_base = str_data(req->headers);
		iov[1].iov_len = str_len(req->headers);
	} else {
		iov[1].iov_base = "";
		iov[1].iov_len = 0;
	}
	/* end of header */
	iov[2].iov_base = "\r\n";
	iov[2].iov_len = 2;

	req->state = HTTP_REQUEST_STATE_PAYLOAD_OUT;
	o_stream_cork(output);
	if (o_stream_sendv(output, iov, N_ELEMENTS(iov)) < 0) {
		*error_r = t_strdup_printf("write(%s) failed: %s",
					   o_stream_get_name(output),
					   o_stream_get_error(output));
		ret = -1;
	}

	http_client_request_debug(req, "Sent header");

	if (ret >= 0 && req->payload_output != NULL) {
		if (!req->payload_sync) {
			if (http_client_request_send_more(req, error_r) < 0)
				ret = -1;
		} else {
			http_client_request_debug(req, "Waiting for 100-continue");
			conn->output_locked = TRUE;
		}
	} else {
		req->state = HTTP_REQUEST_STATE_WAITING;
		conn->output_locked = FALSE;
	}
	o_stream_uncork(output);
	return ret;
}
Esempio n. 17
0
int mail_send_rejection(struct mail_deliver_context *ctx, const char *recipient,
			const char *reason)
{
    struct mail *mail = ctx->src_mail;
    struct istream *input;
    struct smtp_client *smtp_client;
    struct ostream *output;
    const char *return_addr, *hdr;
    const char *value, *msgid, *orig_msgid, *boundary, *error;
    string_t *str;
    int ret;

    if (mail_get_first_header(mail, "Message-ID", &orig_msgid) < 0)
	    orig_msgid = NULL;

    if (mail_get_first_header(mail, "Auto-Submitted", &value) > 0 &&
	strcasecmp(value, "no") != 0) {
	    i_info("msgid=%s: Auto-submitted message discarded: %s",
		   orig_msgid == NULL ? "" : str_sanitize(orig_msgid, 80),
		   str_sanitize(reason, 512));
	    return 0;
    }

    return_addr = mail_deliver_get_return_address(ctx);
    if (return_addr == NULL) {
	    i_info("msgid=%s: Return-Path missing, rejection reason: %s",
		   orig_msgid == NULL ? "" : str_sanitize(orig_msgid, 80),
		   str_sanitize(reason, 512));
	    return 0;
    }

    if (mailbox_get_settings(mail->box)->mail_debug) {
	    i_debug("Sending a rejection to %s: %s", recipient,
		    str_sanitize(reason, 512));
    }

    smtp_client = smtp_client_init(ctx->set, NULL);
    smtp_client_add_rcpt(smtp_client, return_addr);
    output = smtp_client_send(smtp_client);

    msgid = mail_deliver_get_new_message_id(ctx);
    boundary = t_strdup_printf("%s/%s", my_pid, ctx->set->hostname);

    str = t_str_new(512);
    str_printfa(str, "Message-ID: %s\r\n", msgid);
    str_printfa(str, "Date: %s\r\n", message_date_create(ioloop_time));
    str_printfa(str, "From: Mail Delivery Subsystem <%s>\r\n",
		ctx->set->postmaster_address);
    str_printfa(str, "To: <%s>\r\n", return_addr);
    str_append(str, "MIME-Version: 1.0\r\n");
    str_printfa(str, "Content-Type: "
		"multipart/report; report-type=%s;\r\n"
		"\tboundary=\"%s\"\r\n",
		ctx->dsn ? "delivery-status" : "disposition-notification",
		boundary);
    str_append(str, "Subject: ");
    var_expand(str, ctx->set->rejection_subject,
	       get_var_expand_table(mail, reason, recipient));
    str_append(str, "\r\n");

    str_append(str, "Auto-Submitted: auto-replied (rejected)\r\n");
    str_append(str, "Precedence: bulk\r\n");
    str_append(str, "\r\nThis is a MIME-encapsulated message\r\n\r\n");

    /* human readable status report */
    str_printfa(str, "--%s\r\n", boundary);
    str_append(str, "Content-Type: text/plain; charset=utf-8\r\n");
    str_append(str, "Content-Disposition: inline\r\n");
    str_append(str, "Content-Transfer-Encoding: 8bit\r\n\r\n");

    var_expand(str, ctx->set->rejection_reason,
	       get_var_expand_table(mail, reason, recipient));
    str_append(str, "\r\n");

    if (ctx->dsn) {
	    /* DSN status report: For LDA rejects. currently only used when
	       user is out of quota */
	    str_printfa(str, "--%s\r\n"
			"Content-Type: message/delivery-status\r\n\r\n",
			boundary);
	    str_printfa(str, "Reporting-MTA: dns; %s\r\n", ctx->set->hostname);
	    if (mail_get_first_header(mail, "Original-Recipient", &hdr) > 0)
		    str_printfa(str, "Original-Recipient: rfc822; %s\r\n", hdr);
	    str_printfa(str, "Final-Recipient: rfc822; %s\r\n", recipient);
	    str_append(str, "Action: failed\r\n");
	    str_printfa(str, "Status: %s\r\n", ctx->mailbox_full ? "5.2.2" : "5.2.0");
    } else {
	    /* MDN status report: For Sieve "reject" */
	    str_printfa(str, "--%s\r\n"
			"Content-Type: message/disposition-notification\r\n\r\n",
			boundary);
	    str_printfa(str, "Reporting-UA: %s; Dovecot Mail Delivery Agent\r\n",
			ctx->set->hostname);
	    if (mail_get_first_header(mail, "Original-Recipient", &hdr) > 0)
		    str_printfa(str, "Original-Recipient: rfc822; %s\r\n", hdr);
	    str_printfa(str, "Final-Recipient: rfc822; %s\r\n", recipient);

	    if (orig_msgid != NULL)
		    str_printfa(str, "Original-Message-ID: %s\r\n", orig_msgid);
	    str_append(str, "Disposition: "
		       "automatic-action/MDN-sent-automatically; deleted\r\n");
    }
    str_append(str, "\r\n");

    /* original message's headers */
    str_printfa(str, "--%s\r\nContent-Type: message/rfc822\r\n\r\n", boundary);
    o_stream_nsend(output, str_data(str), str_len(str));

    if (mail_get_hdr_stream(mail, NULL, &input) == 0) {
	    /* Note: If you add more headers, they need to be sorted.
	       We'll drop Content-Type because we're not including the message
	       body, and having a multipart Content-Type may confuse some
	       MIME parsers when they don't see the message boundaries. */
	    static const char *const exclude_headers[] = {
		    "Content-Type"
	    };

	    input = i_stream_create_header_filter(input,
	    		HEADER_FILTER_EXCLUDE | HEADER_FILTER_NO_CR |
			HEADER_FILTER_HIDE_BODY, exclude_headers,
			N_ELEMENTS(exclude_headers),
			*null_header_filter_callback, (void *)NULL);

	    ret = o_stream_send_istream(output, input);
	    i_stream_unref(&input);

	    i_assert(ret != 0);
    }

    str_truncate(str, 0);
    str_printfa(str, "\r\n\r\n--%s--\r\n", boundary);
    o_stream_nsend(output, str_data(str), str_len(str));
    if ((ret = smtp_client_deinit(smtp_client, &error)) < 0) {
	    i_error("msgid=%s: Temporarily failed to send rejection: %s",
		    orig_msgid == NULL ? "" : str_sanitize(orig_msgid, 80),
		    str_sanitize(error, 512));
    } else if (ret == 0) {
	    i_info("msgid=%s: Permanently failed to send rejection: %s",
		   orig_msgid == NULL ? "" : str_sanitize(orig_msgid, 80),
		   str_sanitize(error, 512));
    }
    return ret < 0 ? -1 : 0;
}
Esempio n. 18
0
int dcps_get_local_subscription_data (DDS_SubscriptionBuiltinTopicData *dp,
				      Reader_t                         *rp)
{
	size_t		size, psize;
	char		*xp;
	UniQos_t	*uqp;

	size = str_len (rp->r_topic->name);
	size += str_len (rp->r_topic->type->type_name);
	if (rp->r_qos->qos.user_data) {
		ROUND_LEN (size);
		size += str_len (rp->r_qos->qos.user_data);
	}
	if (rp->r_subscriber->qos.partition) {
		ROUND_LEN (size);
		psize = partition_size (rp->r_subscriber->qos.partition);
		size += psize;
	}
	if (rp->r_topic->qos->qos.topic_data) {
		ROUND_LEN (size);
		size += str_len (rp->r_topic->qos->qos.topic_data);
	}
	if (rp->r_subscriber->qos.group_data) {
		ROUND_LEN (size);
		size += str_len (rp->r_subscriber->qos.group_data);
	}
	xp = xmalloc (size);
	if (!xp)
		return (DDS_RETCODE_OUT_OF_RESOURCES);

	dp->topic_name = xp;
	endpoint_key_from_guid (&rp->r_subscriber->domain->participant.p_guid_prefix,
				&rp->r_entity_id,
				(KeyHash_t *) &dp->key);
	memcpy (&dp->participant_key,
		&rp->r_subscriber->domain->participant.p_guid_prefix,
		GUIDPREFIX_SIZE);
	if (sizeof (DDS_BuiltinTopicKey_t) > GUIDPREFIX_SIZE)
		dp->participant_key.value [3] = 0;
	memcpy (xp, str_ptr (rp->r_topic->name),
				str_len (rp->r_topic->name));
	xp += str_len (rp->r_topic->name);
	dp->type_name = xp;
	memcpy (xp, str_ptr (rp->r_topic->type->type_name),
				str_len (rp->r_topic->type->type_name));
	xp += str_len (rp->r_topic->type->type_name);
	uqp = &rp->r_qos->qos;
	dp->durability.kind = uqp->durability_kind;
	dp->deadline = uqp->deadline;
	dp->latency_budget = uqp->latency_budget;
	dp->liveliness.kind = uqp->liveliness_kind;
	dp->liveliness.lease_duration = uqp->liveliness_lease_duration;
	dp->reliability.kind = uqp->reliability_kind;
	dp->reliability.max_blocking_time = uqp->reliability_max_blocking_time;
	dp->ownership.kind = uqp->ownership_kind;
	dp->destination_order.kind = uqp->destination_order_kind;
	if (uqp->user_data)
		ROUND_PTR (xp);
	oseq_set (&dp->user_data.value, uqp->user_data, (unsigned char *) xp);
	xp += DDS_SEQ_LENGTH (dp->user_data.value);
	dp->time_based_filter = rp->r_time_based_filter;
	dp->presentation.access_scope = uqp->presentation_access_scope;
	dp->presentation.coherent_access = uqp->presentation_coherent_access;
	dp->presentation.ordered_access = uqp->presentation_ordered_access;
	if (uqp->partition)
		ROUND_PTR (xp);
	xp += partition_set (&dp->partition.name, rp->r_subscriber->qos.partition, (unsigned char *) xp);
	if (rp->r_topic->qos->qos.topic_data)
		ROUND_PTR (xp);
	oseq_set (&dp->topic_data.value, rp->r_topic->qos->qos.topic_data, (unsigned char *) xp);
	xp += DDS_SEQ_LENGTH (dp->topic_data.value);
	if (rp->r_subscriber->qos.group_data)
		ROUND_PTR (xp);
	oseq_set (&dp->group_data.value, rp->r_subscriber->qos.group_data, (unsigned char *) xp);
	return (DDS_RETCODE_OK);
}
Esempio n. 19
0
int json_find_next_member(int start_from, const char* input, struct json_token_info* info)
{
    return json_find_next_member(start_from, input, str_len(input), info);
}
Esempio n. 20
0
static int module_init(void)
{
	struct conf *conf = conf_cur();
	uint32_t value;
	char *p = fmtp + str_len(fmtp);
	bool b, stereo = true, sprop_stereo = true;
	int n = 0;

	conf_get_bool(conf, "opus_stereo", &stereo);
	conf_get_bool(conf, "opus_sprop_stereo", &sprop_stereo);

	/* always set stereo parameter first */
	n = re_snprintf(p, sizeof(fmtp) - str_len(p),
			"stereo=%d;sprop-stereo=%d", stereo, sprop_stereo);
	if (n <= 0)
		return ENOMEM;

	p += n;

	if (0 == conf_get_u32(conf, "opus_bitrate", &value)) {

		n = re_snprintf(p, sizeof(fmtp) - str_len(p),
				";maxaveragebitrate=%d", value);
		if (n <= 0)
			return ENOMEM;

		p += n;
	}

	if (0 == conf_get_bool(conf, "opus_cbr", &b)) {

		n = re_snprintf(p, sizeof(fmtp) - str_len(p),
				";cbr=%d", b);
		if (n <= 0)
			return ENOMEM;

		p += n;
	}

	if (0 == conf_get_bool(conf, "opus_inbandfec", &b)) {

		n = re_snprintf(p, sizeof(fmtp) - str_len(p),
				";useinbandfec=%d", b);
		if (n <= 0)
			return ENOMEM;

		p += n;
	}

	if (0 == conf_get_bool(conf, "opus_dtx", &b)) {

		n = re_snprintf(p, sizeof(fmtp) - str_len(p),
				";usedtx=%d", b);
		if (n <= 0)
			return ENOMEM;

		p += n;
	}

	(void)conf_get_bool(conf, "opus_mirror", &opus_mirror);

	if (opus_mirror) {
		opus.fmtp = NULL;
		opus.fmtp_ench = opus_fmtp_enc;
	}

	debug("opus: fmtp=\"%s\"\n", fmtp);

	aucodec_register(baresip_aucodecl(), &opus);

	return 0;
}
Esempio n. 21
0
int main(void)
{
	string_t *str;
	const char *user, *home, *authorized;
	const char *extra_env, *key, *value, *const *tmp;
	bool uid_found = FALSE, gid_found = FALSE;

	lib_init();
	str = t_str_new(1024);

	user = getenv("USER");
	if (user != NULL) {
		if (strchr(user, '\t') != NULL) {
			i_error("checkpassword: USER contains TAB");
			return 1;
		}
		str_printfa(str, "user=");
		str_append_tabescaped(str, user);
		str_append_c(str, '\t');
	}

	home = getenv("HOME");
	if (home != NULL) {
		if (strchr(home, '\t') != NULL) {
			i_error("checkpassword: HOME contains TAB");
			return 1;
		}
		str_printfa(str, "userdb_home=");
		str_append_tabescaped(str, home);
		str_append_c(str, '\t');
	}

	extra_env = getenv("EXTRA");
	if (extra_env != NULL) {
		for (tmp = t_strsplit(extra_env, " "); *tmp != NULL; tmp++) {
			value = getenv(*tmp);
			if (value != NULL) {
				key = t_str_lcase(*tmp);
				if (strcmp(key, "userdb_uid") == 0)
					uid_found = TRUE;
				else if (strcmp(key, "userdb_gid") == 0)
					gid_found = TRUE;
				str_append_tabescaped(str, key);
				str_append_c(str, '=');
				str_append_tabescaped(str, value);
				str_append_c(str, '\t');
			}
		}
	}
	if (!uid_found)
		str_printfa(str, "userdb_uid=%s\t",  dec2str(getuid()));
	if (!gid_found)
		str_printfa(str, "userdb_gid=%s\t",  dec2str(getgid()));

	i_assert(str_len(str) > 0);

	if (write_full(4, str_data(str), str_len(str)) < 0) {
		i_error("checkpassword: write_full() failed: %m");
		exit(111);
	}
	authorized = getenv("AUTHORIZED");
	if (authorized == NULL) {
		/* authentication */
		return 0;
	} else if (strcmp(authorized, "2") == 0) {
		/* successful passdb/userdb lookup */
		return 2;
	} else {
		i_error("checkpassword: Script doesn't support passdb/userdb lookup");
		return 111;
	}
}
/* this function prints the prompt. */
void prompt(char *c)
{
  write(1, c, str_len(c));
}
Esempio n. 23
0
void imap_append_string_for_humans(string_t *dest,
				   const unsigned char *src, size_t size)
{
	size_t i, pos, remove_count = 0;
	bool whitespace_prefix = TRUE, last_lwsp = TRUE, modify = FALSE;

	/* first check if there is anything to change */
	for (i = 0; i < size; i++) {
		switch (src[i]) {
		case 0:
			/* convert NUL to #0x80 */
			last_lwsp = FALSE;
			modify = TRUE;
			break;
		case '\t':
			modify = TRUE;
			/* fall through */
		case ' ':
			if (last_lwsp) {
				modify = TRUE;
				remove_count++;
			}
			last_lwsp = TRUE;
			break;
		case 13:
		case 10:
			remove_count++;
			modify = TRUE;
			break;
		case '"':
		case '\\':
			modify = TRUE;
			last_lwsp = FALSE;
			break;
		default:
			if ((src[i] & 0x80) != 0)
				modify = TRUE;
			last_lwsp = FALSE;
			break;
		}
		if (!last_lwsp)
			whitespace_prefix = FALSE;
	}
	if (last_lwsp && i > 0 && !whitespace_prefix) {
		modify = TRUE;
		remove_count++;
	}
	if (!modify) {
		/* fast path: we can simply write it as quoted string
		   without any escaping */
		str_append_c(dest, '"');
		str_append_n(dest, src, size);
		str_append_c(dest, '"');
		return;
	}
	if (size == remove_count) {
		/* contained only whitespace */
		str_append(dest, "\"\"");
		return;
	}

	str_printfa(dest, "{%"PRIuSIZE_T"}\r\n", size - remove_count);
	pos = str_len(dest);

	last_lwsp = TRUE; whitespace_prefix = TRUE;
	for (i = 0; i < size; i++) {
		switch (src[i]) {
		case 0:
			str_append_c(dest, 128);
			last_lwsp = FALSE;
			break;
		case '\t':
		case ' ':
			if (!last_lwsp)
				str_append_c(dest, ' ');
			last_lwsp = TRUE;
			break;
		case 13:
		case 10:
			break;
		default:
			last_lwsp = FALSE;
			str_append_c(dest, src[i]);
			break;
		}
		if (!last_lwsp)
			whitespace_prefix = FALSE;
	}
	if (last_lwsp && i > 0 && !whitespace_prefix)
		str_truncate(dest, str_len(dest)-1);
	i_assert(str_len(dest) - pos == size - remove_count);
}
Esempio n. 24
0
// static helper function to generate one list of disks
// (returns an array of ExScratchDiskDrive objects)
static ExScratchDiskDrive * genScratchDisks(const NAString &def,
						Lng32 &numDirs,
						Generator *generator,
						const char *defName)
{
  ExScratchDiskDrive *result = NULL;

  // temporary
  //  numDrives = 0;
  //  return result;
  // end temporary

  const char *str = def.data();
  if (!str || str[0]=='\0')
    {
      numDirs = 0;
      return result;		// fast return if empty NADefaults val
    }

  
  // ---------------------------------------------------------------------
  // Convert the strings into a temporary list of ExScratchDiskDrive
  // objects (temporary because we want to make the final list a
  // contiguous array)
  // ---------------------------------------------------------------------
  CollHeap *heap = generator->wHeap();
  Space *space = generator->getSpace();
  LIST(ExScratchDiskDrive *) tempList(heap);
  struct stat st;
  
 
  Lng32 nodeNum;
 
  char *token,*saveptr = NULL;
  //save the pointer to this since token will keep changing.

  char *sep = (char *)":";
  token = strtok_r((char *)str,sep,&saveptr);
  while (token != NULL)
    {
      //validate the directory
      if ((stat(token,&st) != 0 ) &&  !S_ISDIR(st.st_mode) ) //&& (numDirs > MAX_SCRATCH_LOCATIONS))
        {
          // syntax error in default, issue a warning (not an error)
          *CmpCommon::diags() << DgSqlCode(2055)
			      << DgString0(def)
			      << DgString1(defName);
          // don't continue after a syntax error
          str = NULL;
        }
      else
        {
          tempList.insert(new(heap) ExScratchDiskDrive(
                               token,
                               strlen(token) ));
        }
      token = strtok_r(NULL,sep,&saveptr);
    }
      
 
  token  = NULL;
    

  // ---------------------------------------------------------------------
  // Calculate total generated space needed and allocate it
  // ---------------------------------------------------------------------
#pragma nowarn(1506)   // warning elimination 
  numDirs = tempList.entries();
#pragma warn(1506)  // warning elimination 
 
  Lng32 allDirNamesLen = 0;
  char *generatedDirNames = NULL;

  Int32 i=0;
  for (; i<numDirs; i++)
    {
      allDirNamesLen += str_len(tempList[i]->getDirName())+1;
    }

  if (numDirs >0)
    {
      result = new(space) ExScratchDiskDrive[numDirs];
      generatedDirNames = new(space) char[allDirNamesLen];
    }

  // ---------------------------------------------------------------------
  // Loop over the temporary list and copy it into the generated space
  // ---------------------------------------------------------------------
  for (i=0; i<numDirs; i++)
    {
      ExScratchDiskDrive *src = tempList[i];
      Lng32 dirNameLen = src->getDirNameLength();
        
      str_cpy_all(generatedDirNames, src->getDirName(), dirNameLen);
      generatedDirNames[dirNameLen] = 0;
      result[i].setDirName(generatedDirNames);
      result[i].setDirNameLength(dirNameLen);
      generatedDirNames += dirNameLen+1;
    }
  return result;
}
Esempio n. 25
0
int postings_dump(struct postings* post, void *buf, unsigned int bufsize, 
  int fd) {
    unsigned int i,
                 j,
                 stopped = 0,
                 pos,                     /* position in current vector */
                 len,                     /* length of current term */
                 wlen,                    /* length of last write */
                 dbufsz;                  /* size of dbuf */
    struct postings_node* node,           /* current node */
                        ** arr;           /* array of postings nodes */
    char *dbuf,                           /* dumping buffer */
         *dbufpos;                        /* position in dumping buffer */
    struct vec v;

    /* FIXME: note, this should assert !post->update_required, but due to the
     * way that TREC documents are parsed (basically under the assumption that
     * another one is always coming) we end up with an empty document at the 
     * end */
    assert(!post->update);

    /* XXX: hack, allocate a big array of postings and then sort them by term.
     * This is so that postings go out sorted by term instead of hash value. */
    if (!(arr = malloc(sizeof(*arr) * post->dterms))) {
        return 0;
    }

    /* the provided buffer is used to dump the postings */
    dbuf = buf;
    dbufsz = bufsize;

    /* copy nodes into array */
    j = 0;
    for (i = 0; i < post->tblsize; i++) {
        node = post->hash[i];
        while (node) {
            /* perform stopping.  Ideally we'd like to stop terms before
             * stemming them, and before they make their way into the postings.
             * However, this means that we have to call the stoplist
             * once-per-term, which makes it a big bottleneck.  We stop here to
             * minimise the performance impact on the most common case, no
             * stopping.  Note that if we really wanted to make stopping 
             * (when actually used) go faster, it would be better to have a
             * sorted stoplist as well, and merge against that rather than 
             * doing one hash lookup per term. */
            if (!post->stop || stop_stop(post->stop, node->term) == STOP_OK) {
                arr[j++] = node;
            } else {
                assert(++stopped);  /* count stopped terms while debugging */
            }
            node = node->next;
        }

        /* reset hash node (memory free'd below) */
        post->hash[i] = NULL;
    }

    assert(j + stopped == post->dterms);
    stopped = 0;

    qsort(arr, post->dterms, sizeof(*arr), post_cmp);

    v.pos = dbuf;
    v.end = dbuf + dbufsz;
    for (i = 0; i < j;) {
        while ((i < post->dterms) 
          && ((len = str_len(arr[i]->term)), 1)
          && (((unsigned int) VEC_LEN(&v)) >= vec_vbyte_len(len) + len 
            + vec_vbyte_len(arr[i]->docs) + vec_vbyte_len(arr[i]->occurs) 
            + vec_vbyte_len(arr[i]->last_docno) 
            + vec_vbyte_len(arr[i]->vec.pos - arr[i]->vecmem))) {

            unsigned int bytes;

            assert(len);
            assert(dbufsz > vec_vbyte_len(len) + len 
              + vec_vbyte_len(arr[i]->docs) + vec_vbyte_len(arr[i]->occurs) 
              + vec_vbyte_len(arr[i]->last_docno)
              + vec_vbyte_len(arr[i]->vec.pos - arr[i]->vecmem));

            /* have enough space, copy stuff into buffer */
            bytes = vec_vbyte_write(&v, len);
            assert(bytes);
            bytes = vec_byte_write(&v, arr[i]->term, len);
            assert(bytes == len);
            bytes = vec_vbyte_write(&v, arr[i]->docs);
            assert(bytes);
            bytes = vec_vbyte_write(&v, arr[i]->occurs);
            assert(bytes);
            bytes = vec_vbyte_write(&v, arr[i]->last_docno);
            assert(bytes);
            bytes = vec_vbyte_write(&v, arr[i]->vec.pos - arr[i]->vecmem);
            assert(bytes);

            /* copy the inverted list in */
            pos = 0;
            while (((unsigned int) VEC_LEN(&v)) 
              < (arr[i]->vec.pos - arr[i]->vecmem) - pos) {

                /* copy last bit we can in */
                pos += vec_byte_write(&v, arr[i]->vecmem + pos, VEC_LEN(&v));

                /* write the buffer out */
                len = v.pos - dbuf;
                dbufpos = dbuf;

                while (len && ((wlen = write(fd, dbufpos, len)) >= 0)) {
                    len -= wlen;
                    dbufpos += wlen;
                }

                if (len) {
                    free(arr);
                    return 0;
                }

                v.pos = dbuf;
                v.end = dbuf + dbufsz;
            }

            /* copy last bit of inverted list in */
            pos += vec_byte_write(&v, arr[i]->vecmem + pos, 
              (arr[i]->vec.pos - arr[i]->vecmem) - pos);
            assert(arr[i]->vecmem + pos == arr[i]->vec.pos);

            free(arr[i]->vecmem);

            i++;
        }

        /* write the buffer out */
        len = v.pos - dbuf;
        dbufpos = dbuf;

        while (len && ((wlen = write(fd, dbufpos, len)) >= 0)) {
            len -= wlen;
            dbufpos += wlen;
        }

        if (len) {
            free(arr);
            return 0;
        }

        v.pos = dbuf;
        v.end = dbuf + dbufsz;
    }

    /* reinitialise hash table */
    post->size = 0;
    post->dterms = 0;
    post->terms = 0;
    post->docs = 0;
    poolalloc_clear(post->string_mem);
    objalloc_clear(post->node_mem);
 
    free(arr);

    return 1;
}
Esempio n. 26
0
static int add_transp_af(const struct sa *laddr)
{
	struct sa local;
	int err = 0;

	if (str_isset(uag.cfg->local)) {
		err = sa_decode(&local, uag.cfg->local,
				str_len(uag.cfg->local));
		if (err) {
			err = sa_set_str(&local, uag.cfg->local, 0);
			if (err) {
				warning("ua: decode failed: '%s'\n",
					uag.cfg->local);
				return err;
			}
		}

		if (!sa_isset(&local, SA_ADDR)) {
			uint16_t port = sa_port(&local);
			(void)sa_set_sa(&local, &laddr->u.sa);
			sa_set_port(&local, port);
		}

		if (sa_af(laddr) != sa_af(&local))
			return 0;
	}
	else {
		sa_cpy(&local, laddr);
		sa_set_port(&local, 0);
	}

	if (uag.use_udp)
		err |= sip_transp_add(uag.sip, SIP_TRANSP_UDP, &local);
	if (uag.use_tcp)
		err |= sip_transp_add(uag.sip, SIP_TRANSP_TCP, &local);
	if (err) {
		warning("ua: SIP Transport failed: %m\n", err);
		return err;
	}

#ifdef USE_TLS
	if (uag.use_tls) {
		/* Build our SSL context*/
		if (!uag.tls) {
			const char *cert = NULL;

			if (str_isset(uag.cfg->cert)) {
				cert = uag.cfg->cert;
				info("SIP Certificate: %s\n", cert);
			}

			err = tls_alloc(&uag.tls, TLS_METHOD_SSLV23,
					cert, NULL);
			if (err) {
				warning("ua: tls_alloc() failed: %m\n", err);
				return err;
			}
		}

		if (sa_isset(&local, SA_PORT))
			sa_set_port(&local, sa_port(&local) + 1);

		err = sip_transp_add(uag.sip, SIP_TRANSP_TLS, &local, uag.tls);
		if (err) {
			warning("ua: SIP/TLS transport failed: %m\n", err);
			return err;
		}
	}
#endif

	return err;
}
Esempio n. 27
0
int dcps_get_builtin_topic_data (DDS_TopicBuiltinTopicData *dp,
				 Topic_t                   *tp,
				 int                       bi_reader)
{
	size_t		size;
	char		*xp;
	UniQos_t	*uqp;
	KeyHash_t	hash;
	int		error;

	size = str_len (tp->name) + 1;
	size += str_len (tp->type->type_name) + 1;
	if (tp->qos->qos.topic_data) {
		ROUND_LEN (size);
		size += str_len (tp->qos->qos.topic_data);
	}
	xp = xmalloc (size);
	if (!xp)
		return (DDS_RETCODE_OUT_OF_RESOURCES);

	dp->name = xp;
	if (bi_reader) { /* Key already in reader cache! */
		error = get_builtin_key (tp->domain, dp->key.value,
					 BT_Topic, tp->entity.handle);
		if (error)
			goto key_error;
	}
	else { /* (Re)calculate key value. */
		topic_key_from_name (str_ptr (tp->name),
				     str_len (tp->name) - 1,
				     str_ptr (tp->type->type_name),
				     str_len (tp->type->type_name) - 1,
				     &hash);
		memcpy (dp->key.value, &hash, sizeof (DDS_BuiltinTopicKey_t));
	}
	memcpy (xp, str_ptr (tp->name), str_len (tp->name));
	xp += str_len (tp->name);
	dp->type_name = xp;
	memcpy (xp, str_ptr (tp->type->type_name), str_len (tp->type->type_name));
	xp += str_len (tp->type->type_name);
	uqp = &tp->qos->qos;
	dp->durability.kind = uqp->durability_kind;
#ifdef DURABILITY_SERVICE
	dp->durability_service.service_cleanup_delay = uqp->ds_cleanup_delay;
	dp->durability_service.history_kind = uqp->ds_history_kind;
	dp->durability_service.history_depth = uqp->ds_history_depth;
	dp->durability_service.max_samples = uqp->ds_limits.max_samples;
	dp->durability_service.max_instances = uqp->ds_limits.max_instances;
	dp->durability_service.max_samples_per_instance = uqp->ds_limits.max_samples_per_instance;
#else
	dp->durability_service = qos_def_writer_qos.durability_service;
#endif
	dp->deadline = uqp->deadline;
	dp->latency_budget = uqp->latency_budget;
	dp->liveliness.kind = uqp->liveliness_kind;
	dp->liveliness.lease_duration = uqp->liveliness_lease_duration;
	dp->reliability.kind = uqp->reliability_kind;
	dp->reliability.max_blocking_time = uqp->reliability_max_blocking_time;
	dp->transport_priority = uqp->transport_priority;
	dp->lifespan = uqp->lifespan;
	dp->destination_order.kind = uqp->destination_order_kind;
	dp->history.kind = uqp->history_kind;
	dp->history.depth = uqp->history_depth;
	dp->resource_limits = uqp->resource_limits;
	dp->ownership.kind = uqp->ownership_kind;
	if (uqp->topic_data)
		ROUND_PTR (xp);
	oseq_set (&dp->topic_data.value, uqp->topic_data, (unsigned char *) xp);
	return (DDS_RETCODE_OK);

    key_error:
	xfree (dp->name);
	return (error);
}
Esempio n. 28
0
static void
settings_export(struct config_export_context *ctx,
		const struct setting_parser_info *info,
		bool parent_unique_deflist,
		const void *set, const void *change_set)
{
	const struct setting_define *def;
	const void *value, *default_value, *change_value;
	void *const *children = NULL, *const *change_children = NULL;
	unsigned int i, count, count2, prefix_len;
	const char *str;
	char *key;
	bool dump, dump_default = FALSE;

	for (def = info->defines; def->key != NULL; def++) {
		value = CONST_PTR_OFFSET(set, def->offset);
		default_value = info->defaults == NULL ? NULL :
			CONST_PTR_OFFSET(info->defaults, def->offset);
		change_value = CONST_PTR_OFFSET(change_set, def->offset);
		switch (ctx->scope) {
		case CONFIG_DUMP_SCOPE_ALL:
			dump_default = TRUE;
			break;
		case CONFIG_DUMP_SCOPE_SET:
			dump_default = *((const char *)change_value) != 0;
			break;
		case CONFIG_DUMP_SCOPE_CHANGED:
			dump_default = FALSE;
			break;
		}
		if (!parent_unique_deflist ||
		    (ctx->flags & CONFIG_DUMP_FLAG_HIDE_LIST_DEFAULTS) == 0) {
			/* .. */
		} else if (*((const char *)change_value) == 0 &&
			   def->offset != info->type_offset) {
			/* this is mainly for service {} blocks. if value
			   hasn't changed, it's the default. even if
			   info->defaults has a different value. */
			default_value = value;
		} else {
			/* value is set explicitly, but we don't know the
			   default here. assume it's not the default. */
			dump_default = TRUE;
		}

		dump = FALSE;
		count = 0;
		str_truncate(ctx->value, 0);
		switch (def->type) {
		case SET_BOOL:
		case SET_SIZE:
		case SET_UINT:
		case SET_UINT_OCT:
		case SET_TIME:
		case SET_STR_VARS:
		case SET_STR:
		case SET_ENUM:
			if (!config_export_type(ctx->value, value,
						default_value, def->type,
						dump_default, &dump))
				i_unreached();
			break;
		case SET_DEFLIST:
		case SET_DEFLIST_UNIQUE: {
			const ARRAY_TYPE(void_array) *val = value;
			const ARRAY_TYPE(void_array) *change_val = change_value;

			if (!array_is_created(val))
				break;

			children = array_get(val, &count);
			for (i = 0; i < count; i++) {
				if (i > 0)
					str_append_c(ctx->value, ' ');
				setting_export_section_name(ctx->value, def, children[i], i);
			}
			change_children = array_get(change_val, &count2);
			i_assert(count == count2);
			break;
		}
		case SET_STRLIST: {
			const ARRAY_TYPE(const_string) *val = value;
			const char *const *strings;

			if (!array_is_created(val))
				break;

			key = p_strconcat(ctx->pool, str_c(ctx->prefix),
					  def->key, NULL);

			if (hash_table_lookup(ctx->keys, key) != NULL) {
				/* already added all of these */
				break;
			}
			hash_table_insert(ctx->keys, key, key);
			/* for doveconf -n to see this KEY_LIST */
			ctx->callback(key, "", CONFIG_KEY_LIST, ctx->context);

			strings = array_get(val, &count);
			i_assert(count % 2 == 0);
			for (i = 0; i < count; i += 2) {
				str = p_strdup_printf(ctx->pool, "%s%s%c%s",
						      str_c(ctx->prefix),
						      def->key,
						      SETTINGS_SEPARATOR,
						      strings[i]);
				ctx->callback(str, strings[i+1],
					      CONFIG_KEY_NORMAL, ctx->context);
			}
			count = 0;
			break;
		}
		case SET_ALIAS:
			break;
		}
		if (str_len(ctx->value) > 0 || dump) {
			key = p_strconcat(ctx->pool, str_c(ctx->prefix),
					  def->key, NULL);
			if (hash_table_lookup(ctx->keys, key) == NULL) {
				enum config_key_type type;

				if (def->offset == info->type_offset &&
				    parent_unique_deflist)
					type = CONFIG_KEY_UNIQUE_KEY;
				else if (SETTING_TYPE_IS_DEFLIST(def->type))
					type = CONFIG_KEY_LIST;
				else
					type = CONFIG_KEY_NORMAL;
				ctx->callback(key, str_c(ctx->value), type,
					ctx->context);
				hash_table_insert(ctx->keys, key, key);
			}
		}

		prefix_len = str_len(ctx->prefix);
		for (i = 0; i < count; i++) {
			str_append(ctx->prefix, def->key);
			str_append_c(ctx->prefix, SETTINGS_SEPARATOR);
			setting_export_section_name(ctx->prefix, def, children[i], i);
			str_append_c(ctx->prefix, SETTINGS_SEPARATOR);
			settings_export(ctx, def->list_info,
					def->type == SET_DEFLIST_UNIQUE,
					children[i], change_children[i]);

			str_truncate(ctx->prefix, prefix_len);
		}
	}
}
Esempio n. 29
0
int dcps_get_builtin_subscription_data (DDS_SubscriptionBuiltinTopicData *dp,
					DiscoveredReader_t               *drp)
{
	size_t		size, psize;
	char		*xp;
	UniQos_t	*uqp;

	size = str_len (drp->dr_topic->name);
	size += str_len (drp->dr_topic->type->type_name);
	if (drp->dr_qos->qos.user_data) {
		ROUND_LEN (size);
		size += str_len (drp->dr_qos->qos.user_data);
	}
	if (drp->dr_qos->qos.partition) {
		ROUND_LEN (size);
		psize = partition_size (drp->dr_qos->qos.partition);
		size += psize;
	}
	if (drp->dr_qos->qos.topic_data) {
		ROUND_LEN (size);
		size += str_len (drp->dr_qos->qos.topic_data);
	}
	if (drp->dr_qos->qos.group_data) {
		ROUND_LEN (size);
		size += str_len (drp->dr_qos->qos.group_data);
	}
	xp = xmalloc (size);
	if (!xp)
		return (DDS_RETCODE_OUT_OF_RESOURCES);

	dp->topic_name = xp;
	dp->key.value [0] = drp->dr_participant->p_guid_prefix.w [0];
	dp->key.value [1] = drp->dr_participant->p_guid_prefix.w [1];
	dp->key.value [2] = drp->dr_entity_id.w;
	memcpy (&dp->participant_key,
		&drp->dr_participant->p_guid_prefix,
		sizeof (DDS_BuiltinTopicKey_t));
	memcpy (xp, str_ptr (drp->dr_topic->name),
				str_len (drp->dr_topic->name));
	xp += str_len (drp->dr_topic->name);
	dp->type_name = xp;
	memcpy (xp, str_ptr (drp->dr_topic->type->type_name),
				str_len (drp->dr_topic->type->type_name));
	xp += str_len (drp->dr_topic->type->type_name);
	uqp = &drp->dr_qos->qos;
	dp->durability.kind = uqp->durability_kind;
	dp->deadline = uqp->deadline;
	dp->latency_budget = uqp->latency_budget;
	dp->liveliness.kind = uqp->liveliness_kind;
	dp->liveliness.lease_duration = uqp->liveliness_lease_duration;
	dp->reliability.kind = uqp->reliability_kind;
	dp->reliability.max_blocking_time = uqp->reliability_max_blocking_time;
	dp->ownership.kind = uqp->ownership_kind;
	dp->destination_order.kind = uqp->destination_order_kind;
	if (uqp->user_data)
		ROUND_PTR (xp);
	oseq_set (&dp->user_data.value, uqp->user_data, (unsigned char *) xp);
	xp += DDS_SEQ_LENGTH (dp->user_data.value);
	dp->time_based_filter = drp->dr_time_based_filter;
	dp->presentation.access_scope = uqp->presentation_access_scope;
	dp->presentation.coherent_access = uqp->presentation_coherent_access;
	dp->presentation.ordered_access = uqp->presentation_ordered_access;
	if (uqp->partition)
		ROUND_PTR (xp);
	xp += partition_set (&dp->partition.name, uqp->partition, (unsigned char *) xp);
	if (uqp->topic_data)
		ROUND_PTR (xp);
	oseq_set (&dp->topic_data.value, uqp->topic_data, (unsigned char *) xp);
	xp += DDS_SEQ_LENGTH (dp->topic_data.value);
	if (uqp->group_data)
		ROUND_PTR (xp);
	oseq_set (&dp->group_data.value, uqp->group_data, (unsigned char *) xp);
	return (DDS_RETCODE_OK);
}
Esempio n. 30
0
int rfc1524_expand_filename (char *nametemplate,
                             char *oldfile, char *newfile, size_t nflen)
{
  int i, j, k, ps, r;
  char *s;
  short lmatch = 0, rmatch = 0;
  char left[_POSIX_PATH_MAX];
  char right[_POSIX_PATH_MAX];

  newfile[0] = 0;

  /* first, ignore leading path components.
   */

  if (nametemplate && (s = strrchr (nametemplate, '/')))
    nametemplate = s + 1;

  if (oldfile && (s = strrchr (oldfile, '/')))
    oldfile = s + 1;

  if (!nametemplate) {
    if (oldfile)
      strfcpy (newfile, oldfile, nflen);
  }
  else if (!oldfile) {
    mutt_expand_fmt (newfile, nflen, nametemplate, "mutt");
  }
  else {                        /* oldfile && nametemplate */


    /* first, compare everything left from the "%s" 
     * (if there is one).
     */

    lmatch = 1;
    ps = 0;
    for (i = 0; nametemplate[i]; i++) {
      if (nametemplate[i] == '%' && nametemplate[i + 1] == 's') {
        ps = 1;
        break;
      }

      /* note that the following will _not_ read beyond oldfile's end. */

      if (lmatch && nametemplate[i] != oldfile[i])
        lmatch = 0;
    }

    if (ps) {

      /* If we had a "%s", check the rest. */

      /* now, for the right part: compare everything right from 
       * the "%s" to the final part of oldfile.
       * 
       * The logic here is as follows:
       * 
       * - We start reading from the end.
       * - There must be a match _right_ from the "%s",
       *   thus the i + 2.  
       * - If there was a left hand match, this stuff
       *   must not be counted again.  That's done by the
       *   condition (j >= (lmatch ? i : 0)).
       */

      rmatch = 1;

      for (r = 0, j = str_len (oldfile) - 1, k =
           str_len (nametemplate) - 1;
           j >= (lmatch ? i : 0) && k >= i + 2; j--, k--) {
        if (nametemplate[k] != oldfile[j]) {
          rmatch = 0;
          break;
        }
      }

      /* Now, check if we had a full match. */

      if (k >= i + 2)
        rmatch = 0;

      if (lmatch)
        *left = 0;
      else
        strnfcpy (left, nametemplate, sizeof (left), i);

      if (rmatch)
        *right = 0;
      else
        strfcpy (right, nametemplate + i + 2, sizeof (right));

      snprintf (newfile, nflen, "%s%s%s", left, oldfile, right);
    }
    else {
      /* no "%s" in the name template. */
      strfcpy (newfile, nametemplate, nflen);
    }
  }

  mutt_adv_mktemp (NULL, newfile, nflen);

  if (rmatch && lmatch)
    return 0;
  else
    return 1;

}