コード例 #1
0
/**
 * Call a program and retrieve its last line of output.
 * @param call The program to run.
 * @return The last line of its output.
 * @note The returned value points to static storage that will be overwritten with each call.
 */
char *call_program_and_get_last_line_of_output(char *call)
{
	/*@ buffers ***************************************************** */
	static char result[512];
	char *tmp;

	/*@ pointers **************************************************** */
	FILE *fin;

	/*@ initialize data ********************************************* */
	malloc_string(tmp);
	result[0] = '\0';
	tmp[0] = '\0';

	/*@******************************************************************** */

	assert_string_is_neither_NULL_nor_zerolength(call);
	if ((fin = popen(call, "r"))) {
		for (fgets(tmp, MAX_STR_LEN, fin); !feof(fin);
			 fgets(tmp, MAX_STR_LEN, fin)) {
			if (strlen(tmp) > 1) {
				strcpy(result, tmp);
			}
		}
		paranoid_pclose(fin);
	} else {
		log_OS_error("Unable to popen call");
	}
	strip_spaces(result);
	return (result);
}
コード例 #2
0
ファイル: nsc_contact.c プロジェクト: mycroft/nsc
int add_ignore (char *name)
{
  char *realname;
  char *message;
  struct ignore_list_t *nouvelle;

  if (name == NULL)
    return (-1);
  if (ignore_list == NULL)
    ignore_list = creer_liste();
  else {
    if(search_first_cel_with_name_in_list(name, ignore_list) != NULL)
      return -1;
  }

  realname = str_to_first_word(name);
  message = name + my_strlen (realname);
  message = strip_spaces(message);

  nouvelle = my_malloc (sizeof (struct ignore_list_t));
  nouvelle->name = my_malloc_strcpy(realname);
  if (message != NULL && *message != '\0')
    nouvelle->message = my_malloc_strcpy(message);
  else
    nouvelle->message = NULL;
  ajout_liste (&ignore_list, nouvelle);

  free(realname);
  if (message != NULL)
    free(message);
  return 0;
}
コード例 #3
0
char *
call_program_and_get_last_line_of_output (char *call)
{
	/** buffers ******************************************************/
  static char result[MAX_STR_LEN+1];
  char tmp[MAX_STR_LEN+1];

	/** pointers *****************************************************/
  FILE *fin;

	/** initialize data **********************************************/
  result[0] = '\0';

  /***********************************************************************/
  if ((fin = popen (call, "r")))
    {
      for (fgets (tmp, MAX_STR_LEN, fin); !feof (fin);
	   fgets (tmp, MAX_STR_LEN, fin))
	{
	  if (strlen (tmp) > 1)
	    {
	      strcpy (result, tmp);
	    }
	}
      pclose (fin);
    }
  strip_spaces (result);
  return (result);
}
コード例 #4
0
ファイル: discovery_utils.cpp プロジェクト: 01org/intelRSD
std::string get_null_terminated_string(const std::uint8_t* data, const std::uint32_t size) {
    if (nullptr == data) {
        return std::string{};
    }
    std::string str{};
    if (data != nullptr && size > 0) {
        for (size_t i = 0; i < size; ++i) {
            if (data[i] != '\0') {
                str += data[i];
            }
        }
    }
    return strip_spaces(str);
}
コード例 #5
0
/**
 * Log the last @p g_noof_log_lines lines of @p filename that match @p
 * grep_for_me to the screen.
 * @param filename The file to give the end of.
 * @param grep_for_me If not "", then only give lines in @p filename that match this regular expression.
 */
	void
	 log_file_end_to_screen(char *filename, char *grep_for_me) {

		/*@ buffers ********************************************************** */
		char *command = NULL;
		char *tmp = NULL;

		/*@ pointers ********************************************************* */
		FILE *fin = NULL;

		/*@ int ************************************************************** */
		int i = 0;
		size_t n = 0;

		assert_string_is_neither_NULL_nor_zerolength(filename);
		assert(grep_for_me != NULL);

		if (!does_file_exist(filename)) {
			return;
		}
		if (grep_for_me[0] != '\0') {
			asprintf(&command, "grep '%s' %s | tail -n%d",
					 grep_for_me, filename, g_noof_log_lines);
		} else {
			asprintf(&command, "tail -n%d %s", g_noof_log_lines, filename);
		}
		fin = popen(command, "r");
		if (!fin) {
			log_OS_error(command);
		} else {
			for (i = 0; i < g_noof_log_lines; i++) {
				for (;
					strlen(err_log_lines[i]) < 2 && !feof(fin);) {
					getline(&(err_log_lines[i]), &n, fin);
					strip_spaces(err_log_lines[i]);
					if (!strncmp(err_log_lines[i], "root:", 5)) {
						asprintf(&tmp, "%s", err_log_lines[i] + 6);
						paranoid_free(err_log_lines[i]);
						err_log_lines[i] = tmp;
					}
					if (feof(fin)) {
						break;
					}
				}
			}
			paranoid_pclose(fin);
		}
		refresh_log_screen();
		paranoid_free(command);
	}
