예제 #1
0
Object<Type>* ObjectPool<Type>::create(){
	for(unsigned i=prev_create;i<objs.size();i++){
		if(!objs[i]->in_used){
			objs[i]->in_used=true;
			prev_create=i;
			return (objs[i]);
		}
	}
	for(unsigned i=0;i<prev_create;i++){
		if(!objs[i]->in_used){
			objs[i]->in_used=true;
			prev_create=i;
			return (objs[i]);
		}
	}
	if(dynamic_malloc){
		create_obj(2*objs.size()+1);
		return create();
	}else{
		std::cerr<<"Tim::ObjectPool bad alloc, make sure you initialize with enough size"<<std::endl;
		std::cerr<<"or you can enable dynamic_malloc"<<std::endl;
		return 0;
	}

}
예제 #2
0
파일: curl.c 프로젝트: pez2001/node.c
static size_t curl_write_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
  node *state = node_GetItem((node*)stream,0);
  node *read_block = node_GetItem((node*)stream,1);
  node *block = node_GetItem((node*)stream,2);
  node *base_class = get_base_class(state);
  node *value = create_class_instance(base_class);
  add_garbage(state,value);
  node *real_value = get_value(value);
  char *ret = (char*)malloc((size*nmemb)+1);
  memset(ret+(size*nmemb) + 0, 0, 1);
  memcpy(ret,ptr,(size*nmemb));
  node_SetString(real_value,ret);
  free(ret);
  set_obj_string(value,"name","data");
  node *parameters = create_obj("parameters");
  node_AddItem(parameters,value);
  //printf("curl data handler callback\n");
  //node_PrintTree(value);
  //node *read_obj = 
  //node_PrintTree(read_block);
  execute_obj(state,read_block,block,parameters,True,False);//,True);resolve
  //execute_obj(state,read_block,block,parameters,True,True,True);
  return((size*nmemb));
}
예제 #3
0
파일: create.c 프로젝트: pdbogen/RhostMUSH
static void 
open_exit(dbref player, dbref loc, char *direction, char *linkto, int key)
{
    dbref exit;
    char *tpr_buff, *tprp_buff;

    if (!Good_obj(loc))
	return;

    if (!direction || !*direction) {
	notify_quiet(player, "Open where?");
	return;
    } else if (!controls(player, loc) && !could_doit(player, loc, A_LOPEN, 0, 0)) {
	notify_quiet(player, "Permission denied.");
	return;
    }
    exit = create_obj(player, TYPE_EXIT, direction, 0);
    if (exit == NOTHING)
	return;

    /* Initialize everything and link it in. */

    s_Exits(exit, loc);
    s_Next(exit, Exits(loc));
    s_Exits(loc, exit);

    /* and we're done */

    if ( !(key & SIDEEFFECT ) )
       notify_quiet(player, "Opened.");

    /* See if we should do a link */

    if (!linkto || !*linkto)
	return;

    loc = parse_linkable_room(player, linkto);
    if (loc != NOTHING) {

	/* Make sure the player passes the link lock */

	if ((loc != HOME) && !could_doit(player, loc, A_LLINK, 1, 0)) {
	    notify_quiet(player, "You can't link to there.");
	    return;
	}
	/* Link it if the player can pay for it */

	if (!payfor(player, mudconf.linkcost)) {
            tprp_buff = tpr_buff = alloc_lbuf("open_exit");
	    notify_quiet(player,
			 safe_tprintf(tpr_buff, &tprp_buff, "You don't have enough %s to link.",
				 mudconf.many_coins));
            free_lbuf(tpr_buff);
	} else {
	    s_Location(exit, loc);
	    if ( !(key & SIDEEFFECT ) )
	       notify_quiet(player, "Linked.");
	}
    }
}
예제 #4
0
파일: fight.c 프로젝트: matthewbode/mg2
void make_corpse(struct char_data * ch)
{
  struct obj_data *corpse, *o;
  struct obj_data *money;
  int i;

  corpse = create_obj();

  corpse->item_number = NOTHING;
  IN_ROOM(corpse) = NOWHERE;
  corpse->name = str_dup("corpse");

  sprintf(buf2, "The corpse of %s is lying here.", GET_NAME(ch));
  corpse->description = str_dup(buf2);

  sprintf(buf2, "the corpse of %s", GET_NAME(ch));
  corpse->short_description = str_dup(buf2);

  GET_OBJ_TYPE(corpse) = ITEM_CONTAINER;
  GET_OBJ_WEAR(corpse) = ITEM_WEAR_TAKE;
  GET_OBJ_EXTRA(corpse) = ITEM_NODONATE;
  GET_OBJ_VAL(corpse, 0) = 0;	/* You can't store stuff in a corpse */
  GET_OBJ_VAL(corpse, 3) = 1;	/* corpse identifier */
  GET_OBJ_WEIGHT(corpse) = GET_WEIGHT(ch) + IS_CARRYING_W(ch);
  GET_OBJ_RENT(corpse) = 100000;
  if (IS_NPC(ch))
    GET_OBJ_TIMER(corpse) = max_npc_corpse_time;
  else
    GET_OBJ_TIMER(corpse) = max_pc_corpse_time;

  /* transfer character's inventory to the corpse */
  corpse->contains = ch->carrying;
  for (o = corpse->contains; o != NULL; o = o->next_content)
    o->in_obj = corpse;
  object_list_new_owner(corpse, NULL);

  /* transfer character's equipment to the corpse */
  for (i = 0; i < NUM_WEARS; i++)
    if (GET_EQ(ch, i)) {
      remove_otrigger(GET_EQ(ch, i), ch);
      obj_to_obj(unequip_char(ch, i), corpse);
    }

  /* transfer gold */
  if (GET_GOLD(ch) > 0) {
    /* following 'if' clause added to fix gold duplication loophole */
    if (IS_NPC(ch) || (!IS_NPC(ch) && ch->desc)) {
      money = create_money(GET_GOLD(ch));
      obj_to_obj(money, corpse);
    }
    GET_GOLD(ch) = 0;
  }
  ch->carrying = NULL;
  IS_CARRYING_N(ch) = 0;
  IS_CARRYING_W(ch) = 0;

  obj_to_room(corpse, IN_ROOM(ch));
}
예제 #5
0
파일: obj.c 프로젝트: j16r/poseidon
void init_obj(void)
{
    // Set up the base dir ring
    Base_dir.Next = &Base_dir;
    Base_dir.Previous = &Base_dir;
    Base_dir.Parent = &Base_dir;

    // Initialize the root directory
    Base_dir.Type = OTYPE_DIR;
    Base_dir.St = NULL;

    // Set up the basic directory structure
    dir_Tasks = (struct Object_dec *)create_obj(&Base_dir,OTYPE_SUBDIR);
    dir_Devices = (struct Object_dec *)create_obj(&Base_dir,OTYPE_SUBDIR);
    
    // Add the kernel task to the Tasks directory
    add_obj(dir_Tasks,&Base_obj);
}
예제 #6
0
static void*
__acquire_category(const char* &name, char *buf, _Locale_name_hint* hint,
                   loc_extract_name_func_t extract_name,
                   loc_create_func_t create_obj, loc_default_name_func_t default_name,
                   Category_Map ** M, int *__err_code) {
  typedef Category_Map::iterator Category_iterator;
  pair<Category_iterator, bool> result;

  *__err_code = _STLP_LOC_UNDEFINED;

  // Find what name to look for. Be careful if user requests the default.
  if (name[0] == 0) {
    name = default_name(buf);
    if (name == 0 || name[0] == 0)
      name = "C";
  }
  else {
    const char* cname = extract_name(name, buf, hint, __err_code);
    if (cname == 0) {
      return 0;
    }
    name = cname;
  }

  Category_Map::value_type __e(name, pair<void*,size_t>((void*)0,size_t(0)));

  _STLP_auto_lock sentry(category_hash_mutex());

  if (!*M)
    *M = new Category_Map();

  // Look for an existing entry with that name.
  result = (*M)->insert_noresize(__e);

  if (result.second) {
    // There was no entry in the map already.  Create the category.
    (*result.first).second.first = create_obj(name, hint, __err_code);
    if (!(*result.first).second.first) {
      (*M)->erase(result.first);
#if defined (_STLP_LEAKS_PEDANTIC)
      if ((*M)->empty()) {
        delete *M;
        *M = 0;
      }
#endif
      return 0;
    }
  }

  // Increment the reference count.
  ++((*result.first).second.second);

  return (*result.first).second.first;
}
예제 #7
0
파일: handler.c 프로젝트: Lundessa/raven3
struct obj_data *create_money(int amount)
{
  struct obj_data *obj;
  struct extra_descr_data *new_descr;
  char buf[200];
  int y;

  if (amount <= 0) {
    log("SYSERR: Try to create negative or 0 money. (%d)", amount);
    return (NULL);
  }
  obj = create_obj();
  CREATE(new_descr, struct extra_descr_data, 1);

  if (amount == 1) {
    obj->name = strdup("coin gold");
    obj->short_description = strdup("a gold coin");
    obj->description = strdup("One miserable gold coin is lying here.");
    new_descr->keyword = strdup("coin gold");
    new_descr->description = strdup("It's just one miserable little gold coin.");
  } else {
    obj->name = strdup("coins gold");
    obj->short_description = strdup(money_desc(amount));
    snprintf(buf, sizeof(buf), "%s is lying here.", money_desc(amount));
    obj->description = strdup(CAP(buf));

    new_descr->keyword = strdup("coins gold");
    if (amount < 10)
      snprintf(buf, sizeof(buf), "There are %d coins.", amount);
    else if (amount < 100)
      snprintf(buf, sizeof(buf), "There are about %d coins.", 10 * (amount / 10));
    else if (amount < 1000)
      snprintf(buf, sizeof(buf), "It looks to be about %d coins.", 100 * (amount / 100));
    else if (amount < 100000)
      snprintf(buf, sizeof(buf), "You guess there are, maybe, %d coins.",
	      1000 * ((amount / 1000) + rand_number(0, (amount / 1000))));
    else
      strcpy(buf, "There are a LOT of coins.");	/* strcpy: OK (is < 200) */
    new_descr->description = strdup(buf);
  }

  new_descr->next = NULL;
  obj->ex_description = new_descr;

  GET_OBJ_TYPE(obj) = ITEM_MONEY;
  for(y = 0; y < TW_ARRAY_MAX; y++)
    obj->obj_flags.wear_flags[y] = 0;
  SET_BIT_AR(GET_OBJ_WEAR(obj), ITEM_WEAR_TAKE);
  GET_OBJ_VAL(obj, 0) = amount;
  GET_OBJ_COST(obj) = amount;
  obj->item_number = NOTHING;