コード例 #6
0
ファイル: m00convert.c プロジェクト: gabrielecirulli/m00conv
static void convert_files(m00data_t* data)
{
	debug_print("Starting file conversion\n");
	
	char line[256];
	unsigned long line_a = 0, line_c = 0; /* line_a: count of all lines; line_c: converted lines */
	int g = 0, x = 0, z = 0;

	char output_line[256]; /* String that contains the converted output */
	
	debug_print("Beginning to read/write the files\n");
	while(fgets(line, 255, data->in_file) != NULL)
	{
		line_a++; /* Increase line count */
		char* stripped = strip_spaces(strip_comments(line));

		if(is_blank(stripped) || !parse_line(stripped, &g, &x, &z))
			continue; /* Skip unuseful lines */

		line_c++;



		if(sprintf(output_line, "    %02d %02d % 05d  % 05d\n", (int)line_c+2, g, x, z) < 0)
		{
			fprintf(stderr, "m00conv: an unknown error occurred while writing the file\n");
			terminate(1);
		}
		fputs(output_line, data->out_file);

		debug_print("L%lu A%lu (-%lu): '%s'\n"
			"\tg=%d  x=%d  z=%d\n"
			"\t=%s",
			line_a, line_c, line_a-line_c, line,
			g, x, z,
			output_line);
	}

	/* 'end of instructions' line */
	if(sprintf(output_line, "    %02dM30\n", (int)line_c+3) < 0)
	{
		fprintf(stderr, "m00conv: an unknown error occurred while writing the file\n");
		terminate(1);
	}
	fputs(output_line, data->out_file);

	debug_print("Finished reading/writing the files\n");
}
コード例 #7
0
ファイル: create_test_font.cpp プロジェクト: Arternis/skia
static void generate_index(const char* defaultName, FILE* out) {
    int fontCount = gWritten.count();
    fprintf(out,
            "static SkTestFontData gTestFonts[] = {\n");
    int fontIndex;
    for (fontIndex = 0; fontIndex < fontCount; ++fontIndex) {
        const FontWritten& writ = gWritten[fontIndex];
        const char* name = writ.fName;
        SkString strippedStr = strip_spaces(SkString(name));
        strippedStr.appendf("%s", gStyleName[writ.fStyle]);
        const char* strip = strippedStr.c_str();
        fprintf(out,
                "    {    %sPoints, %sVerbs, %sCharCodes,\n"
                "         %sCharCodesCount, %sWidths,\n"
                "         %sMetrics, \"%s\", SkTypeface::%s, NULL\n"
                "    },\n",
                strip, strip, strip, strip, strip, strip, name, gStyleName[writ.fStyle]);
    }
    fprintf(out, "};\n\n");
    fprintf(out, "const int gTestFontsCount = (int) SK_ARRAY_COUNT(gTestFonts);\n\n");
    fprintf(out,
                "struct SubFont {\n"
                "    const char* fName;\n"
                "    SkTypeface::Style fStyle;\n"
                "    SkTestFontData& fFont;\n"
                "    const char* fFile;\n"
                "};\n\n"
                "const SubFont gSubFonts[] = {\n");
    int defaultIndex = -1;
    for (int subIndex = 0; subIndex < gFontsCount; subIndex++) {
        const FontDesc& desc = gFonts[subIndex];
        if (!strcmp(defaultName, desc.fName)) {
            defaultIndex = subIndex;
        }
        fprintf(out,
                "    { \"%s\", SkTypeface::%s, gTestFonts[%d], \"%s\"},\n", desc.fName,
                gStyleName[desc.fStyle], desc.fFontIndex, desc.fFile);
    }
    fprintf(out, "};\n\n");
    fprintf(out, "const int gSubFontsCount = (int) SK_ARRAY_COUNT(gSubFonts);\n\n");
    SkASSERT(defaultIndex >= 0);
    fprintf(out, "const int gDefaultFontIndex = %d;\n", defaultIndex);
}
コード例 #8
0
char * get_last_word(char * str)
{
	if (str == NULL)
		return NULL;
	if (str == "")
		return "";
	char * trimmed;
	trimmed = strip_spaces(str);
	
	int index1 = 0;
	int len = 0;
	for (int index = 0; trimmed[index] != '\0'; index++)
		len++;
	char  *LastWord = (char*)malloc(len*sizeof(char));
	for (int index = len - 1; index >= 0; index--)
	{
		if (trimmed[index] == ' ')
			break;
		else
		{
			LastWord[index1] = trimmed[index];
		}
		index1++;
	}
	LastWord[index1] = '\0';
	int c = 0;
	int d = 0;
	int length = 0;

	for (int index = 0; LastWord[index] != '\0'; index++)
		length++;

	char *str1 = (char*)malloc(length*sizeof(char));

	for (c = length - 1, d = 0; c >= 0; c--, d++)
		str1[d] = LastWord[c];

	str1[d] = '\0';

	return str1;
}
コード例 #9
0
ファイル: jabber-digest.c プロジェクト: hiciu/ekg2
char *jabber_sasl_digest_md5_response(session_t *s, char *challenge, const char *username, const char *password) {
	jabber_private_t *j =  s->priv;
	char **arr;
	char *retval, *nonce = NULL, *realm = NULL;
// XXX	char *rspauth	= NULL;
	int i;

	/* maybe we need to change/create another one parser... i'm not sure. please notify me, I'm lazy, sorry */
	/* for chrome.pl and jabber.autocom.pl it works */

	arr = array_make(challenge, "=,", 0, 1, 1);

	/* check data */
	if (g_strv_length(arr) & 1) {
		debug_error("Parsing var<=>value failed, NULL....\n");
		jabber_handle_disconnect(s, "IE, Current SASL support for ekg2 cannot handle with this data, sorry.", EKG_DISCONNECT_FAILURE);
		g_strfreev(arr);
		j->parser = NULL;
		return NULL;
	}

	/* parse data */
	i = 0;
	while (arr[i]) {
		char *tmp = strip_spaces(arr[i]);
		debug("md5_digest [%d] %s: %s\n", i / 2, arr[i], __(arr[i+1]));
		if (!xstrcmp(tmp, "realm"))		realm	= arr[i+1];
// XXX		else if (!xstrcmp(tmp, "rspauth"))	rspauth	= arr[i+1];
		else if (!xstrcmp(tmp, "nonce"))	nonce	= arr[i+1];
		i++;
		if (arr[i]) i++;
	}

	retval = sasl_auth_digest_md5(s, username, password, nonce, realm);

	g_strfreev(arr);

	return retval;
}
コード例 #10
0
ファイル: proc.c プロジェクト: tolimit/nmon
void proc_net(struct net_brk * net_brk)
{
	if (net_brk == NULL)
		return;

	struct data * p = net_brk->ext->p;
	static FILE *fp = (FILE *)-1;
	char buf[1024];
	int i=0;
	int ret;
	unsigned long junk;

	if( fp == (FILE *)-1) {
		if( (fp = fopen("/proc/net/dev","r")) == NULL) {
			error("failed to open - /proc/net/dev");
			net_brk->networks=0;
			return;
		}
	}
	if(fgets(buf,1024,fp) == NULL) goto end; /* throw away the header lines */
	if(fgets(buf,1024,fp) == NULL) goto end; /* throw away the header lines */
	/*
	   Inter-|   Receive                                                |  Transmit
	   face |bytes    packets errs drop fifo frame compressed multicast|bytes    packets errs drop fifo colls carrier compressed
lo:    1956      30    0    0    0     0          0         0     1956      30    0    0    0     0       0          0
eth0:       0       0    0    0    0     0          0         0   458718       0  781    0    0     0     781          0
sit0:       0       0    0    0    0     0          0         0        0       0    0    0    0     0       0          0
eth1:       0       0    0    0    0     0          0         0        0       0    0    0    0     0       0          0
*/
	for(i=0;i<NETMAX;i++) {
		if(fgets(buf,1024,fp) == NULL)
			break;
		strip_spaces((char *)buf);
		/* 1   2   3    4   5   6   7   8   9   10   11   12  13  14  15  16 */
		ret = sscanf(&buf[0], "%s %llu %llu %lu %lu %lu %lu %lu %lu %llu %llu %lu %lu %lu %lu %lu",
				(char *)&p->ifnets[i].if_name,
				&p->ifnets[i].if_ibytes,
				&p->ifnets[i].if_ipackets,
				&p->ifnets[i].if_ierrs,
				&p->ifnets[i].if_idrop,
				&p->ifnets[i].if_ififo,
				&p->ifnets[i].if_iframe,
				&junk,
				&junk,
				&p->ifnets[i].if_obytes,
				&p->ifnets[i].if_opackets,
				&p->ifnets[i].if_oerrs,
				&p->ifnets[i].if_odrop,
				&p->ifnets[i].if_ofifo,
				&p->ifnets[i].if_ocolls,
				&p->ifnets[i].if_ocarrier
				);
		p->ifnets[i].if_ibits = p->ifnets[i].if_ibytes * 8;
		p->ifnets[i].if_obits = p->ifnets[i].if_obytes * 8;

		if(ret != 16)
			fprintf(stderr,"sscanf wanted 16 returned = %d line=%s\n", ret, (char *)buf);
	}
end:
	if(reread) {
		fclose(fp);
		fp = (FILE *)-1;
	} else rewind(fp);
	net_brk->networks = i;
}
コード例 #11
0
ファイル: create_test_font.cpp プロジェクト: Arternis/skia
static void output_font(SkTypeface* face, const char* name, SkTypeface::Style style,
        const char* used, FILE* out) {
    int emSize = face->getUnitsPerEm() * 2;
    SkPaint paint;
    paint.setAntiAlias(true);
    paint.setTextAlign(SkPaint::kLeft_Align);
    paint.setTextEncoding(SkPaint::kUTF16_TextEncoding);
    paint.setTextSize(emSize);
    SkSafeUnref(paint.setTypeface(face));
    SkTDArray<SkPath::Verb> verbs;
    SkTDArray<unsigned> charCodes;
    SkTDArray<SkScalar> widths;
    SkString ptsOut;
    output_path_data(paint, used, emSize, &ptsOut, &verbs, &charCodes, &widths);
    SkString fontnameStr(name);
    SkString strippedStr = strip_spaces(fontnameStr);
    strippedStr.appendf("%s", gStyleName[style]);
    const char* fontname = strippedStr.c_str();
    fprintf(out, "const SkScalar %sPoints[] = {\n", fontname);
    ptsOut = strip_final(ptsOut);
    fprintf(out, "%s", ptsOut.c_str());
    fprintf(out, "\n};\n\n");
    fprintf(out, "const unsigned char %sVerbs[] = {\n", fontname);
    int verbCount = verbs.count();
    int outChCount = 0;
    for (int index = 0; index < verbCount;) {
        SkPath::Verb verb = verbs[index];
        SkASSERT(verb >= SkPath::kMove_Verb && verb <= SkPath::kDone_Verb);
        SkASSERT((unsigned) verb == (unsigned char) verb);
        fprintf(out, "%u", verb);
        if (++index < verbCount) {
            outChCount += 3;
            fprintf(out, "%c", ',');
            if (outChCount >= kMaxLineLength) {
                outChCount = 0;
                fprintf(out, "%c", '\n');
            } else {
                fprintf(out, "%c", ' ');
            }
        }
    }
    fprintf(out, "\n};\n\n");
    
    fprintf(out, "const unsigned %sCharCodes[] = {\n", fontname);
    int offsetCount = charCodes.count();
    for (int index = 0; index < offsetCount;) {
        unsigned offset = charCodes[index];
        fprintf(out, "%u", offset);
        if (++index < offsetCount) {
            outChCount += offset_str_len(offset) + 2;
            fprintf(out, "%c", ',');
            if (outChCount >= kMaxLineLength) {
                outChCount = 0;
                fprintf(out, "%c", '\n');
            } else {
                fprintf(out, "%c", ' ');
            }
        }
    }
    fprintf(out, "\n};\n\n");
    
    SkString widthsStr;
    fprintf(out, "const SkFixed %sWidths[] = {\n", fontname);
    for (int index = 0; index < offsetCount; ++index) {
        output_fixed(widths[index], emSize, &widthsStr);
    }
    widthsStr = strip_final(widthsStr);
    fprintf(out, "%s\n};\n\n", widthsStr.c_str());
    
    fprintf(out, "const int %sCharCodesCount = (int) SK_ARRAY_COUNT(%sCharCodes);\n\n",
            fontname, fontname);

    SkPaint::FontMetrics metrics;
    paint.getFontMetrics(&metrics);
    fprintf(out, "const SkPaint::FontMetrics %sMetrics = {\n", fontname);
    SkString metricsStr;
    metricsStr.printf("0x%08x, ", metrics.fFlags);
    output_scalar(metrics.fTop, emSize, &metricsStr);
    output_scalar(metrics.fAscent, emSize, &metricsStr);
    output_scalar(metrics.fDescent, emSize, &metricsStr);
    output_scalar(metrics.fBottom, emSize, &metricsStr);
    output_scalar(metrics.fLeading, emSize, &metricsStr);
    output_scalar(metrics.fAvgCharWidth, emSize, &metricsStr);
    output_scalar(metrics.fMaxCharWidth, emSize, &metricsStr);
    output_scalar(metrics.fXMin, emSize, &metricsStr);
    output_scalar(metrics.fXMax, emSize, &metricsStr);
    output_scalar(metrics.fXHeight, emSize, &metricsStr);
    output_scalar(metrics.fCapHeight, emSize, &metricsStr);
    output_scalar(metrics.fUnderlineThickness, emSize, &metricsStr);
    output_scalar(metrics.fUnderlinePosition, emSize, &metricsStr);
    metricsStr = strip_final(metricsStr);
    fprintf(out, "%s\n};\n\n", metricsStr.c_str());
}
コード例 #12
0
ファイル: channels.cpp プロジェクト: carriercomm/AFKMud
/* Duplicate of to_channel from act_comm.c modified for dynamic channels */
void send_tochannel( char_data * ch, mud_channel * channel, string & argument )
{
   int speaking = -1;

   for( int lang = 0; lang < LANG_UNKNOWN; ++lang )
   {
      if( ch->speaking == lang )
      {
         speaking = lang;
         break;
      }
   }

   if( ch->isnpc(  ) && channel->type == CHAN_GUILD )
   {
      ch->print( "Mobs can't be in clans/guilds.\r\n" );
      return;
   }

   if( ch->has_pcflag( PCFLAG_SILENCE ) )
   {
      ch->printf( "You can't %s.\r\n", channel->name.c_str(  ) );
      return;
   }

   if( ch->has_aflag( AFF_SILENCE ) )
   {
      ch->print( "You are unable to utter a sound!\r\n" );
      return;
   }

   if( !ch->IS_PKILL(  ) && channel->type == CHAN_PK )
   {
      if( !ch->is_immortal(  ) )
      {
         ch->print( "Peacefuls have no need to use PK channels.\r\n" );
         return;
      }
   }

   if( ch->in_room->flags.test( ROOM_SILENCE ) || ch->in_room->flags.test( ROOM_NOYELL ) || ch->in_room->area->flags.test( AFLAG_SILENCE ) )
   {
      ch->print( "The room absorbs your words!\r\n" );
      return;
   }

   if( ch->isnpc(  ) && ch->has_aflag( AFF_CHARM ) )
   {
      if( ch->master )
         ch->master->print( "I don't think so...\r\n" );
      return;
   }

   if( argument.empty(  ) )
   {
      if( !channel->flags.test( CHAN_KEEPHISTORY ) )
      {
         ch->printf( "%s what?\r\n", capitalize( channel->name ).c_str(  ) );
         return;
      }

      show_channel_history( ch, channel );
      return;
   }

   // Adaptation of Smaug 1.8b feature. Stop whitespace abuse now!
   strip_spaces( argument );

   string arg, word;
   char_data *victim = nullptr;
   social_type *social = nullptr;
   string socbuf_char, socbuf_vict, socbuf_other;

   arg = argument;
   arg = one_argument( arg, word );

   if( word[0] == '@' && ( social = find_social( word.substr( 1, word.length(  ) ) ) ) != nullptr )
   {
      if( !arg.empty(  ) )
      {
         string name;

         one_argument( arg, name );

         if( ( victim = ch->get_char_world( name ) ) )
            arg = one_argument( arg, name );

         if( !victim )
         {
            socbuf_char = social->char_no_arg;
            socbuf_vict = social->others_no_arg;
            socbuf_other = social->others_no_arg;
            if( socbuf_char.empty(  ) && socbuf_other.empty(  ) )
               social = nullptr;
         }
         else if( victim == ch )
         {
            socbuf_char = social->char_auto;
            socbuf_vict = social->others_auto;
            socbuf_other = social->others_auto;
            if( socbuf_char.empty(  ) && socbuf_other.empty(  ) )
               social = nullptr;
         }
         else
         {
            socbuf_char = social->char_found;
            socbuf_vict = social->vict_found;
            socbuf_other = social->others_found;
            if( socbuf_char.empty(  ) && socbuf_other.empty(  ) && socbuf_vict.empty(  ) )
               social = nullptr;
         }
      }
      else
      {
         socbuf_char = social->char_no_arg;
         socbuf_vict = social->others_no_arg;
         socbuf_other = social->others_no_arg;
         if( socbuf_char.empty(  ) && socbuf_other.empty(  ) )
            social = nullptr;
      }
   }

   bool emote = false;
   if( word[0] == ',' )
   {
      emote = true;
      argument = argument.substr( 1, argument.length(  ) );
   }

   if( social )
   {
      act_printf( AT_PLAIN, ch, argument.c_str(  ), victim, TO_CHAR, "&W[&[%s]%s&W] &[%s]%s",
                  channel->colorname.c_str(  ), capitalize( channel->name ).c_str(  ), channel->colorname.c_str(  ), socbuf_char.c_str(  ) );
   }
   else if( emote )
   {
      ch->printf( "&W[&[%s]%s&W] &[%s]%s %s\r\n",
                  channel->colorname.c_str(  ), capitalize( channel->name ).c_str(  ), channel->colorname.c_str(  ), ch->name, argument.c_str(  ) );
   }
   else
   {
      if( ch->has_pcflag( PCFLAG_WIZINVIS ) )
         ch->printf( "&[%s](%d) You %s '%s'\r\n", channel->colorname.c_str(  ), ( !ch->isnpc(  ) ? ch->pcdata->wizinvis : ch->mobinvis ), channel->name.c_str(  ), argument.c_str(  ) );
      else
         ch->printf( "&[%s]You %s '%s'\r\n", channel->colorname.c_str(  ), channel->name.c_str(  ), argument.c_str(  ) );
   }

   if( ch->in_room->flags.test( ROOM_LOGSPEECH ) )
      append_to_file( LOG_FILE, "%s: %s (%s)", ch->isnpc(  )? ch->short_descr : ch->name, argument.c_str(  ), channel->name.c_str(  ) );

   /*
    * Channel history. Records the last MAX_CHANHISTORY messages to channels which keep historys 
    */
   if( channel->flags.test( CHAN_KEEPHISTORY ) )
      update_channel_history( ch, channel, argument, emote );

   list < char_data * >::iterator ich;
   for( ich = pclist.begin(  ); ich != pclist.end(  ); ++ich )
   {
      char_data *vch = *ich;

      /*
       * Hackish solution to stop that damned "someone chat" bug - Matarael 17.3.2002 
       */
      bool mapped = false;
      int origmap = -1, origx = -1, origy = -1;

      if( vch == ch || !vch->desc )
         continue;

      if( vch->desc->connected == CON_PLAYING && hasname( vch->pcdata->chan_listen, channel->name ) )
      {
         string sbuf = argument;
         char lbuf[MIL + 4];  /* invis level string + buf */

         if( vch->level < channel->level )
            continue;

         if( vch->in_room->flags.test( ROOM_SILENCE ) || vch->in_room->area->flags.test( AFLAG_SILENCE ) )
            continue;

         if( channel->type == CHAN_ROOM )
         {
            if( vch->in_room != ch->in_room )
               continue;

            /*
             * Check to see if a player on a map is at the same coords as the recipient
             */
            if( !is_same_char_map( ch, vch ) )
               continue;
         }

         if( channel->type == CHAN_ZONE && ( vch->in_room->area != ch->in_room->area || vch->in_room->flags.test( ROOM_NOYELL ) ) )
            continue;

         if( channel->type == CHAN_PK && !vch->IS_PKILL(  ) && !vch->is_immortal(  ) )
            continue;

         if( channel->type == CHAN_GUILD )
         {
            if( vch->isnpc(  ) )
               continue;
            if( vch->pcdata->clan != ch->pcdata->clan )
               continue;
         }

         int position = vch->position;
         vch->position = POS_STANDING;

         if( ch->has_pcflag( PCFLAG_WIZINVIS ) && vch->can_see( ch, false ) && vch->is_immortal(  ) )
            snprintf( lbuf, MIL + 4, "&[%s](%d) ", channel->colorname.c_str(  ), ( !ch->isnpc(  ) ) ? ch->pcdata->wizinvis : ch->mobinvis );
         else
            lbuf[0] = '\0';

         if( speaking != -1 && ( !ch->isnpc(  ) || ch->speaking ) )
         {
            int speakswell = UMIN( knows_language( vch, ch->speaking, ch ), knows_language( ch, ch->speaking, vch ) );

            if( speakswell < 85 )
               sbuf = translate( speakswell, argument, lang_names[speaking] );
         }

         /*
          * Check to see if target is ignoring the sender 
          */
         if( is_ignoring( vch, ch ) )
         {
            /*
             * If the sender is an imm then they cannot be ignored 
             */
            if( !ch->is_immortal(  ) || vch->level > ch->level )
            {
               /*
                * Off to oblivion! 
                */
               continue;
            }
         }

         MOBtrigger = false;

         /*
          * Hackish solution to stop that damned "someone chat" bug - Matarael 17.3.2002 
          */
         if( ch->has_pcflag( PCFLAG_ONMAP ) )
         {
            mapped = true;
            origx = ch->mx;
            origy = ch->my;
            origmap = ch->wmap;
         }

         if( ch->isnpc(  ) && ch->has_actflag( ACT_ONMAP ) )
         {
            mapped = true;
            origx = ch->mx;
            origy = ch->my;
            origmap = ch->wmap;
         }
         fix_maps( vch, ch );

         char buf[MSL];
         if( !social && !emote )
         {
            snprintf( buf, MSL, "&[%s]$n %ss '$t&[%s]'", channel->colorname.c_str(  ), channel->name.c_str(  ), channel->colorname.c_str(  ) );
            mudstrlcat( lbuf, buf, MIL + 4 );
            act( AT_PLAIN, lbuf, ch, sbuf.c_str(  ), vch, TO_VICT );
         }

         if( emote )
         {
            snprintf( buf, MSL, "&W[&[%s]%s&W] &[%s]$n $t", channel->colorname.c_str(  ), capitalize( channel->name ).c_str(  ), channel->colorname.c_str(  ) );
            mudstrlcat( lbuf, buf, MIL + 4 );
            act( AT_PLAIN, lbuf, ch, sbuf.c_str(  ), vch, TO_VICT );
         }

         if( social )
         {
            if( vch == victim )
            {
               act_printf( AT_PLAIN, ch, nullptr, vch, TO_VICT, "&W[&[%s]%s&W] &[%s]%s",
                           channel->colorname.c_str(  ), capitalize( channel->name ).c_str(  ), channel->colorname.c_str(  ), socbuf_vict.c_str(  ) );
            }
            else
            {
               act_printf( AT_PLAIN, ch, vch, victim, TO_THIRD, "&W[&[%s]%s&W] &[%s]%s", channel->colorname.c_str(  ),
                           capitalize( channel->name ).c_str(  ), channel->colorname.c_str(  ), socbuf_other.c_str(  ) );
            }
         }

         vch->position = position;
         /*
          * Hackish solution to stop that damned "someone chat" bug - Matarael 17.3.2002 
          */
         if( mapped )
         {
            ch->wmap = origmap;
            ch->mx = origx;
            ch->my = origy;
            if( ch->isnpc(  ) )
               ch->set_actflag( ACT_ONMAP );
            else
               ch->set_pcflag( PCFLAG_ONMAP );
         }
         else
         {
            if( ch->isnpc(  ) )
               ch->unset_actflag( ACT_ONMAP );
            else
               ch->unset_pcflag( PCFLAG_ONMAP );
            ch->wmap = -1;
            ch->mx = -1;
            ch->my = -1;
         }
      }
   }
}
コード例 #13
0
ファイル: proc.c プロジェクト: tolimit/nmon
		void proc_partitions(struct disk_brk * brk)
		{
			static FILE *fp = (FILE *)-1;
			char buf[1024];
			int i = 0;
			int ret;
			struct data * p = brk->ext->p;

			if( fp == (FILE *)-1) {
				if( (fp = fopen("/proc/partitions","r")) == NULL) {
					error("failed to open - /proc/partitions");
					partitions=0;
					return;
				}
			}
			if(fgets(buf,1024,fp) == NULL) goto end; /* throw away the header lines */
			if(fgets(buf,1024,fp) == NULL) goto end;
			/*
			   major minor  #blocks  name     rio rmerge rsect ruse wio wmerge wsect wuse running use aveq

			   33     0    1052352 hde 2855 15 2890 4760 0 0 0 0 -4 7902400 11345292
			   33     1    1050304 hde1 2850 0 2850 3930 0 0 0 0 0 3930 3930
			   3     0   39070080 hda 9287 19942 226517 90620 8434 25707 235554 425790 -12 7954830 33997658
			   3     1   31744408 hda1 651 90 5297 2030 0 0 0 0 0 2030 2030
			   3     2    6138720 hda2 7808 19561 218922 79430 7299 20529 222872 241980 0 59950 321410
			   3     3     771120 hda3 13 41 168 80 0 0 0 0 0 80 80
			   3     4          1 hda4 0 0 0 0 0 0 0 0 0 0 0
			   3     5     408208 hda5 812 241 2106 9040 1135 5178 12682 183810 0 11230 192850
			   */
			for(i=0; i < brk->diskmax; i++) {
				if(fgets(buf,1024,fp) == NULL)
					break;
				strip_spaces(buf);
				ret = sscanf(&buf[0], "%d %d %lu %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
						&p->dk[i].dk_major,
						&p->dk[i].dk_minor,
						&p->dk[i].dk_blocks,
						(char *)&p->dk[i].dk_name,
						&p->dk[i].dk_reads,
						&p->dk[i].dk_rmerge,
						&p->dk[i].dk_rkb,
						&p->dk[i].dk_rmsec,
						&p->dk[i].dk_writes,
						&p->dk[i].dk_wmerge,
						&p->dk[i].dk_wkb,
						&p->dk[i].dk_wmsec,
						&p->dk[i].dk_inflight,
						&p->dk[i].dk_use,
						&p->dk[i].dk_aveq
						);
				p->dk[i].dk_rkb /= 2; /* sectors = 512 bytes */
				p->dk[i].dk_wkb /= 2;
				p->dk[i].dk_xfers = p->dk[i].dk_rkb + p->dk[i].dk_wkb;
				if(p->dk[i].dk_xfers == 0)
					p->dk[i].dk_bsize = 0;
				else
					p->dk[i].dk_bsize = (p->dk[i].dk_rkb+p->dk[i].dk_wkb)/p->dk[i].dk_xfers*1024;

				p->dk[i].dk_time /= 10.0; /* in milli-seconds to make it upto 100%, 1000/100 = 10 */

				if(ret != 15) {
#ifdef DEBUG
					if(debug)fprintf(stderr,"sscanf wanted 15 returned = %d line=%s\n", ret,buf);
#endif /*DEBUG*/
					partitions_short = 1;
				} else partitions_short = 0;
			}
end:
			if(reread) {
				fclose(fp);
				fp = (FILE *)-1;
			} else rewind(fp);
			brk->disks = i;
		}
コード例 #14
0
/**
 * Ask the user which backup media type they would like to use.
 * The choices are @p none (exit to shell), @c cdr, @c cdrw, @c dvd,
 * @c tape, @c cdstream, @c udev (only when @p g_text_mode is TRUE), @c nfs,
 * and @c iso.
 * @param restoring TRUE if we're restoring, FALSE if we're backing up.
 * @return The backup type chosen, or @c none if the user chose "Exit to shell".
 */
	t_bkptype which_backup_media_type(bool restoring) {

		/*@ char ************************************************************ */
		t_bkptype output;


		/*@ newt ************************************************************ */
		char *title_sz;
		char *minimsg_sz;
		static t_bkptype possible_bkptypes[] =
			{ none, cdr, cdrw, dvd, tape, cdstream, udev, nfs, iso };
		static char *possible_responses[] =
			{ "none", "cdr", "cdrw", "dvd", "tape", "cdstream", "udev",
			"nfs", "iso", NULL
		};
		char *outstr = NULL;
		t_bkptype backup_type;
		int i;
		size_t n = 0;

		newtComponent b1;
		newtComponent b2;
		newtComponent b3;
		newtComponent b4;
		newtComponent b5;
		newtComponent b6;
		newtComponent b7;
		newtComponent b8;
		newtComponent b_res;
		newtComponent myForm;

		if (g_text_mode) {
			for (backup_type = none; backup_type == none;) {
				printf(_("Backup type ("));
				for (i = 0; possible_responses[i]; i++) {
					printf("%c%s", (i == 0) ? '\0' : ' ',
						   possible_responses[i]);
				}
				printf(")\n--> ");
				(void) getline(&outstr, &n, stdin);
				strip_spaces(outstr);
				for (i = 0; possible_responses[i]; i++) {
					if (!strcmp(possible_responses[i], outstr)) {
						backup_type = possible_bkptypes[i];
					}
				}
			}
			paranoid_free(outstr);
			return (backup_type);
		}
		newtDrawRootText(18, 0, WELCOME_STRING);
		if (restoring) {
			asprintf(&title_sz,
					 _("Please choose the backup media from which you want to read data."));
			asprintf(&minimsg_sz, _("Read from:"));
		} else {
			asprintf(&title_sz,
					 _("Please choose the backup media to which you want to archive data."));
			asprintf(&minimsg_sz, _("Backup to:"));
		}
		newtPushHelpLine(title_sz);
		paranoid_free(title_sz);

		//  newtOpenWindow (23, 3, 34, 17, minimsg_sz);
		newtCenteredWindow(34, 17, minimsg_sz);
		paranoid_free(minimsg_sz);

		b1 = newtButton(1, 1, _("CD-R disks "));
		b2 = newtButton(17, 1, _("CD-RW disks"));
		b3 = newtButton(1, 9, _("Tape drive "));
		b4 = newtButton(17, 5, _("CD streamer"));
		b5 = newtButton(1, 5, _(" DVD disks "));
		b6 = newtButton(17, 9, _(" NFS mount "));
		b7 = newtButton(1, 13, _(" Hard disk "));
		b8 = newtButton(17, 13, _("    Exit   "));
		myForm = newtForm(NULL, NULL, 0);
		newtFormAddComponents(myForm, b1, b5, b3, b7, b2, b4, b6, b8,
							  NULL);
		b_res = newtRunForm(myForm);
		newtFormDestroy(myForm);
		newtPopWindow();
		if (b_res == b1) {
			output = cdr;
		} else if (b_res == b2) {
			output = cdrw;
		} else if (b_res == b3) {
			output = tape;
		} else if (b_res == b4) {
			output = cdstream;
		} else if (b_res == b5) {
			output = dvd;
		} else if (b_res == b6) {
			output = nfs;
		} else if (b_res == b7) {
			output = iso;
		} else {
			output = none;
		}
		newtPopHelpLine();
		return (output);
	}