  return (obj);
}
예제 #8
0
static void*
__acquire_category(const char* name, _Locale_name_hint* hint,
                   loc_extract_name_func_t extract_name,
                   loc_create_func_t create_obj, loc_default_name_func_t default_obj,
                   Category_Map ** M) {
#if !defined (__BORLANDC__) || (__BORLANDC__ >= 0x564)
  typedef Category_Map::iterator Category_iterator;
  pair<Category_iterator, bool> result;
#else
#  if !defined(_STLP_DEBUG)
  pair<_Ht_iterator<_Slist_iterator<pair<const string,pair<void *,unsigned int> >,_Nonconst_traits<pair<const string,pair<void *,unsigned int> > > >,_NonLocalHashMapTraitsT<pair<const string,pair<void *,unsigned int> > > >, bool> result;
#  else
  pair<_DBG_iter<_NonDbg_hashtable<pair<const string,pair<void *,unsigned int> >,string,hash<string>,_HashMapTraitsT<pair<const string,pair<void *,unsigned int> > >,_Select1st<pair<const string,pair<void *,unsigned int> > >,_DbgEqual<string,equal_to<string> >,allocator<pair<const string,pair<void *,unsigned int> > > >,_DbgTraits<_NonLocalHashMapTraitsT<pair<const string,pair<void *,unsigned int> > > > >, bool> result;
#  endif
#endif

  // Find what name to look for. Be careful if user requests the default.
  const char *cname;
  char buf[_Locale_MAX_SIMPLE_NAME];
  if (name == 0 || name[0] == 0) {
    cname = default_obj(buf);
    if (cname == 0 || cname[0] == 0)
      cname = "C";
  }
  else {
    cname = extract_name(name, buf, hint);
    if (cname == 0) {
      return 0;
    }
  }

  Category_Map::value_type __e(cname, pair<void*,size_t>((void*)0,size_t(0)));

  _STLP_auto_lock sentry(__category_hash_lock);

  if (!*M)
    *M = new Category_Map();

  // Look for an existing entry with that name.
  result = (*M)->insert_noresize(__e);

  // There was no entry in the map already.  Create the category.
  if (result.second)
    (*result.first).second.first = create_obj(cname, hint);

  // Increment the reference count.
  ++((*result.first).second.second);

  return (*result.first).second.first;
}
예제 #9
0
obj_t * create_serial_obj(server_conf_t *conf, char *name,
    char *dev, seropt_t *opts, char *errbuf, int errlen)
{
/*  Creates a new serial device object and adds it to the master objs list.
 *    Note: the console is open and set for non-blocking I/O.
 *  Returns the new object, or NULL on error.
 */
    ListIterator i;
    obj_t *serial;

    assert(conf != NULL);
    assert((name != NULL) && (name[0] != '\0'));
    assert((dev != NULL) && (dev[0] != '\0'));
    assert(opts != NULL);

    /*  Check for duplicate console and device names.
     *  While the write-lock will protect against two separate daemons
     *    using the same device, it will not protect against two console
     *    objects within the same daemon process using the same device.
     *    So that check is performed here.
     */
    i = list_iterator_create(conf->objs);
    while ((serial = list_next(i))) {
        if (is_console_obj(serial) && !strcmp(serial->name, name)) {
            snprintf(errbuf, errlen,
                "console [%s] specifies duplicate console name", name);
            break;
        }
        if (is_serial_obj(serial) && !strcmp(serial->aux.serial.dev, dev)) {
            snprintf(errbuf, errlen,
                "console [%s] specifies duplicate device \"%s\"", name, dev);
            break;
        }
    }
    list_iterator_destroy(i);
    if (serial != NULL) {
        return(NULL);
    }
    serial = create_obj(conf, name, -1, CONMAN_OBJ_SERIAL);
    serial->aux.serial.dev = create_string(dev);
    serial->aux.serial.opts = *opts;
    serial->aux.serial.logfile = NULL;
    /*
     *  Add obj to the master conf->objs list.
     */
    list_append(conf->objs, serial);

    return(serial);
}
예제 #10
0
파일: mcache.c 프로젝트: deadcafe/JohnDoe
static inline struct mc_chunk *
alloc_chunk(size_t size)
{
	struct mc_chunk *chunk;

	chunk = mmap(0, size,
		     PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS,
		     -1, 0);
	if (chunk == MAP_FAILED)
		return NULL;
	DBGTRACE("%s(%d): size:%lu chunk:%p\n",
		 __func__, __LINE__, size, chunk);
	chunk->size = size;
	chunk->cache = NULL;
	create_obj(chunk);
	return chunk;
}
예제 #11
0
static void*
__acquire_category(const char* name, loc_extract_name_func_t extract_name,
                   loc_create_func_t create_obj, loc_default_name_func_t default_obj, 
                   Category_Map ** M) {
  typedef Category_Map::iterator Category_iterator;
  pair<Category_iterator, bool> result;
  
  // Find what name to look for. Be careful if user requests the default.
  const char *cname;
  char buf[_Locale_MAX_SIMPLE_NAME];
  if (name == 0 || name[0] == 0) {
    cname = default_obj(buf);
    if (cname == 0 || cname[0] == 0)
      cname = "C";
  }
  else {
    cname = extract_name(name, buf);
    if (cname == 0) {
      return 0;
    }
  }

  Category_Map::value_type __e(cname, pair<void*,size_t>((void*)0,size_t(0)));

  _STLP_auto_lock sentry(__category_hash_lock);

  if (!*M)
    *M = new Category_Map();

#if defined(__SC__)    //*TY 06/01/2000 - added workaround for SCpp
  if(!*M) delete *M;  //*TY 06/01/2000 - it forgets to generate dtor for Category_Map class. This fake code forces to generate one.
#endif          //*TY 06/01/2000 - 

  // Look for an existing entry with that name.
  result = (*M)->insert_noresize(__e);

  // There was no entry in the map already.  Create the category.
  if (result.second) 
    (*result.first).second.first = create_obj(cname);

  // Increment the reference count.
  ++((*result.first).second.second);

  return (*result.first).second.first;
}
예제 #12
0
static void*
__acquire_category(const char* name, loc_create_func_t create_obj,
                   loc_default_name_func_t default_obj, Category_Map ** M)
{
    typedef Category_Map::iterator Category_iterator;
    pair<Category_iterator, bool> result;
#if defined(__LIBSTD_CPP_SYMBIAN32_WSD__) || defined(_STLP_LIBSTD_CPP_NO_STATIC_VAR_)
    _STLP_auto_lock sentry(get_locale_catalog_category_hash_lock());
# else
    _STLP_auto_lock sentry(__category_hash_lock);
# endif

    typedef const char* key_type;


    if (!*M)
        *M = new Category_Map();

#if defined(__SC__)		//*TY 06/01/2000 - added workaround for SCpp
if(!*M) delete *M;	//*TY 06/01/2000 - it forgets to generate dtor for Category_Map class. This fake code forces to generate one.
#endif					//*TY 06/01/2000 - 

    // Find what name to look for.  Be careful if user requests the default.
    char buf[_Locale_MAX_SIMPLE_NAME];
    if (name == 0 || name[0] == 0)
        name = default_obj(buf);
    if (name == 0 || name[0] == 0)
        name = "C";

    pair<const key_type, pair<void*,size_t> > __e(name, pair<void*,size_t>((void*)0,size_t(0)));

    // Look for an existing entry with that name.

    result = (*M)->insert_noresize(__e);

    // There was no entry in the map already.  Create the category.
    if (result.second)
        (*result.first).second.first = create_obj(name);

    // Increment the reference count.
    ++((*result.first).second.second);

    return (*result.first).second.first;
}
예제 #13
0
    HS_DBREF CHSInterface::CreateNewGameObject(int object_type)