コード例 #15
0
ファイル: resreq.c プロジェクト: CraigNoble/openlava
/* parseUsage()
 */
static int
parseUsage(char *usageReq, struct resVal *resVal, struct lsInfo *lsInfo)
{
    int i;
    int m;
    int entry;
    float value;
    char *token;
    link_t *link;
    linkiter_t iter;
    struct _rusage_ *r;
    char *s;
    int *rusage_bit_map;
    float *val;
    char *usageReq2;
    char *s2;

    if ((i = strlen(usageReq)) == 0)
        return PARSE_OK;

    for (m = 0; m < i; m++)
        if (usageReq[m] != ' ')
            break;
    if (m == i)
        return PARSE_OK;

    s2 = usageReq2 = strip_spaces(usageReq);

    resVal->rl = make_link();
    link = get_rusage_entries(usageReq2);

    i = 0;
    traverse_init(link, &iter);
    while ((s = traverse_link(&iter))) {

        /* Allocate for each element of the link
         */
        rusage_bit_map = calloc(GET_INTNUM(lsInfo->nRes), sizeof(int));
        val = calloc(lsInfo->nRes, sizeof(float));

        resVal->genClass = 0;
        while ((token = getNextToken(&s)) != NULL) {

            if (token[0] == '-')
                token++;

            entry = getKeyEntry(token);
            if (entry > 0) {
                if (entry != KEY_DURATION && entry != KEY_DECAY)
                    goto pryc;

                if (s[0] == '=') {
                    int returnValue;
                    if (entry == KEY_DURATION)
                        returnValue =  getTimeVal(&s, &value);
                    else
                        returnValue = getVal(&s, &value);
                    if (returnValue < 0 || value < 0.0)
                        return PARSE_BAD_VAL;
                    if (entry == KEY_DURATION)
                        resVal->duration = value;
                    else
                        resVal->decay = value;

                    continue;
                }
            }

            entry = getResEntry(token);
            if (entry < 0)
		goto pryc;

            if (!(lsInfo->resTable[entry].flags & RESF_DYNAMIC)
                && (lsInfo->resTable[entry].valueType != LS_NUMERIC)) {
                if (s[0] == '=') {
                    if (getVal(&s, &value) < 0 || value < 0.0)
                        goto pryc;
                }
                continue;
            }

            if (entry < MAXSRES)
                resVal->genClass |= 1 << entry;

            SET_BIT(entry, rusage_bit_map);

            if (s[0] == '=') {
                if (getVal(&s, &value) < 0 || value < 0.0)
                    goto pryc;
                val[entry] = value;
            }
        }

        /* Save the current rusage block
         */
        r = calloc(1, sizeof(struct _rusage_));
        r->bitmap = rusage_bit_map;
        r->val = val;
        enqueue_link(resVal->rl, r);

        if (i == 0) {
            /* The entry 0 is both in the link and
             * in the resVal. The default values
             * were allocated in setDefaults()
             */
            _free_(resVal->rusage_bit_map);
            _free_(resVal->val);
	    /* Copy the values as later we free them separately
	     */
            resVal->rusage_bit_map = calloc(GET_INTNUM(lsInfo->nRes),
					    sizeof(int));
	    memcpy(resVal->rusage_bit_map,
		   rusage_bit_map,
		   GET_INTNUM(lsInfo->nRes) * sizeof(int));
            resVal->val = calloc(lsInfo->nRes, sizeof(float));
	    memcpy(resVal->val, r->val, lsInfo->nRes * sizeof(float));
        }
        ++i;
    } /* while (s = traverse_link()) */

    resVal->options |= PR_RUSAGE;

    while ((s = pop_link(link)))
        _free_(s);
    fin_link(link);
    _free_(s2);

    return PARSE_OK;

pryc:

    _free_(rusage_bit_map);
    _free_(val);
    while ((s = pop_link(link)))
        _free_(s);
    fin_link(link);
    while ((r = pop_link(resVal->rl))) {
        _free_(r->bitmap);
        _free_(r->val);
        _free_(r);
    }
    fin_link(resVal->rl);
    resVal->rl = NULL;
    _free_(s2);

    return PARSE_BAD_NAME;
}
コード例 #16
0
/**
 * Run a program and log its output (stdout and stderr) to the logfile.
 * @param program The program to run. Passed to the shell, so you can use pipes etc.
 * @param debug_level If @p g_loglevel is higher than this, do not log the output.
 * @return The exit code of @p program (depends on the command, but 0 almost always indicates success).
 */
int run_program_and_log_output(char *program, int debug_level)
{
	/*@ buffer ****************************************************** */
	char callstr[MAX_STR_LEN * 2];
	char incoming[MAX_STR_LEN * 2];
	char tmp[MAX_STR_LEN * 2];
	char initial_label[MAX_STR_LEN * 2];

	/*@ int ********************************************************* */
	int res;
	int i;
	int len;
	bool log_if_failure = FALSE;
	bool log_if_success = FALSE;

	/*@ pointers *************************************************** */
	FILE *fin;
	char *p;

	/*@ end vars *************************************************** */

	assert(program != NULL);
	if (!program[0]) {
		log_msg(2, "Warning - asked to run zerolength program");
		return (1);
	}
//  if (debug_level == TRUE) { debug_level=5; }

	//  assert_string_is_neither_NULL_nor_zerolength(program);

	if (debug_level <= g_loglevel) {
		log_if_success = TRUE;
		log_if_failure = TRUE;
	}
	sprintf(callstr,
			"%s > /tmp/mondo-run-prog-thing.tmp 2> /tmp/mondo-run-prog-thing.err",
			program);
	while ((p = strchr(callstr, '\r'))) {
		*p = ' ';
	}
	while ((p = strchr(callstr, '\n'))) {
		*p = ' ';
	}							/* single '=' is intentional */


	len = (int) strlen(program);
	for (i = 0; i < 35 - len / 2; i++) {
		tmp[i] = '-';
	}
	tmp[i] = '\0';
	strcat(tmp, " ");
	strcat(tmp, program);
	strcat(tmp, " ");
	for (i = 0; i < 35 - len / 2; i++) {
		strcat(tmp, "-");
	}
	strcpy(initial_label, tmp);
	res = system(callstr);
	if (((res == 0) && log_if_success) || ((res != 0) && log_if_failure)) {
		log_msg(0, "running: %s", callstr);
		log_msg(0,
				"--------------------------------start of output-----------------------------");
	}
	if (log_if_failure
		&&
		system
		("cat /tmp/mondo-run-prog-thing.err >> /tmp/mondo-run-prog-thing.tmp 2> /dev/null"))
	{
		log_OS_error("Command failed");
	}
	unlink("/tmp/mondo-run-prog-thing.err");
	fin = fopen("/tmp/mondo-run-prog-thing.tmp", "r");
	if (fin) {
		for (fgets(incoming, MAX_STR_LEN, fin); !feof(fin);
			 fgets(incoming, MAX_STR_LEN, fin)) {
			/* patch by Heiko Schlittermann */
			p = incoming;
			while (p && *p) {
				if ((p = strchr(p, '%'))) {
					memmove(p, p + 1, strlen(p) + 1);
					p += 2;
				}
			}
			/* end of patch */
			strip_spaces(incoming);
			if ((res == 0 && log_if_success)
				|| (res != 0 && log_if_failure)) {
				log_msg(0, incoming);
			}
		}
		paranoid_fclose(fin);
	}
	unlink("/tmp/mondo-run-prog-thing.tmp");
	if ((res == 0 && log_if_success) || (res != 0 && log_if_failure)) {
		log_msg(0,
				"--------------------------------end of output------------------------------");
		if (res) {
			log_msg(0, "...ran with res=%d", res);
		} else {
			log_msg(0, "...ran just fine. :-)");
		}
	}
//  else
//    { log_msg (0, "-------------------------------ran w/ res=%d------------------------------", res); }
	return (res);
}
コード例 #17
0
/*************************************************************************
 * call_program_and_log_output() -- Hugo Rabson                           *
 *                                                                       *
 * Purpose:                                                              *
 * Called by:                                                            *
 * Returns:                                                              *
 *************************************************************************/