#endif
{
#ifdef PENNMUSH                 // No change in code between versions
    HS_DBREF dbObject;
    dbObject = new_object();
    set_name(dbObject, "NewObj");
    Owner(dbObject) = HSCONF.space_wiz;
    Zone(dbObject) = Zone(HSCONF.space_wiz);
    Type(dbObject) = TYPE_THING;
    SetFlag(dbObject, GetGameOption(HSGO_THING_FLAGS));
    return dbObject;
#endif

#if defined(TM3) || defined(MUX)
    return create_obj(GOD, object_type, "NewObj", 0);
#endif

}
예제 #14
0
파일: mail.c 프로젝트: adept2tech/Mclandia
void
postmaster_receive_mail (struct char_data *ch, struct char_data *mailman,
						 int cmd, char *arg)
{
	char buf[256];
	struct obj_data *obj;

	if (!has_mail (GET_IDNUM (ch)))
	{
		sprintf (buf,
				 "$n tells you, 'Sorry, you don't have any mail waiting.'");
		act (buf, FALSE, mailman, 0, ch, TO_VICT);
		return;
	}
	while (has_mail (GET_IDNUM (ch)))
	{
		obj = create_obj ();
		obj->item_number = NOTHING;
		obj->name = str_dup ("mail paper letter");
		obj->short_description = str_dup ("a piece of mail");
		obj->description = str_dup ("Someone has left a piece of mail here.");

		GET_OBJ_TYPE (obj) = ITEM_NOTE;
		GET_OBJ_WEAR (obj) = ITEM_WEAR_TAKE | ITEM_WEAR_HOLD;
		GET_OBJ_WEIGHT (obj) = 1;
		GET_OBJ_COST (obj) = 30;
		GET_OBJ_RENT (obj) = 10;
		obj->action_description = read_delete (GET_IDNUM (ch));

		if (obj->action_description == NULL)
			obj->action_description =
				str_dup
				("Mail system error - please report.  Error #11.\r\n");

		obj_to_char (obj, ch);

		act ("$n gives you a piece of mail.", FALSE, mailman, 0, ch, TO_VICT);
		act ("$N gives $n a piece of mail.", FALSE, ch, 0, mailman, TO_ROOM);
	}
}
예제 #15
0
// Clones an object and returns the HS_DBREF of the new clone.
HS_DBREF CHSInterface::CloneThing(HS_DBREF model)
{
    HS_DBREF clone;

#ifdef PENNMUSH                 // No change in code between versions
    clone = new_object();

    // Copy the basic information from the model to the clone.
    memcpy(REFDB(clone), REFDB(model), sizeof(struct object));
    Owner(clone) = Owner(model);
    Name(clone) = NULL;

    // NULL-out some memory pointers we didn't really want copied.
    db[clone].list = NULL;

    // Now copy the pointer information.
    atr_cpy(clone, model);
    Locks(clone) = NULL;
    clone_locks(model, model, clone);
    Zone(clone) = Zone(model);
    Parent(clone) = Parent(model);
    Flags(clone) = clone_flag_bitmask("FLAG", Flags(model));
    set_name(clone, Name(model));
    s_Pennies(clone, Pennies(model));

#ifdef CREATION_TIMES
    /*
     * We give the clone the same modification time that its
     * other clone has, but update the creation time
     */
    db[clone].creation_time = time((time_t *) 0);
#endif

    db[clone].contents = db[clone].location = db[clone].next = NOTHING;
#endif

#if defined(TM3) || defined(MUX)
    clone = create_obj(Owner(model), Typeof(model),
                       Name(model), Pennies(model));

    //atr_free(clone);
    s_Name(clone, Name(model));
    s_Pennies(clone, Pennies(model));
    s_Parent(clone, Parent(model));
#ifdef TM3
    atr_cpy(Owner(clone), clone, model);
    s_Flags(clone, Flags(model));
    s_Flags2(clone, Flags2(model));
    s_Flags3(clone, Flags3(model));
#endif

#ifdef MUX
    atr_cpy(clone, model);
    s_Flags(clone, FLAG_WORD1, Flags(model));
    s_Flags(clone, FLAG_WORD2, Flags2(model));
    s_Flags(clone, FLAG_WORD3, Flags3(model));
    s_Home(clone, Home(model));
#endif
#endif

    return clone;
}
예제 #16
0
void make_corpse(struct char_data *ch)
{
  char buf2[MAX_NAME_LENGTH + 64];
  struct obj_data *corpse, *o;
  struct obj_data *money;
  int i;

  corpse = create_obj();

  corpse->item_number = NOTHING;
  IN_ROOM(corpse) = NOWHERE;
  corpse->name = strdup("corpse");

  snprintf(buf2, sizeof(buf2), "The corpse of %s is lying here.", GET_NAME(ch));
  corpse->description = strdup(buf2);

  snprintf(buf2, sizeof(buf2), "the corpse of %s", GET_NAME(ch));
  corpse->short_description = strdup(buf2);

  GET_OBJ_TYPE(corpse) = ITEM_CONTAINER;
  GET_OBJ_WEAR(corpse) = ITEM_WEAR_TAKE;
  GET_OBJ_EXTRA(corpse) = ITEM_NODONATE;
  GET_OBJ_VAL(corpse, 0) = 0;	/* You can't store stuff in a corpse */
  GET_OBJ_VAL(corpse, 3) = 1;	/* corpse identifier */
  GET_OBJ_WEIGHT(corpse) = GET_WEIGHT(ch) + IS_CARRYING_W(ch);
  GET_OBJ_RENT(corpse) = 100000;
  if (IS_NPC(ch))
    GET_OBJ_TIMER(corpse) = max_npc_corpse_time;
  else
    GET_OBJ_TIMER(corpse) = max_pc_corpse_time;

  /* transfer character's inventory to the corpse */
  corpse->contains = ch->carrying;
  for (o = corpse->contains; o != NULL; o = o->next_content)
    o->in_obj = corpse;
  object_list_new_owner(corpse, NULL);

  /* transfer character's equipment to the corpse */
  for (i = 0; i < NUM_WEARS; i++)
    if (GET_EQ(ch, i))
      obj_to_obj(unequip_char(ch, i), corpse);

  /* transfer gold */
  if (GET_GOLD(ch) > 0) {
    /*
     * following 'if' clause added to fix gold duplication loophole
     * The above line apparently refers to the old "partially log in,
     * kill the game character, then finish login sequence" duping
     * bug. The duplication has been fixed (knock on wood) but the
     * test below shall live on, for a while. -gg 3/3/2002
     */
    if (IS_NPC(ch) || ch->desc) {
      money = create_money(GET_GOLD(ch));
      obj_to_obj(money, corpse);
    }
    GET_GOLD(ch) = 0;
  }
  ch->carrying = NULL;
  IS_CARRYING_N(ch) = 0;
  IS_CARRYING_W(ch) = 0;

  obj_to_room(corpse, IN_ROOM(ch));
}
예제 #17
0
obj_t * create_unixsock_obj(server_conf_t *conf, char *name, char *dev,
    char *errbuf, int errlen)
{
/*  Creates a new unix domain object and adds it to the master objs list.
 *  Returns the new objects, or NULL on error.
 */
    int           n;
    ListIterator  i;
    obj_t        *unixsock;
    int           rv;

    assert(conf != NULL);
    assert((name != NULL) && (name[0] != '\0'));
    assert((dev != NULL) && (dev[0] != '\0'));
    assert(errbuf != NULL);
    assert(errlen > 0);

    /*  Check length of device string.
     */
    n = max_unixsock_dev_strlen();
    if (strlen(dev) > n) {
        snprintf(errbuf, errlen,
            "console [%s] exceeds maximum device length of %d bytes", name, n);
        return(NULL);
    }
    /*  Check for duplicate console and device names.
     */
    i = list_iterator_create(conf->objs);
    while ((unixsock = list_next(i))) {
        if (is_console_obj(unixsock) && !strcmp(unixsock->name, name)) {
            snprintf(errbuf, errlen,
                "console [%s] specifies duplicate console name", name);
            break;
        }
        if (is_unixsock_obj(unixsock)
                && !strcmp(unixsock->aux.unixsock.dev, dev)) {
            snprintf(errbuf, errlen,
                "console [%s] specifies duplicate device \"%s\"", name, dev);
            break;
        }
    }
    list_iterator_destroy(i);
    if (unixsock != NULL) {
        return(NULL);
    }
    unixsock = create_obj(conf, name, -1, CONMAN_OBJ_UNIXSOCK);
    unixsock->aux.unixsock.dev = create_string(dev);
    unixsock->aux.unixsock.logfile = NULL;
    unixsock->aux.unixsock.timer = -1;
    unixsock->aux.unixsock.state = CONMAN_UNIXSOCK_DOWN;
    /*
     *  Add obj to the master conf->objs list.
     */
    list_append(conf->objs, unixsock);

    rv = inevent_add(unixsock->aux.unixsock.dev,
        (inevent_cb_f) open_unixsock_obj, unixsock);
    if (rv < 0) {
        log_msg(LOG_INFO,
            "Console [%s] unable to register device \"%s\" for inotify events",
            unixsock->name, unixsock->aux.unixsock.dev);
    }
    return(unixsock);
}
예제 #18
0
파일: conf.c 프로젝트: leevon/rhizel
cfg_st *cfg_load(char *path)
{
    FILE *fp = fopen(path, "r");
    if (NULL == fp)
    {
      return NULL;
    }

    struct cfg_section *sec_head = NULL;
    struct cfg_section *sec_prev = NULL;
    struct cfg_section *sec_curr = NULL;

    struct cfg_obj *obj_curr = NULL;
    struct cfg_obj *obj_prev = NULL;

    char *line = NULL;
    size_t   n  = 0;
    ssize_t len = 0;

    while ((len = _readline(&line, &n, fp)) != -1)
    {
        char *s = line;
        #ifdef __DEBUG__
          printf("1_readline:%s\n",s);
        #endif
        if (is_comment(&s))
            continue;
        len = strlen(s);

        if (len>2 && s[0]=='[' && s[len-1]==']')
        {
            char *name = s + 1;
            *(name+len-1-1) = '\0';
            trim(name);

            if ((sec_curr = find_section(sec_head, name)) == NULL)
            {
                if ((sec_curr = create_section(sec_head, name)) == NULL)
                {
                    free(line);
                    return NULL;
                }

                if (sec_head == NULL)
                    sec_head = sec_curr;
                if (sec_prev != NULL)
                    sec_prev->next = sec_curr;

                sec_prev = sec_curr;
                obj_prev = NULL;
            }
            else
            {
                obj_prev = sec_curr->obj;
                while (obj_prev->next != NULL)
                    obj_prev = obj_prev->next;
            }
            continue;
        }

        char *delimiter = strchr(s, '=');
        if (delimiter == NULL)
            continue;
        *delimiter = '\0';

        char *name = s;
        trim(name);

        char *value = delimiter + 1;
        delimiter = strchr(value, '#');
        if (NULL != delimiter)
        {
          *delimiter = '\0';
        }
        trim(value);

        if (sec_curr == NULL)
        {
            if ((sec_curr = create_section(sec_head, "global")) == NULL)
            {
                free(line);

                return NULL;
            }

            if (sec_head == NULL)
                sec_head = sec_curr;
            sec_prev = sec_curr;
            obj_prev = NULL;
        }

        if ((obj_curr = find_obj(sec_curr, name)) == NULL)
        {
            obj_curr = create_obj(sec_head, name, value);
            if (obj_curr == NULL)
            {
                free(line);

                return NULL;
            }

            if (obj_prev)
                obj_prev->next = obj_curr;
            if (sec_curr->obj == NULL)
                sec_curr->obj = obj_curr;

            obj_prev = obj_curr;
        }
        else
        {
            char *old_value = obj_curr->value;

            if ((obj_curr->value = strdup(value)) == NULL)
            {
                cfg_free(sec_head);

                free(line);

                return NULL;
            }

            free(old_value);
        }
    }

    free(line);
    fclose(fp);

    if (sec_head == NULL)
    {
        if ((sec_head = calloc(1, sizeof(struct cfg_section))) == NULL)
            return NULL;
    }
    #ifdef __DEBUG__
      ini_print(sec_head);
    #endif
    
    return sec_head;
}
예제 #19
0
파일: handler.c 프로젝트: Calebros/aol
struct obj_data *create_money(struct money_data amount)
{
  struct obj_data *obj;
  struct extra_descr_data *new_descr;
  char buf[200];
  int coins;

  if ( money_to_copper(amount) <= 0) {
    log("SYSERR: Try to create negative or 0 money.");
    return NULL;
  }

  obj = create_obj();
  CREATE(new_descr, struct extra_descr_data, 1);

  coins = amount.platinum + amount.steel + amount.gold + amount.copper;

  if (coins == 1) {
    obj->name = str_dup("one coin");
    obj->short_description = str_dup("a coin");
    obj->description = str_dup("One miserable coin is lying here.");
    new_descr->keyword = str_dup("coin");
    new_descr->description = str_dup("It's just one miserable little coin.");
  } else {
    obj->name = str_dup("coins");
    obj->short_description = str_dup(money_desc(coins));
    sprintf(buf, "%s is lying here.", money_desc(coins));
    obj->description = str_dup(CAP(buf));

    new_descr->keyword = str_dup("coins");
    if (coins < 10) {
      sprintf(buf, "There are %d coins.", coins);
      new_descr->description = str_dup(buf);
    } else if (coins < 100) {
      sprintf(buf, "There are about %d coins.", 10 * (coins / 10));
      new_descr->description = str_dup(buf);
    } else if (coins < 1000) {
      sprintf(buf, "It looks to be about %d coins.", 100 * (coins / 100));
      new_descr->description = str_dup(buf);
    } else if (coins < 100000) {
      sprintf(buf, "You guess there are, maybe, %d coins.",
	      1000 * ((coins / 1000) + number(0, (coins / 1000))));
      new_descr->description = str_dup(buf);
    } else
      new_descr->description = str_dup("There are a LOT of coins.");
  }

  new_descr->next = NULL;
  obj->ex_description = new_descr;

  GET_OBJ_TYPE(obj) = ITEM_MONEY;
  GET_OBJ_WEAR(obj) = ITEM_WEAR_TAKE;
  GET_OBJ_VAL(obj, 0) = amount.platinum;
  GET_OBJ_VAL(obj, 1) = amount.steel;
  GET_OBJ_VAL(obj, 2) = amount.gold;
  GET_OBJ_VAL(obj, 3) = amount.copper;
  GET_OBJ_COST(obj) = money_to_copper(amount);
  obj->item_number = NOTHING;