int
call_program_and_log_output (char *program)
{
	/** buffer *******************************************************/
  char callstr[MAX_STR_LEN+1];
  char incoming[MAX_STR_LEN+1];
  char tmp[MAX_STR_LEN+1];

	/** int **********************************************************/
  int res;
  int i;
  int len;

	/** pointers ****************************************************/
  FILE *fin;
  char *p;

	/** end vars ****************************************************/
  sprintf (callstr, "%s > /tmp/mondo-run-prog.tmp 2> /tmp/mondo-run-prog.err",
	   program);
  while ((p = strchr (callstr, '\r')))
    {
      *p = ' ';
    }
  while ((p = strchr (callstr, '\n')))
    {
      *p = ' ';
    }				/* single '=' is intentional */
  res = system (callstr);
  len = strlen (program);
  for (i = 0; i < 35 - len / 2; i++)
    {
      tmp[i] = '-';
    }
  tmp[i] = '\0';
  strcat (tmp, " ");
  strcat (tmp, program);
  strcat (tmp, " ");
  for (i = 0; i < 35 - len / 2; i++)
    {
      strcat (tmp, "-");
    }
  log_it (debug, tmp);
  system ("cat /tmp/mondo-run-prog.err >> /tmp/mondo-run-prog.tmp");
  unlink ("/tmp/mondo-run-prog.err");
  fin = fopen ("/tmp/mondo-run-prog.tmp", "r");
  if (fin)
    {
      for (fgets (incoming, MAX_STR_LEN, fin); !feof (fin);
	   fgets (incoming, MAX_STR_LEN, fin))
	{
/*	  for(i=0; incoming[i]!='\0'; i++);
	  for(; i>0 && incoming[i-1]<=32; i--);
	  incoming[i]='\0';
*/
	  strip_spaces (incoming);
	  log_it (debug, incoming);
	}
      fclose (fin);
    }
  log_it
    (debug, "--------------------------------end of output------------------------------");
  if (res)
    {
      log_it (debug, "...ran with errors.");
    }
  /* else { log_it(debug, "...ran just fine. :-)"); } */
  return (res);
}
コード例 #18
0
ファイル: conf.c プロジェクト: keszybz/kmscon
static int parse_line(struct conf_option *opts, size_t olen,
		      char **buf, size_t *size)
{
	char *key;
	char *value = NULL;
	char *line;
	char c;
	size_t len, klen;
	int ret;

	line = *buf;
	len = *size;

	/* parse key */
	key = line;
	while (len) {
		c = *line;
		if (c == '\n' ||
		    c == '#' ||
		    c == '=')
			break;
		++line;
		--len;
	}

	if (!len) {
		*line = 0;
		goto done;
	} else if (*line == '\n') {
		*line = 0;
		goto done;
	} else if (*line == '#') {
		*line = 0;
		goto skip_comment;
	} else if (*line != '=') {
		return -EFAULT;
	}

	*line++ = 0;
	--len;

	/* parse value */
	value = line;
	while (len) {
		c = *line;
		if (c == '\n' ||
		    c == '#')
			break;
		++line;
		--len;
	}

	if (!len) {
		*line = 0;
		goto done;
	} else if (*line == '\n') {
		*line = 0;
		goto done;
	} else if (*line == '#') {
		*line = 0;
		goto skip_comment;
	} else {
		return -EFAULT;
	}

skip_comment:
	while (len) {
		c = *line;
		if (c == '\n')
			break;
		++line;
		--len;
	}

done:
	strip_spaces(&key);
	
	klen = strlen(key);
	if (klen > 0) {
		if (value)
			strip_spaces(&value);

		ret = parse_kv_pair(opts, olen, key, value);
		if (ret)
			return ret;
	}

	if (!len) {
		*buf = NULL;
		*size = 0;
	} else {
		*buf = ++line;
		*size = --len;
	}

	return 0;
}