  return obj;
}
예제 #20
0
파일: objsave.c 프로젝트: madvlad/doom-mud
int Crash_load_objs(struct char_data *ch) {
  FILE *fl;
  char fname[MAX_STRING_LENGTH];
  char line[256];
  int t[10],i,num_of_days;
  int orig_rent_code;
  struct obj_data *temp;
  int locate=0, nr,cost,num_objs=0;
  struct obj_data *cont_row[MAX_BAG_ROWS];
  int rentcode,timed,netcost,gold,account,nitems;

  if (!get_filename(fname, sizeof(fname), CRASH_FILE, GET_NAME(ch)))
    return 1;

  for (i = 0; i < MAX_BAG_ROWS; i++)
    cont_row[i] = NULL;

  if (!(fl = fopen(fname, "r"))) {
    if (errno != ENOENT) { /* if it fails, NOT because of no file */
      char buf[MAX_STRING_LENGTH];
      sprintf(buf, "SYSERR: READING OBJECT FILE %s (5)", fname);
      perror(buf);
      send_to_char(ch, "\r\n********************* NOTICE *********************\r\n"
                       "There was a problem loading your objects from disk.\r\n"
                       "Contact a God for assistance.\r\n");
    }
    mudlog(NRM, MAX(LVL_IMMORT, GET_INVIS_LEV(ch)), TRUE, "%s entering game with no equipment.", GET_NAME(ch));
    return 1;
  }
  if (get_line(fl, line))
    sscanf(line,"%d %d %d %d %d %d",&rentcode, &timed,
           &netcost,&gold,&account,&nitems);

  if (rentcode == RENT_RENTED || rentcode == RENT_TIMEDOUT) {
    char str[64];
    sprintf(str, "%d", SECS_PER_REAL_DAY);
    num_of_days = (int)((float) (time(0) - timed) / (float)atoi(str));
    cost = (int) (netcost * num_of_days);
    if (cost > GET_GOLD(ch) + GET_BANK_GOLD(ch)) {
      fclose(fl);
      mudlog(BRF, MAX(LVL_IMMORT, GET_INVIS_LEV(ch)), TRUE, 
             "%s entering game, rented equipment lost (no $).", GET_NAME(ch));
      Crash_crashsave(ch);
      return 2;
    } else {
      GET_BANK_GOLD(ch) -= MAX(cost - GET_GOLD(ch), 0);
      GET_GOLD(ch) = MAX(GET_GOLD(ch) - cost, 0);
      save_char(ch);
    }
  }
  switch (orig_rent_code = rentcode) {
  case RENT_RENTED:
    mudlog(NRM, MAX(LVL_IMMORT, GET_INVIS_LEV(ch)), TRUE, 
           "%s un-renting and entering game.", GET_NAME(ch));
    break;
  case RENT_CRASH:

    mudlog(NRM, MAX(LVL_IMMORT, GET_INVIS_LEV(ch)), TRUE,
           "%s retrieving crash-saved items and entering game.", GET_NAME(ch));
    break;
  case RENT_CRYO:
    mudlog(NRM, MAX(LVL_IMMORT, GET_INVIS_LEV(ch)), TRUE,
           "%s un-cryo'ing and entering game.", GET_NAME(ch));
    break;
  case RENT_FORCED:
  case RENT_TIMEDOUT:
    mudlog(NRM, MAX(LVL_IMMORT, GET_INVIS_LEV(ch)), TRUE,
           "%s retrieving force-saved items and entering game.", GET_NAME(ch));
    break;
  default:
    mudlog(NRM, MAX(LVL_IMMORT, GET_INVIS_LEV(ch)), TRUE,
           "WARNING: %s entering game with undefined rent code.", GET_NAME(ch));
    break;
  }

  temp = NULL;
  while (get_line(fl, line)) {
    char tag[6];
    int num;

    /* first, we get the number. Not too hard. */
    if(*line == '$' && line[1] == '~') {
      if (temp)
        num_objs += handle_obj(temp, ch, locate, cont_row);
      break;
    }
    if (*line == '#') {
      if (sscanf(line, "#%d", &nr) != 1) {
        continue;
      } else {
        if (temp)
          num_objs += handle_obj(temp, ch, locate, cont_row);
        temp = NULL;
        locate = 0;
      }
      /* we have the number, check it, load obj. */
      if (nr == NOTHING) {   /* then it is unique */
        temp = create_obj();
        temp->item_number=NOTHING;
      } else if (nr < 0) {
        continue;
      } else {
        if(nr >= 999999) 
          continue;
        if(real_object(nr) != NOTHING) {
          temp=read_object(nr,VIRTUAL);
          if (!temp) {
            continue;
          }
        } else {
          log("Nonexistent object %d found in rent file.", nr);
          continue;
        }
      }
    }

    tag_argument(line, tag);
    num = atoi(line);

    switch(*tag) {
    case 'A':
      if (!strcmp(tag, "ADes")) {
      	char error[40];
      	snprintf(error, sizeof(error)-1, "rent(Ades):%s", temp->name);
        temp->action_description = fread_string(fl, error);
      } else if (!strcmp(tag, "Aff ")) {
        sscanf(line, "%d %d %d", &t[0], &t[1], &t[2]);
        if (t[0] < MAX_OBJ_AFFECT) {
          temp->affected[t[0]].location = t[1];
          temp->affected[t[0]].modifier = t[2];
        }
      }
      break;
    case 'C':
      if (!strcmp(tag, "Cost"))
        GET_OBJ_COST(temp) = num;
      break;
    case 'D':
      if (!strcmp(tag, "Desc"))
        temp->description = strdup(line);
      break;
    case 'E':
      if(!strcmp(tag, "EDes")) {
        struct extra_descr_data *new_desc;
        char error[40];
        snprintf(error, sizeof(error)-1, "rent(Edes): %s", temp->name);        
        if (temp->item_number != NOTHING && /* Regular object */
            temp->ex_description &&   /* with ex_desc == prototype */
            (temp->ex_description == obj_proto[real_object(temp->item_number)].ex_description))
          temp->ex_description = NULL;
        CREATE(new_desc, struct extra_descr_data, 1);
        new_desc->keyword = fread_string(fl, error);
        new_desc->description = fread_string(fl, error);
        new_desc->next = temp->ex_description;
        temp->ex_description = new_desc;
      }
      break;
    case 'F':
      if (!strcmp(tag, "Flag"))
        GET_OBJ_EXTRA(temp) = asciiflag_conv(line);
      break;
    case 'L':
      if(!strcmp(tag, "Loc "))
        locate = num;
      break;
    case 'N':
      if (!strcmp(tag, "Name"))
        temp->name = strdup(line);
      break;
    case 'P':
      if (!strcmp(tag, "Perm"))
        temp->obj_flags.bitvector = asciiflag_conv(line);
      break;
    case 'R':
      if (!strcmp(tag, "Rent"))
        GET_OBJ_RENT(temp) = num;
      break;
    case 'S':
      if (!strcmp(tag, "Shrt"))
        temp->short_description = strdup(line);
      break;
    case 'T':
      if (!strcmp(tag, "Type"))
        GET_OBJ_TYPE(temp) = num;
      break;
    case 'W':
      if (!strcmp(tag, "Wear"))
        GET_OBJ_WEAR(temp) = asciiflag_conv(line);
      else if (!strcmp(tag, "Wght"))
        GET_OBJ_WEIGHT(temp) = num;
      break;
    case 'V':
      if (!strcmp(tag, "Vals")) {
        sscanf(line, "%d %d %d %d", &t[0], &t[1], &t[2], &t[3]);
        for (i = 0; i < 4; i++)
          GET_OBJ_VAL(temp, i) = t[i];
      }
      break;
    }
  }
 
  /* Little hoarding check. -gg 3/1/98 */
 mudlog(NRM, MAX(LVL_GOD, GET_INVIS_LEV(ch)), TRUE, "%s (level %d) has %d objects (max %d).", 
         GET_NAME(ch), GET_LEVEL(ch), num_objs, max_obj_save);

  fclose(fl);

  if ((orig_rent_code == RENT_RENTED) || (orig_rent_code == RENT_CRYO))
    return 0;
  else
    return 1;
}
예제 #21
0
/**
* formerly obj_from_store
*
* @param FILE *fl The open item file.
* @param obj_vnum vnum The vnum of the item being loaded, or NOTHING for non-prototyped item.
* @param int *location A place to bind the current WEAR_x position of the item; also used to track container contents.
* @param char_data *notify Optional: A person to notify if an item is updated (NULL for none).
* @return obj_data* The loaded item, or NULL if it's not available.
*/
obj_data *Obj_load_from_file(FILE *fl, obj_vnum vnum, int *location, char_data *notify) {
	void scale_item_to_level(obj_data *obj, int level);

	char line[MAX_INPUT_LENGTH], error[MAX_STRING_LENGTH], s_in[MAX_INPUT_LENGTH];
	obj_data *proto = obj_proto(vnum);
	struct extra_descr_data *ex;
	obj_data *obj, *new;
	bool end = FALSE;
	int length, i_in[3];
	int l_in;
	bool seek_end = FALSE;
	
	// up-front
	*location = 0;
	
	// load based on vnum or, if NOTHING, create anonymous object
	if (proto) {
		obj = read_object(vnum, FALSE);
	}
	else {
		// what we do here depends on input ... if the vnum was real, but no proto, it's a deleted obj
		if (vnum == NOTHING) {
			obj = create_obj();
		}
		else {
			obj = NULL;
			seek_end = TRUE;	// signal it to skip obj data
		}
	}
	
	// default to version 0
	if (obj) {
		OBJ_VERSION(obj) = 0;
	}
	
	// for fread_string
	sprintf(error, "Obj_load_from_file %d", vnum);
	
	// for more readable if/else chain	
	#define OBJ_FILE_TAG(src, tag, len)  (!strn_cmp((src), (tag), ((len) = strlen(tag))))

	while (!end) {
		if (!get_line(fl, line)) {
			log("SYSERR: Unexpected end of obj file in Obj_load_from_file");
			exit(1);
		}
		
		if (OBJ_FILE_TAG(line, "End", length)) {
			end = TRUE;
		}
		else if (seek_end) {
			// are we looking for the end of the object? ignore this line
			// WARNING: don't put any ifs that require "obj" above seek_end; obj is not guaranteed
			continue;
		}
		else if (OBJ_FILE_TAG(line, "Version:", length)) {
			if (sscanf(line + length + 1, "%d", &i_in[0])) {
				OBJ_VERSION(obj) = i_in[0];
			}
		}
		else if (OBJ_FILE_TAG(line, "Location:", length)) {
			if (sscanf(line + length + 1, "%d", &i_in[0]) == 1) {
				*location = i_in[0];
			}
		}
		else if (OBJ_FILE_TAG(line, "Keywords:", length)) {
			if (GET_OBJ_KEYWORDS(obj) && (!proto || GET_OBJ_KEYWORDS(obj) != GET_OBJ_KEYWORDS(proto))) {
				free(GET_OBJ_KEYWORDS(obj));
			}
			GET_OBJ_KEYWORDS(obj) = fread_string(fl, error);
		}
		else if (OBJ_FILE_TAG(line, "Short-desc:", length)) {
			if (GET_OBJ_SHORT_DESC(obj) && (!proto || GET_OBJ_SHORT_DESC(obj) != GET_OBJ_SHORT_DESC(proto))) {
				free(GET_OBJ_SHORT_DESC(obj));
			}
			GET_OBJ_SHORT_DESC(obj) = fread_string(fl, error);
		}
		else if (OBJ_FILE_TAG(line, "Long-desc:", length)) {
			if (GET_OBJ_LONG_DESC(obj) && (!proto || GET_OBJ_LONG_DESC(obj) != GET_OBJ_LONG_DESC(proto))) {
				free(GET_OBJ_LONG_DESC(obj));
			}
			GET_OBJ_LONG_DESC(obj) = fread_string(fl, error);
		}
		else if (OBJ_FILE_TAG(line, "Action-desc:", length)) {
			if (GET_OBJ_ACTION_DESC(obj) && (!proto || GET_OBJ_ACTION_DESC(obj) != GET_OBJ_ACTION_DESC(proto))) {
				free(GET_OBJ_ACTION_DESC(obj));
			}
			GET_OBJ_ACTION_DESC(obj) = fread_string(fl, error);
		}
		else if (OBJ_FILE_TAG(line, "Extra-desc:", length)) {
			if (proto && obj->ex_description == proto->ex_description) {
				obj->ex_description = NULL;
			}
			
			CREATE(ex, struct extra_descr_data, 1);
			ex->next = obj->ex_description;
			obj->ex_description = ex;
			
			ex->keyword = fread_string(fl, error);
			ex->description = fread_string(fl, error);
		}
		else if (OBJ_FILE_TAG(line, "Val-0:", length)) {
			if (sscanf(line + length + 1, "%d", &i_in[0])) {
				GET_OBJ_VAL(obj, 0) = i_in[0];
			}
		}
		else if (OBJ_FILE_TAG(line, "Val-1:", length)) {
			if (sscanf(line + length + 1, "%d", &i_in[0])) {
				GET_OBJ_VAL(obj, 1) = i_in[0];
			}
		}
		else if (OBJ_FILE_TAG(line, "Val-2:", length)) {
			if (sscanf(line + length + 1, "%d", &i_in[0])) {
				GET_OBJ_VAL(obj, 2) = i_in[0];
			}
		}
		else if (OBJ_FILE_TAG(line, "Type:", length)) {
			if (sscanf(line + length + 1, "%d", &i_in[0])) {
				GET_OBJ_TYPE(obj) = i_in[0];
			}
		}
		else if (OBJ_FILE_TAG(line, "Wear:", length)) {
			if (sscanf(line + length + 1, "%s", s_in)) {
				GET_OBJ_WEAR(obj) = asciiflag_conv(s_in);
			}
		}
		else if (OBJ_FILE_TAG(line, "Flags:", length)) {
			if (sscanf(line + length + 1, "%s", s_in)) {
				GET_OBJ_EXTRA(obj) = asciiflag_conv(s_in);
			}
		}
		else if (OBJ_FILE_TAG(line, "Affects:", length)) {
			if (sscanf(line + length + 1, "%s", s_in)) {
				obj->obj_flags.bitvector = asciiflag_conv(s_in);
			}
		}
		else if (OBJ_FILE_TAG(line, "Timer:", length)) {
			if (sscanf(line + length + 1, "%d", &i_in[0])) {
				GET_OBJ_TIMER(obj) = i_in[0];
			}
		}
		else if (OBJ_FILE_TAG(line, "Current-scale:", length)) {
			if (sscanf(line + length + 1, "%d", &i_in[0])) {
				GET_OBJ_CURRENT_SCALE_LEVEL(obj) = i_in[0];
			}
		}
		else if (OBJ_FILE_TAG(line, "Min-scale:", length)) {
			if (sscanf(line + length + 1, "%d", &i_in[0])) {
				GET_OBJ_MIN_SCALE_LEVEL(obj) = i_in[0];
			}
		}
		else if (OBJ_FILE_TAG(line, "Max-scale:", length)) {
			if (sscanf(line + length + 1, "%d", &i_in[0])) {
				GET_OBJ_MAX_SCALE_LEVEL(obj) = i_in[0];
			}
		}
		else if (OBJ_FILE_TAG(line, "Material:", length)) {
			if (sscanf(line + length + 1, "%d", &i_in[0])) {
				GET_OBJ_MATERIAL(obj) = i_in[0];
			}
		}
		else if (OBJ_FILE_TAG(line, "Last-empire:", length)) {
			if (sscanf(line + length + 1, "%d", &i_in[0])) {
				obj->last_empire_id = i_in[0];
			}
		}
		else if (OBJ_FILE_TAG(line, "Last-owner:", length)) {
			if (sscanf(line + length + 1, "%d", &l_in)) {
				obj->last_owner_id = l_in;
			}
		}
		else if (OBJ_FILE_TAG(line, "Stolen-timer:", length)) {
			if (sscanf(line + length + 1, "%d", &i_in[0])) {
				obj->stolen_timer = i_in[0];
			}
		}
		else if (OBJ_FILE_TAG(line, "Autostore-timer:", length)) {
			if (sscanf(line + length + 1, "%d", &i_in[0])) {
				GET_AUTOSTORE_TIMER(obj) = i_in[0];
			}
		}
		else if (OBJ_FILE_TAG(line, "Apply:", length)) {
			if (sscanf(line + length + 1, "%d %d %d", &i_in[0], &i_in[1], &i_in[2])) {
				obj->affected[i_in[0]].location = i_in[1];
				obj->affected[i_in[0]].modifier = i_in[2];
			}
		}
		else if (OBJ_FILE_TAG(line, "Bound-to:", length)) {
			if (sscanf(line + length + 1, "%d", &i_in[0])) {
				struct obj_binding *bind;
				CREATE(bind, struct obj_binding, 1);
				bind->idnum = i_in[0];
				bind->next = OBJ_BOUND_TO(obj);
				OBJ_BOUND_TO(obj) = bind;
			}
		}
		else if (OBJ_FILE_TAG(line, "Trigger:", length)) {
예제 #22
0
obj_t * create_logfile_obj(server_conf_t *conf, char *name,
    obj_t *console, logopt_t *opts, char *errbuf, int errlen)
{
/*  Creates a new logfile object and adds it to the master objs list.
 *    Note: the logfile is open and set for non-blocking I/O.
 *  Note: the logfile will later be opened and set for non-blocking I/O
 *    by main:open_objs:reopen_obj:open_logfile_obj().
 *  Returns the new object, or NULL on error.
 */
    ListIterator i;
    obj_t *logfile;
    char buf[MAX_LINE];
    char *pname;
    obj_t *obj;

    assert(conf != NULL);
    assert((name != NULL) && (name[0] != '\0'));
    assert(console != NULL);
    assert(opts != NULL);

    /*  Check for duplicate logfile names.
     *  While the write-lock will protect against two separate daemons
     *    using the same logfile, it will not protect against two logfile
     *    objects within the same daemon process using the same filename.
     *    So that check is performed here.
     */
    if (strchr(name, '%')
            && (format_obj_string(buf, sizeof(buf), console, name) >= 0)) {
        pname = buf;
    }
    else {
        pname = name;
    }

    i = list_iterator_create(conf->objs);
    while ((logfile = list_next(i))) {
        if (!is_logfile_obj(logfile)) {
            continue;
        }
        if (!strcmp(logfile->name, pname)) {
            break;
        }
    }
    list_iterator_destroy(i);

    if (logfile) {
        snprintf(errbuf, errlen, "console [%s] already logging to \"%s\"",
            logfile->aux.logfile.console->name, pname);
        return(NULL);
    }
    logfile = create_obj(conf, name, -1, CONMAN_OBJ_LOGFILE);
    logfile->aux.logfile.console = console;
    logfile->aux.logfile.lineState = CONMAN_LOG_LINE_INIT;
    logfile->aux.logfile.opts = *opts;
    logfile->aux.logfile.gotTruncate = !!conf->enableZeroLogs;

    if (logfile->aux.logfile.opts.enableSanitize
            || logfile->aux.logfile.opts.enableTimestamp) {
        logfile->aux.logfile.gotProcessing = 1;
    }
    else {
        logfile->aux.logfile.gotProcessing = 0;
    }

    if (strchr(name, '%')) {
        logfile->aux.logfile.fmtName = create_string(name);
    }
    else {
        logfile->aux.logfile.fmtName = NULL;
    }

    if (is_process_obj(console)) {
        console->aux.process.logfile = logfile;
    }
    else if (is_serial_obj(console)) {
        console->aux.serial.logfile = logfile;
    }
    else if (is_telnet_obj(console)) {
        console->aux.telnet.logfile = logfile;
    }
    else if (is_unixsock_obj(console)) {
        console->aux.unixsock.logfile = logfile;
    }
#if WITH_FREEIPMI
    else if (is_ipmi_obj(console)) {
        console->aux.ipmi.logfile = logfile;
    }
#endif /* WITH_FREEIPMI */
    else {
        log_err(0, "INTERNAL: Unrecognized console [%s] type=%d",
            console->name, console->type);
    }
    /*  Add obj to the master conf->objs list
     *    before its corresponding console obj.
     */
    i = list_iterator_create(conf->objs);
    while ((obj = list_next(i))) {
        if (obj == console) {
            list_insert(i, logfile);
            break;
        }
    }
    list_iterator_destroy(i);
    if (!obj) {
        log_err(0, "INTERNAL: Console [%s] object not found in master list",
            console->name);
    }
    return(logfile);
}
예제 #23
0
/*
 * read_scroll:
 *	Let the hero read a scroll
 */
int read_scroll()
{
	struct object *obj;
	struct linked_list *item;
	int i, j, wh;
	unsigned long ch, nch;
	struct room *rp;
	struct linked_list *titem;
	char buf[LINLEN];
	bool bless, curse;

	if ((item = get_item("read", SCROLL)) == NULL)
		return 0;
	obj = OBJPTR(item);
	if (obj->o_type != SCROLL) {
		msg("Nothing to read.");
		after = FALSE;
		return 0;
	}
	msg("As you read the scroll, it vanishes.");
	wh = obj->o_which;
	bless = o_on(obj, ISBLESS);
	curse = o_on(obj, ISCURSED);
	del_pack(item);		/* Get rid of the thing */

	/*
	 * Calculate the effect it has on the hero
	 */
	switch(wh) {
	case S_KNOWALL:
		if (!curse) {
			idenpack();				/* identify all the pack */
			msg("You feel more knowledgable.");
			chg_abil(WIS,1,TRUE);
			s_know[S_KNOWALL] = TRUE;
		}
	when S_CONFUSE:
		if (!curse) {
			/*
			 * Scroll of monster confusion.  Give him that power.
			 */
			msg("Your hands begin to glow red.");
			player.t_flags |= CANHUH;
			s_know[S_CONFUSE] = TRUE;
		}
	when S_LIGHT:
		rp = player.t_room;
		if (!curse) {
			if (rp == NULL) {
				s_know[S_LIGHT] = TRUE;
				msg("The corridor glows and then fades.");
			}
			else {
				if (rf_on(rp,ISDARK)) {
					s_know[S_LIGHT] = TRUE;
					msg("The room is lit.");
					rp->r_flags &= ~ISDARK;
				}
				light(&hero);
				mvwaddch(cw, hero.y, hero.x, PLAYER);
			}
		}
	when S_ARMOR:
		if (!curse) {
			if (cur_armor != NULL && o_off(cur_armor,ISPROT)) {
				s_know[S_ARMOR] = TRUE;
				msg("Your armor glows faintly for a moment.");
				if (o_on(cur_armor,ISCURSED))
					cur_armor->o_ac = armors[cur_armor->o_which].a_class;
				else
					cur_armor->o_ac--;
				resoflg(cur_armor,ISCURSED);
			}
		}
	when S_HOLD:
		if (!curse) {
			/*
			 * Hold monster scroll.  Stop all monsters within 3 spaces
			 * from chasing after the hero.
			 */
			int x,y;
			struct linked_list *mon;

			for (x = hero.x - 3; x <= hero.x + 3; x++) {
				for (y = hero.y - 3; y <= hero.y + 3; y++) {
					if (y > 0 && x > 0 && isalpha(mvwinch(mw, y, x))) {
						if ((mon = find_mons(y, x)) != NULL) {
							struct thing *th;

							th = THINGPTR(mon);
							th->t_flags &= ~ISRUN;
							th->t_flags |= ISHELD;
							th->t_flags |= ISSTUCK;
						}
					}
				}
			}
		}
	when S_SLEEP:
		/*
		 * Scroll which makes you fall asleep
		 */
		if (!bless) {
			s_know[S_SLEEP] = TRUE;
			msg("You fall asleep.");
			player.t_nocmd += 4 + rnd(SLEEPTIME);
		}
	when S_CREATE:
		if (!bless) {
			if (makemons(mtlev[rnd(levcount)]->m_show))
				s_know[S_CREATE] = TRUE;
			else
				msg("You hear a faint cry of anguish in the distance.");
		}
	when S_IDENT:
		if (!curse) {
			msg("This scroll is an identify scroll");
			s_know[S_IDENT] = TRUE;
			whatis(NULL);
		}
	when S_MAP:
		if (curse)
			break;
		s_know[S_MAP] = TRUE;
		addmsg("Oh, now this scroll has a ");
		if (rnd(100) < 10 || bless) {
			addmsg("very detailed map on it.");
			endmsg();
			displevl();
		}
		else {
			addmsg("map on it.");
			endmsg();
			overwrite(stdscr, hw);
			for (i = 1; i < LINES - 2; i++) {
				for (j = 0; j < COLS; j++) {
					switch (nch = ch = mvwinch(hw, i, j)) {
						case SECRETDOOR:
							nch = DOOR;
							mvaddch(i, j, nch);
						case '-':
						case '|':
						case DOOR:
						case PASSAGE:
						case ' ':
						case STAIRS:
							if (mvwinch(mw, i, j) != ' ') {
								struct thing *it;
								struct linked_list *blah;

								blah = find_mons(i, j);
								if (blah != NULL) {
									it = THINGPTR(blah);
									if (it->t_oldch == ' ')
										it->t_oldch = nch;
								}
							}
							break;
						default:
							nch = ' ';
					}
					if (nch != ch)
						waddch(hw, nch);
				}
			}
			overlay(cw, hw);
			overwrite(hw, cw);
		}
	when S_GFIND:
		if (!curse) {
			int gtotal = 0;
			struct room *rp;

			wclear(hw);
			for (rp = rooms; rp < &rooms[MAXROOMS]; rp++) {
				gtotal += rp->r_goldval;
				if (rp->r_goldval != 0 &&
				  mvinch(rp->r_gold.y,rp->r_gold.x) == GOLD)
					mvwaddch(hw,rp->r_gold.y,rp->r_gold.x,GOLD);
			}
			if (gtotal) {
				s_know[S_GFIND] = TRUE;
				msg("You begin to feel greedy and sense gold.");
				overlay(hw,cw);
			}
			else
				msg("You begin to feel a pull downward.");
		}
	when S_TELEP:
		if (!curse) {
			int rm;
			struct room *cur_room;

			cur_room = player.t_room;
			rm = teleport(rndspot, &player);
			if (cur_room != &rooms[rm])
				s_know[S_TELEP] = TRUE;
		}
	when S_ENCH:
		if (!curse) {
			if (cur_weapon == NULL || (cur_weapon != NULL &&
			  (o_on(cur_weapon,ISPROT) || cur_weapon->o_type != WEAPON)))
				msg("You feel a strange sense of loss.");
			else {
				s_know[S_ENCH] = TRUE;
				if (o_on(cur_weapon,ISCURSED)) {
					resoflg(cur_weapon,ISCURSED);
					cur_weapon->o_hplus = rnd(2);
					cur_weapon->o_dplus = rnd(2);
				}
				else {		/* weapon was not cursed here */
					if (rnd(100) < 50)
						cur_weapon->o_hplus += 1;
					else
						cur_weapon->o_dplus += 1;
				}
				setoflg(cur_weapon, ISKNOW);
				msg("Your %s glows blue for a moment.",
				  w_magic[cur_weapon->o_which].mi_name);
			}
		}
	when S_SCARE:
		/*
		 * A monster will refuse to step on a scare monster scroll
		 * if it is dropped.  Thus reading it is a mistake and produces
		 * laughter at the poor rogue's boo boo.
		 */
		msg("You hear maniacal laughter in the distance.");
	when S_REMOVE:
		if (!curse) {
			if (cur_armor != NULL && o_off(cur_armor,ISPROT))
				resoflg(cur_armor,ISCURSED);
			if (cur_weapon != NULL && o_off(cur_weapon,ISPROT))
				resoflg(cur_weapon,ISCURSED);
			if (cur_ring[LEFT]!=NULL && o_off(cur_ring[LEFT],ISPROT))
				resoflg(cur_ring[LEFT],ISCURSED);
			if (cur_ring[RIGHT]!=NULL && o_off(cur_ring[RIGHT],ISPROT))
				resoflg(cur_ring[RIGHT],ISCURSED);
			msg("You feel as if somebody is watching over you.");
			s_know[S_REMOVE] = TRUE;
		}
	when S_AGGR:
		if (!bless) {
			if (mlist != NULL) {
				aggravate();
				msg("You hear a high pitched humming noise.");
				s_know[S_AGGR] = TRUE;
			}
		}
	when S_NOP:
		msg("This scroll seems to be blank.");
	when S_GENOCIDE:
		if (!curse) {
			msg("You have been granted the boon of genocide.");
			genocide();
			s_know[S_GENOCIDE] = TRUE;
		}
	when S_DCURSE:
		if (!bless) {
			struct linked_list *ll;
			struct object *lb;

			msg("Your pack shudders.");
			for (ll = pack ; ll != NULL ; ll = next(ll)) {
				lb = OBJPTR(ll);
				if (o_off(lb,ISPROT)) {
					resoflg(lb, ISBLESS);
					setoflg(lb, ISCURSED);
				}
			}
		}
	when S_DLEVEL:
		if (!bless) {
			int much = rnd(9) - 4;

			if (much != 0) {
				level += much;
				if (level < 1)
					level = 1;
				mpos = 0;
				new_level(NORMLEV);		/* change levels */
				msg("You are whisked away to another region.");
				s_know[S_DLEVEL] = TRUE;
			}
		}
	when S_PROTECT:
		if (!curse) {
			struct linked_list *ll;
			struct object *lb;

			msg("You are granted the power of protection.");
			if ((ll = get_item("protect",0)) != NULL) {
				lb = OBJPTR(ll);
				setoflg(lb,ISPROT);
				mpos = 0;
				msg("Protected %s.",inv_name(lb,TRUE));
			}
			s_know[S_PROTECT] = TRUE;
		}
	when S_ALLENCH:
		if (!curse) {
			struct linked_list *ll;
			struct object *lb;
			int howmuch, ac, good;

			msg("You are granted the power of enchantment.");
			good = TRUE;
			if ((ll = get_item("enchant",0)) != NULL) {
				lb = OBJPTR(ll);
				resoflg(lb,ISCURSED);
				resoflg(lb,ISPROT);
				howmuch = rnd(3) + 1;
				switch(lb->o_type) {
					case RING:
						if (lb->o_ac < 0)
							lb->o_ac = 0;
						lb->o_ac += howmuch;
					when ARMOR:
						ac = armors[lb->o_which].a_class;
						if (lb->o_ac > ac)
							lb->o_ac = ac;
						lb->o_ac -= howmuch;
					when STICK:
						lb->o_charges += howmuch + 10;
					when WEAPON:
						if (lb->o_dplus < 0)
							lb->o_dplus = 0;
						if (lb->o_hplus < 0)
							lb->o_hplus = 0;
						lb->o_hplus += howmuch;
						lb->o_dplus += howmuch;
					otherwise:
						msg("You are injured as the scroll flashes & bursts into flames !!!");
						chg_hpt(-roll(6,6),FALSE,K_SCROLL);
						good = FALSE;
				}
				if (good) {
					mpos = 0;
					msg("Enchanted %s.",inv_name(lb,TRUE));
				}
			}
			s_know[S_ALLENCH] = TRUE;
		}
	when S_BLESS:
		if (!curse) {
			struct linked_list *ll;
			struct object *lb;

			msg("Your pack glistens brightly.");
			for (ll = pack ; ll != NULL ; ll = next(ll)) {
				whatis(ll);
				lb = OBJPTR(ll);
				resoflg(lb,ISCURSED);
				setoflg(lb,ISBLESS);
			}
		}
	when S_MAKEIT:
		if (!curse) {
			msg("You have been endowed with the power of creation.");
			s_know[S_MAKEIT] = TRUE;
			create_obj(TRUE);
		}
	when S_BAN: {
		int howdeep;
		char *ptr;

		if (bless) {
			if (level > 6) {
				howdeep = 1 + rnd(5);
				ptr = "elevated to the upper";
			}
			else {
				howdeep = -1;
				bless = FALSE;
			}
		}
		else {
			howdeep = level + 10 + rnd(20) + (curse * 20);
			ptr = "banished to the lower";
		}
		if ((!bless && level < howdeep) || bless) {
			level = howdeep;
			new_level(NORMLEV);
			mpos = 0;
			msg("You are %s regions.", ptr);
			s_know[S_BAN] = TRUE;
		}
	}
	when S_CWAND:
		if (!curse) {
			struct linked_list *ll;
			struct object *lb;
			bool wands = FALSE;

			for (ll = pack ; ll != NULL ; ll = next(ll)) {
				lb = OBJPTR(ll);
				if (lb->o_type == STICK) {
					whatis(ll);
					setoflg(lb, ISKNOW);
					resoflg(lb, ISCURSED);
					lb->o_charges += rnd(11) + 5;
					wands = TRUE;
				}
			}
			if (wands) {
				msg("Your sticks gleam.");
				s_know[wh] = TRUE;
			}
		}
	when S_LOCTRAP: {
		struct trap *trp;

		if (ntraps > 0) {
			for (trp = &traps[0]; trp < &traps[ntraps]; trp++)
				trp->tr_flags |= ISFOUND;
			look(FALSE);
			msg("You now recognize pitfalls.");
			s_know[S_LOCTRAP] = TRUE;
		}
	}
	otherwise:
		msg("What a puzzling scroll!");
		return 0;
	}
예제 #24
0
ObjectPool<Type>::ObjectPool(unsigned size,bool _dynamic_malloc) {
	dynamic_malloc=_dynamic_malloc;
	prev_create=0;
	create_obj(size);
	cur_pool=this;
}
예제 #25
0
파일: websockets.c 프로젝트: pez2001/node.c
static int callback_nyx_websockets(struct libwebsocket_context *context,struct libwebsocket *wsi,enum libwebsocket_callback_reasons reason, void *user,void *in,size_t len)
{
  struct per_session_data_nyx *pss =(struct per_session_data_nyx*)user;
  int n;

  node *wsd_state = (node*)libwebsocket_context_user(context);
  //node *daemon = (node*)libwebsocket_context_user(context);
  //node *wsd_state = node_GetNode(get_value(daemon));
  node *found_prot = NULL;
  node *state = NULL;
  node *block = NULL;
  //node *daemon = NULL;
  node *daemon_obj = NULL;
  node *session_uid = NULL;
  long lsession_uid = 0;
  node *sessions_num = NULL;
  node *sessions = NULL;
  long lsessions_num = 0;
  
  if(wsd_state)
  {
    state = node_GetItem(wsd_state,0);
    block = node_GetItem(wsd_state,1);
    //daemon = node_GetItem(wsd_state,2);
    node *protocols = node_GetItem(wsd_state,3);
    session_uid = node_GetItem(wsd_state,4);
    node *session_uid_value = node_GetItemByKey(session_uid,"value");
    lsession_uid = node_GetSint32(session_uid_value);
    sessions_num = node_GetItem(wsd_state,5);
    sessions = node_GetItem(wsd_state,6);
    node *sessions_num_value = node_GetItemByKey(sessions_num,"value");
    lsessions_num = node_GetSint32(sessions_num_value);
    daemon_obj = node_GetItem(wsd_state,9);
    if(wsi)
    {
      node *protocols_items = node_GetItemByKey(protocols,"items");
      const struct libwebsocket_protocols *prot = libwebsockets_get_protocol(wsi);
      if(prot && prot->name)
      {
        node_ItemIterationReset(protocols_items);
        while(node_ItemIterationUnfinished(protocols_items))
        {
          node *proto = node_ItemIterate(protocols_items);
          if(!strcmp(get_obj_name(proto),prot->name))
          {
            found_prot = proto;
          }
        }
      }
    }
  }

  switch(reason) 
  {

    //case LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED:
    case LWS_CALLBACK_CLIENT_ESTABLISHED:
      printf("new session created:%d, num:%d\n",lsession_uid,lsessions_num);
      pss->session = NULL;
      break;

    case LWS_CALLBACK_HTTP:
      if(len < 1)
      {
        libwebsockets_return_http_status(context,wsi,HTTP_STATUS_BAD_REQUEST,NULL);
        return(-1);
      }
      if(lws_hdr_total_length(wsi,WSI_TOKEN_POST_URI))
        return(0);

      if(found_prot)
      {
        //printf("found prot in http callback : uid:%d,num:%d (sess:%x)\n",lsession_uid+1,lsessions_num,pss->session);
        if(!pss->session)
        {
          lsession_uid++;
          node *session_uid_value = node_GetItemByKey(session_uid,"value");
          node_SetSint32(session_uid_value,lsession_uid);
          lsessions_num++;
          node *sessions_num_value = node_GetItemByKey(sessions_num,"value");
          node_SetSint32(sessions_num_value,lsessions_num);
          pss->session = create_session(state,sessions,lsession_uid,get_obj_name(found_prot));
          node *session_privates = node_GetItemByKey(pss->session,"privates");
          set_obj_int(session_privates,"is_http",1);
          //printf("created new session :%d actual sessions num:%d\n",lsession_uid,lsessions_num);
        }
        

        node *parameters = create_obj("parameters");
        node *base_class = get_base_class(state);
        node *prot_value = create_class_instance(base_class);
        set_obj_string(prot_value,"name","protocol");
        set_obj_string(prot_value,"value",get_obj_name(found_prot));
        node_AddItem(parameters,prot_value);
        inc_obj_refcount(prot_value);
        char *url = str_CreateEmpty();
        url = str_AddChars(url,in,len);
        node *url_value = create_class_instance(base_class);
        set_obj_string(url_value,"name","url");
        set_obj_string(url_value,"value",url);
        node_AddItem(parameters,url_value);
        inc_obj_refcount(url_value);
        free(url);
        node_AddItem(parameters,pss->session);
        inc_obj_refcount(pss->session);
        //node_AddItem(parameters,daemon_obj);
        node_AddItem(parameters,sessions);
        inc_obj_refcount(sessions);
        node *tmp_parent = node_GetParent(found_prot);
        node *bmembers = node_GetItemByKey(block,"members");
        node_SetParent(found_prot,bmembers);
        node *ret_obj = execute_obj(state,found_prot,block,parameters,True,False);//,True);resolve
        node_SetParent(found_prot,tmp_parent);
        //dec_obj_refcount(msg_value);
        dec_obj_refcount(prot_value);
        //add_garbage(state,msg_value);//TODO check if "just survives"
        add_garbage(state,prot_value);
        dec_obj_refcount(url_value);
        add_garbage(state,url_value);
        dec_obj_refcount(pss->session);
        dec_obj_refcount(sessions);
 
        node *ret_obj_value = node_GetItemByKey(ret_obj,"value");
        if( (node_GetType(ret_obj_value)==NODE_TYPE_STRING && strlen(node_GetString(ret_obj_value))) || (node_GetType(ret_obj_value)==NODE_TYPE_BINARY && node_GetBinaryLength(ret_obj_value)) )
        {
          //printf("returning http message: [%s] :%d\n",node_GetString(ret_obj_value),strlen(node_GetString(ret_obj_value)));
          //node *ret_obj_copy = node_CopyTree(ret_obj,True,True);
          node *ret_obj_copy = copy_class(ret_obj);
          //reset_obj_refcount(ret_obj_copy);
          set_obj_string(ret_obj_copy,"name","message");
          add_member(pss->session,ret_obj_copy);
          inc_obj_refcount(ret_obj_copy);
        }
        libwebsocket_callback_on_writable(context, wsi);
      }
      break;

    case LWS_CALLBACK_HTTP_BODY_COMPLETION:
      if(found_prot)
      {
        printf("found prot in http body complete : %d,num:%d\n",lsession_uid,lsessions_num);
        if(daemon_obj)
        {
          printf("body: found daemon_obj\n");
        }
      }
      else
        printf("body closed: prot not found\n");
      //lwsl_notice("LWS_CALLBACK_HTTP_BODY_COMPLETION\n");
      libwebsockets_return_http_status(context,wsi,HTTP_STATUS_OK,NULL);
     return(-1);

    case LWS_CALLBACK_HTTP_FILE_COMPLETION:
      if(found_prot)
     {
        //printf("found prot in http file complete : %d,num:%d\n",lsession_uid,lsessions_num);
        lsessions_num--;
        node *sessions_num_value = node_GetItemByKey(sessions_num,"value");
        node_SetSint32(sessions_num_value,lsessions_num);
        delete_session(state,sessions,pss->session);
        pss->session = NULL;
        if(daemon_obj)
        {
          printf("http: found daemon_obj\n");
        }
      }
      else
        printf("file closed: prot not found\n");
      return(-1);

    case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
      if(found_prot)
      {
      int n;
      static const char *token_names[] = 
      {
        /*[WSI_TOKEN_GET_URI]   =*/ "GET URI",
        /*[WSI_TOKEN_POST_URI]    =*/ "POST URI",
        /*[WSI_TOKEN_OPTIONS]    =*/ "Options",
        /*[WSI_TOKEN_HOST]    =*/ "Host",
        /*[WSI_TOKEN_CONNECTION]  =*/ "Connection",
        /*[WSI_TOKEN_KEY1]    =*/ "key 1",
        /*[WSI_TOKEN_KEY2]    =*/ "key 2",
        /*[WSI_TOKEN_PROTOCOL]    =*/ "Protocol",
        /*[WSI_TOKEN_UPGRADE]   =*/ "Upgrade",
        /*[WSI_TOKEN_ORIGIN]    =*/ "Origin",
        /*[WSI_TOKEN_DRAFT]   =*/ "Draft",
        /*[WSI_TOKEN_CHALLENGE]   =*/ "Challenge",
        /* new for 04 */
        /*[WSI_TOKEN_KEY]   =*/ "Key",
        /*[WSI_TOKEN_VERSION]   =*/ "Version",
        /*[WSI_TOKEN_SWORIGIN]    =*/ "Sworigin",
        /* new for 05 */
        /*[WSI_TOKEN_EXTENSIONS]  =*/ "Extensions",
        /* client receives these */
        /*[WSI_TOKEN_ACCEPT]    =*/ "Accept",
        /*[WSI_TOKEN_NONCE]   =*/ "Nonce",
        /*[WSI_TOKEN_HTTP]    =*/ "Http",
        "Accept:",
        "Accept_Request_Headers:",
        "If-None-Match:",
        "If-Modified-Since:",
        "Accept-Encoding:",
        "Accept-Language:",
        "Pragma:",
        "Cache-Control:",
        "Authorization:",
        "Cookie:",
        "Content-Length:",
        "Content-Type:",
        "Date:",
        "Range:",
        "Referer:",
        "Uri-Args:",
        /*[WSI_TOKEN_MUXURL]  =*/ "MuxURL",
      };

      //printf("found prot in http filter callback : uid:%d,num:%d (sess:%x)\n",lsession_uid+1,lsessions_num,pss->session);
      if(!pss->session)
      {
        lsession_uid++;
        node *session_uid_value = node_GetItemByKey(session_uid,"value");
        node_SetSint32(session_uid_value,lsession_uid);
        lsessions_num++;
        node *sessions_num_value = node_GetItemByKey(sessions_num,"value");
        node_SetSint32(sessions_num_value,lsessions_num);
        pss->session = create_session(state,sessions,lsession_uid,get_obj_name(found_prot));
        //node *session_privates = node_GetItemByKey(pss->session,"privates");
        //set_obj_int(session_privates,"is_http",1);
      }
      //printf("filter sess:%x\n",pss->session);


      for(n=0;n<(int)(sizeof(token_names)/sizeof(token_names[0]));n++) 
      {
        if (!lws_hdr_total_length(wsi, n))
          continue;
        char *cookies = (char*)malloc(512);
        memset(cookies,0,512);
        lws_hdr_copy(wsi,cookies,511,n);
        //printf("header:%s = [%s]\n",token_names[n],cookies);
        //fflush(stdout);
        if(pss->session && !strcmp("Cookie:",token_names[n]))
        {
          //printf("cookie found:%s = [%s]\n",token_names[n],cookies);
          //fflush(stdout);
          node *base_class = get_base_class(state);
          node *cookie_value = create_class_instance(base_class);
          set_obj_string(cookie_value,"name","cookie");
          set_obj_string(cookie_value,"value",cookies);
          add_member(pss->session,cookie_value);
          inc_obj_refcount(cookie_value);
        }
        free(cookies);
      }
      }
    break;

    case LWS_CALLBACK_HTTP_WRITEABLE: 
    case LWS_CALLBACK_SERVER_WRITEABLE:
      {
        //node_PrintTree(pss->session);
        node *message = get_member(pss->session,"message");
        node *session_privates = node_GetItemByKey(pss->session,"privates");
        node *http_only = node_GetItemByKey(session_privates,"is_http");

        while(message)
        {
          //node *session_id = get_member(pss->session,"id");
          //node *session_id_value = node_GetItemByKey(session_id,"value");
          node *message_value = node_GetItemByKey(message,"value");
          unsigned char *me = NULL;
          unsigned long me_len = 0;
          if(node_GetType(message_value)==NODE_TYPE_STRING)
          {
            me = (unsigned char*)node_GetString(message_value);
            me_len = strlen((char*)me);
          }
          else if(node_GetType(message_value)==NODE_TYPE_BINARY)
          {
            me = (unsigned char*)node_GetBinary(message_value);
            me_len = node_GetBinaryLength(message_value);
          }
          //printf("sending message now: [%s] to: %d\n",me,node_GetSint32(session_id_value));
          //fflush(stdout);
          unsigned char *buf = (unsigned char*)malloc(LWS_SEND_BUFFER_PRE_PADDING + me_len + LWS_SEND_BUFFER_POST_PADDING);
          memcpy(buf+LWS_SEND_BUFFER_PRE_PADDING,me,me_len);

          if(http_only)
            //n = libwebsocket_write(wsi, me, me_len, LWS_WRITE_HTTP);
            n = libwebsocket_write(wsi,buf+LWS_SEND_BUFFER_PRE_PADDING,me_len,LWS_WRITE_HTTP);
          else
            //n = libwebsocket_write(wsi, me, me_len, LWS_WRITE_TEXT);
            n = libwebsocket_write(wsi,buf+LWS_SEND_BUFFER_PRE_PADDING,me_len,LWS_WRITE_TEXT);
          free(buf);
          if(n<0)
          {
            printf("ERROR %d writing to socket, hanging up\n", n);
            return(1);
          }
          if(n<(long)me_len)
          {
            printf("Partial write\n");
            return(-1);
          }
          //node_FreeTree(pss->message);
          remove_member(pss->session,message);
          dec_obj_refcount(message);
          //printf("removing message from queue:%x (%d)\n",message,get_obj_refcount(message));
          add_garbage(state,message);
          message = get_member(pss->session,"message");          
        }
        if(http_only)
        {
          //if(lws_http_transaction_completed(wsi))
          //{
            //printf("removing http session num:%d\n",lsessions_num);
            lsessions_num--;
            node *sessions_num_value = node_GetItemByKey(sessions_num,"value");
            node_SetSint32(sessions_num_value,lsessions_num);
            delete_session(state,sessions,pss->session);
            pss->session = NULL;
            //printf("removed http\n");
              return -1;
            //return(-1);
          //}
          //else
          //  libwebsocket_callback_on_writable(context, wsi);
        }
      }
      break;

    case LWS_CALLBACK_ESTABLISHED:
      if(found_prot)
      {
        //printf("found prot in establish callback : uid:%d,num:%d (sess:%x)\n",lsession_uid+1,lsessions_num,pss->session);
        if(!pss->session)
        {
          lsession_uid++;
          node *session_uid_value = node_GetItemByKey(session_uid,"value");
          node_SetSint32(session_uid_value,lsession_uid);
          lsessions_num++;
          node *sessions_num_value = node_GetItemByKey(sessions_num,"value");
          node_SetSint32(sessions_num_value,lsessions_num);
          pss->session = create_session(state,sessions,lsession_uid,get_obj_name(found_prot));
        }
        if(daemon_obj)
        {
          node *connect_handler = get_member(daemon_obj,"connect_handler");
          if(connect_handler)
          {
            connect_handler = resolve_object(state,connect_handler);
            node *parameters = create_obj("parameters");
            node *base_class = get_base_class(state);
      
            node *prot_value = create_class_instance(base_class);
            set_obj_string(prot_value,"name","protocol");
            set_obj_string(prot_value,"value",get_obj_name(found_prot));
            node_AddItem(parameters,prot_value);
            inc_obj_refcount(prot_value);

            node_AddItem(parameters,pss->session);
            inc_obj_refcount(pss->session);
            node_AddItem(parameters,sessions);
            inc_obj_refcount(sessions);
            node *tmp_parent = node_GetParent(connect_handler);
            node *bmembers = node_GetItemByKey(block,"members");
            node_SetParent(connect_handler,bmembers);
            node *ret_obj = execute_obj(state,connect_handler,block,parameters,True,False);//,True);resolve
            node_SetParent(connect_handler,tmp_parent);
            dec_obj_refcount(prot_value);
            add_garbage(state,prot_value);
            dec_obj_refcount(pss->session);
            dec_obj_refcount(sessions);
            node *ret_obj_value = node_GetItemByKey(ret_obj,"value");
            if(node_GetType(ret_obj_value)==NODE_TYPE_STRING && strlen(node_GetString(ret_obj_value)))
            {
            }
          }
        }
      }
      break;

    case LWS_CALLBACK_CLOSED_HTTP:
    break;
    
    case LWS_CALLBACK_CLOSED:
    case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
      if(found_prot)
      {
        //printf("found prot in closed callback : uid:%d,num:%d (sess:%x)\n",lsession_uid,lsessions_num,pss->session);
        if(daemon_obj)
        {
        //printf("closed: found daemon_obj\n");
          node *disconnect_handler = get_member(daemon_obj,"disconnect_handler");
          if(disconnect_handler)
          {
            //printf("disc found\n");
            disconnect_handler = resolve_object(state,disconnect_handler);
            node *parameters = create_obj("parameters");
            node *base_class = get_base_class(state);
      
            node *prot_value = create_class_instance(base_class);
            set_obj_string(prot_value,"name","protocol");
            set_obj_string(prot_value,"value",get_obj_name(found_prot));
            node_AddItem(parameters,prot_value);
            inc_obj_refcount(prot_value);

            node_AddItem(parameters,pss->session);
            inc_obj_refcount(pss->session);
            node_AddItem(parameters,sessions);
            inc_obj_refcount(sessions);
            node *tmp_parent = node_GetParent(disconnect_handler);
            node *bmembers = node_GetItemByKey(block,"members");
            node_SetParent(disconnect_handler,bmembers);
            node *ret_obj = execute_obj(state,disconnect_handler,block,parameters,True,False);//,True);resolve
            node_SetParent(disconnect_handler,tmp_parent);
            dec_obj_refcount(prot_value);
            add_garbage(state,prot_value);
            dec_obj_refcount(pss->session);
            dec_obj_refcount(sessions);
            node *ret_obj_value = node_GetItemByKey(ret_obj,"value");
            if(node_GetType(ret_obj_value)==NODE_TYPE_STRING && strlen(node_GetString(ret_obj_value)))
            {
            }
          }
        }
        lsessions_num--;
        node *sessions_num_value = node_GetItemByKey(sessions_num,"value");
        node_SetSint32(sessions_num_value,lsessions_num);
        delete_session(state,sessions,pss->session);
        pss->session = NULL;
        //printf("disconnected\n");
      }
      else 
      {
        printf("closed connection without prot found\n");
        if(pss->session)
          printf("but a session was found\n");
      }
      break;

    case LWS_CALLBACK_RECEIVE:
      if(len>1024) 
      { //TODO use some variable
      lwsl_err("Server received packet bigger than %u, hanging up\n", 1024);
      return(1);
      }
      if(found_prot)
      {
      node *parameters = create_obj("parameters");
      node *base_class = get_base_class(state);
      
      node *prot_value = create_class_instance(base_class);
      set_obj_string(prot_value,"name","protocol");
      set_obj_string(prot_value,"value",get_obj_name(found_prot));
      node_AddItem(parameters,prot_value);
      inc_obj_refcount(prot_value);

      char *msg = str_CreateEmpty();
      msg = str_AddChars(msg,in,len);
      node *msg_value = create_class_instance(base_class);
      set_obj_string(msg_value,"name","message");
      set_obj_string(msg_value,"value",msg);
      node_AddItem(parameters,msg_value);
      inc_obj_refcount(msg_value);
      free(msg);

      /*node *session_value = create_class_instance(base_class);
      reset_obj_refcount(session_value);
      add_garbage(state,session_value);
      set_obj_string(session_value,"name","session_id");
      set_obj_int(session_value,"value",lsession_uid);
      set_obj_int(session_value,"item_index",2);
      node_AddItem(parameters,session_value);
      */
      node_AddItem(parameters,pss->session);
      inc_obj_refcount(pss->session);
      //node_AddItem(parameters,daemon_obj);
      //inc_obj_refcount(daemon_obj);

      node_AddItem(parameters,sessions);
      inc_obj_refcount(sessions);

      //printf("recv callback\n");
      //fflush(stdout);
      node *tmp_parent = node_GetParent(found_prot);
      node *bmembers = node_GetItemByKey(block,"members");
      node_SetParent(found_prot,bmembers);

      node *ret_obj = execute_obj(state,found_prot,block,parameters,True,False);//,True);resolve
      node_SetParent(found_prot,tmp_parent);
      //printf("recv callback finished\n");
      //fflush(stdout);

      dec_obj_refcount(msg_value);
      dec_obj_refcount(prot_value);
      add_garbage(state,msg_value);//TODO check if "just survives"
      add_garbage(state,prot_value);

      dec_obj_refcount(pss->session);
      dec_obj_refcount(sessions);
      //dec_obj_refcount(daemon_obj);
      //printf("recv gc\n");
      //fflush(stdout);
      //node *ret_obj_value = node_GetItemByKey(ret_obj,"value");
      //char *me = node_GetString(ret_obj_value);
      //printf("returned string:[%s]\n",me);
      node *ret_obj_value = node_GetItemByKey(ret_obj,"value");
      if(node_GetType(ret_obj_value)==NODE_TYPE_STRING && strlen(node_GetString(ret_obj_value)))
      {
        //printf("returning message: [%s] :%d\n",node_GetString(ret_obj_value),strlen(node_GetString(ret_obj_value)));
        //node *ret_obj_copy = node_CopyTree(ret_obj,True,True);
        node *ret_obj_copy = copy_class(ret_obj);
        //reset_obj_refcount(ret_obj_copy);
        set_obj_string(ret_obj_copy,"name","message");
        add_member(pss->session,ret_obj_copy);
        inc_obj_refcount(ret_obj_copy);
        //set_obj_string(ret_obj,"name","message");
        //add_member(pss->session,ret_obj);
        //inc_obj_refcount(ret_obj);
      }
      libwebsocket_callback_on_writable(context, wsi);
      }
      break;
    default:
      break;
  }

  return(0);
}
예제 #26
0
파일: objsave.c 프로젝트: madvlad/doom-mud
int Obj_to_store(struct obj_data *obj, FILE *fp, int locate)
{
  int counter2;
  struct extra_descr_data *ex_desc;
  char buf1[MAX_STRING_LENGTH +1];
  char flags[65];
  struct obj_data *temp = NULL;

  if (GET_OBJ_VNUM(obj) != NOTHING)
    temp=read_object(GET_OBJ_VNUM(obj), VIRTUAL);
  else {
    temp = create_obj();
    temp->item_number = -1;
  }

  if (obj->action_description) {
    strcpy(buf1, obj->action_description);
    strip_string(buf1);
  } else
    *buf1 = 0;

  fprintf(fp, "#%d\n", GET_OBJ_VNUM(obj));
  if (locate)
    fprintf(fp, "Loc : %d\n", locate);
  if (GET_OBJ_VAL(obj, 0) != GET_OBJ_VAL(temp, 0) ||
      GET_OBJ_VAL(obj, 1) != GET_OBJ_VAL(temp, 1) ||
      GET_OBJ_VAL(obj, 2) != GET_OBJ_VAL(temp, 2) ||
      GET_OBJ_VAL(obj, 3) != GET_OBJ_VAL(temp, 3))
    fprintf(fp,
             "Vals: %d %d %d %d\n",
             GET_OBJ_VAL(obj, 0),
             GET_OBJ_VAL(obj, 1),
             GET_OBJ_VAL(obj, 2),
             GET_OBJ_VAL(obj, 3)
             );
  if (GET_OBJ_EXTRA(obj) != GET_OBJ_EXTRA(temp)) {
    sprintascii(flags, GET_OBJ_EXTRA(obj));
    fprintf(fp, "Flag: %s\n", flags);
  }

#define TEST_OBJS(obj1, obj2, field) ((!obj1->field || !obj2->field || \
                                      strcmp(obj1->field, obj2->field)))
#define TEST_OBJN(field) (obj->obj_flags.field != temp->obj_flags.field)

  if (TEST_OBJS(obj, temp, name))
    fprintf(fp, "Name: %s\n", obj->name ? obj->name : "Undefined");
  if (TEST_OBJS(obj, temp, short_description))
    fprintf(fp, "Shrt: %s\n", obj->short_description ? obj->short_description : "Undefined");

  /* These two could be a pain on the read... we'll see... */
  if (TEST_OBJS(obj, temp, description))
    fprintf(fp, "Desc: %s\n", obj->description ? obj->description : "Undefined");

  /* Only even try to process this if an action desc exists */
  if (obj->action_description || temp->action_description)
    if (TEST_OBJS(obj, temp, action_description))
      fprintf(fp, "ADes:\n%s~\n", buf1);

  if (TEST_OBJN(type_flag))
    fprintf(fp, "Type: %d\n", GET_OBJ_TYPE(obj));
  if (TEST_OBJN(weight))
    fprintf(fp, "Wght: %d\n", GET_OBJ_WEIGHT(obj));
  if (TEST_OBJN(cost))
    fprintf(fp, "Cost: %d\n", GET_OBJ_COST(obj));
  if (TEST_OBJN(cost_per_day))
    fprintf(fp, "Rent: %d\n", GET_OBJ_RENT(obj));
  if (TEST_OBJN(bitvector)) {
    sprintascii(flags, obj->obj_flags.bitvector);
    fprintf(fp, "Perm: %s\n", flags);
  }
  if (TEST_OBJN(wear_flags)) {
    sprintascii(flags, GET_OBJ_WEAR(obj));
    fprintf(fp, "Wear: %s\n", flags);
  }

  /* Do we have affects? */
  for (counter2 = 0; counter2 < MAX_OBJ_AFFECT; counter2++)
    if (obj->affected[counter2].modifier != temp->affected[counter2].modifier)
      fprintf(fp, "Aff : %d %d %d\n",
               counter2,
               obj->affected[counter2].location,
               obj->affected[counter2].modifier
               );

  /* Do we have extra descriptions? */
  if (obj->ex_description || temp->ex_description) {
    /* To be reimplemented.  Need to handle this case in loading as
       well */
    if ((obj->ex_description && temp->ex_description && 
         obj->ex_description != temp->ex_description) ||
        !obj->ex_description || !temp->ex_description) {
      for (ex_desc = obj->ex_description; ex_desc; ex_desc = ex_desc->next) {
        /*. Sanity check to prevent nasty protection faults . */
        if (!*ex_desc->keyword || !*ex_desc->description) {
          continue;
        }
        strcpy(buf1, ex_desc->description);
        strip_string(buf1);
        fprintf(fp, "EDes:\n"
                 "%s~\n"
                 "%s~\n",
                 ex_desc->keyword,
                 buf1
                 );
      }
    }
  }

  fprintf(fp, "\n");

  extract_obj(temp);

  return 1;
}