/* Do a sprintf at the given offset into a malloc-allocated buffer. Reallocates
   the buffer and updates the variables to make room if necessary. */
int strbuf_sprintf(char **buf, size_t *size, size_t *offset, const char *fmt, ...)
{
    va_list va;
    int n;

    ncat_assert(*offset <= *size);

    if (*buf == NULL) {
        *size = 1;
        *buf = (char *) safe_malloc(*size);
    }

    for (;;) {
        va_start(va, fmt);
        n = Vsnprintf(*buf + *offset, *size - *offset, fmt, va);
        va_end(va);
        if (n < 0)
            *size = MAX(*size, 1) * 2;
        else if (n >= *size - *offset)
            *size += n + 1;
        else
            break;
        *buf = (char *) safe_realloc(*buf, *size);
    }
    *offset += n;

    return n;
}
Esempio n. 2
0
File: textbox.c Progetto: adsr/agar
/* Set the text from a format string. */
void
AG_TextboxPrintf(AG_Textbox *tb, const char *fmt, ...)
{
	AG_Variable *stringb;
	va_list args;
	char *text;

	AG_ObjectLock(tb->ed);
	stringb = AG_GetVariable(tb->ed, "string", &text);
	if (fmt != NULL && fmt[0] != '\0') {
		va_start(args, fmt);
		Vsnprintf(text, stringb->info.size, fmt, args);
		va_end(args);
		tb->ed->pos = AG_LengthUTF8(text);
	} else {
		text[0] = '\0';
		tb->ed->pos = 0;
	}
	AG_TextboxBufferChanged(tb);
	AG_UnlockVariable(stringb);
	AG_ObjectUnlock(tb->ed);

	/* XXX for AG_Numerical, etc. */
	AG_Redraw(tb);
}
Esempio n. 3
0
int Snprintf(char *s, size_t n, const char *fmt, ...) {
  va_list ap;
  int ret;

  va_start(ap, fmt);
  ret = Vsnprintf(s, n, fmt, ap);
  va_end(ap);

  return ret;
}
Esempio n. 4
0
/**
 * Yet another assertion handler.
 */
void DEBUG_AssertFormat(const char * file, long line, Str format, ...)
{
    char msg[512];
#ifdef UNICODE
    Char msg2[COUNT(msg)];
#else /* !UNICODE */
#  define msg2 msg
#endif /* UNICODE */

#if defined(_WIN32) && !defined(_NT_KERNEL)
    ULONG lastError = GetLastError();
#  ifdef _USE_EXCEPTION_HANDLING
    __try {
#  endif /* _USE_EXCEPTION_HANDLING */
#endif /* _WIN32) && !_NT_KERNEL */
        int n;
        va_list va;
        va_start(va, format);

        /* format the message */
        n = Vsnprintf(msg2,COUNT(msg2),format,va);
#ifdef UNICODE
        msg[0] = 0;
        msg2[COUNT(msg2)-1] = 0;
        wcstombs(msg, msg2, COUNT(msg));
        msg[COUNT(msg)-1] = 0;
#endif /* UNICODE */

        /* if the output string is REALLY long, terminate it with ... */
        if (n >= COUNT(msg)-1 || n < 0) {
            n = COUNT(msg)-1;
            msg[n--] = 0;
            msg[n--] = '.'; 
            msg[n--] = '.'; 
            msg[n--] = '.';
            msg[n--] = ' ';
        } else {
            msg[COUNT(msg)-1] = 0;
        }

        va_end(va);
#if defined(_WIN32) && !defined(_NT_KERNEL)
#  ifdef _USE_EXCEPTION_HANDLING
    } __except(EXCEPTION_EXECUTE_HANDLER) {
        /* NOTE: ASSMSG1 macro would recursively invoke this function */
        TRACE1("EXCEPTION %08lX in DEBUG_AssertFormat\n",GetExceptionCode());
        ASSMSG("EXCEPTION in DEBUG_AssertFormat");
    }
#  endif /* _USE_EXCEPTION_HANDLING */
    DEBUG_Assert(msg, file, line);
    SetLastError(lastError);
#else
    DEBUG_Assert(msg, file, line);
#endif /* _WIN32) && !_NT_KERNEL */
}
Esempio n. 5
0
/* Set the label text (format string). */
void
AG_ButtonText(AG_Button *bu, const char *fmt, ...)
{
	char s[AG_LABEL_MAX];
	va_list ap;

	va_start(ap, fmt);
	Vsnprintf(s, sizeof(s), fmt, ap);
	va_end(ap);
	AG_ButtonTextS(bu, s);
}
Esempio n. 6
0
void DSAD_Printf(OUT const INT8 *string,...)
{
#if 0
	va_list args;
	int i;
	if (dsadPrintEnable == 1)
 	{
		va_start(args,string);
		i = Vsnprintf((char *)dsadPrintBuff,sizeof(dsadPrintBuff), string, args);
		va_end(args);
		DSADS_P("%s", dsadPrintBuff);
	}
#endif
}
Esempio n. 7
0
void KLog2 (const char *format, va_list ap)
{
	MutexLock (&dbg_mutex);
	
	Vsnprintf (&klog_entry[current_log][0], KLOG_WIDTH, format, ap);
	
	if (klog_to_screen == TRUE)
		KPrintString (&klog_entry[current_log][0]);

	current_log++;
	current_log %= KLOG_ENTRIES;
	
	MutexUnlock (&dbg_mutex);	
}
Esempio n. 8
0
/* Specify static text (format string). */
void
VG_TextPrintf(VG_Text *vt, const char *fmt, ...)
{
	va_list ap;

	VG_Lock(VGNODE(vt)->vg);
	if (fmt != NULL) {
		va_start(ap, fmt);
		Vsnprintf(vt->text, sizeof(vt->text), fmt, ap);
		va_end(ap);
	} else {
		vt->text[0] = '\0';
	}
	VG_Unlock(VGNODE(vt)->vg);
}
Esempio n. 9
0
File: textbox.c Progetto: adsr/agar
AG_Textbox *
AG_TextboxNew(void *parent, Uint flags, const char *fmt, ...)
{
	char s[AG_LABEL_MAX];
	va_list ap;

	if (fmt != NULL) {
		va_start(ap, fmt);
		Vsnprintf(s, sizeof(s), fmt, ap);
		va_end(ap);
		return AG_TextboxNewS(parent, flags, s);
	} else {
		return AG_TextboxNewS(parent, flags, NULL);
	}
}
Esempio n. 10
0
void KLog (const char *format, ...)
{
	va_list ap;
	
	va_start (ap, format);
	
	MutexLock (&dbg_mutex);
	
	Vsnprintf (&klog_entry[current_log][0], KLOG_WIDTH, format, ap);
	
	if (klog_to_screen == TRUE)
		KPrintString (&klog_entry[current_log][0]);

	current_log++;
	current_log %= KLOG_ENTRIES;
//	{ int i = 0; while (i < 5000000) {i++; Vsnprintf (&klog_entry[current_log][0], KLOG_WIDTH, format, ap);}}
			
	MutexUnlock (&dbg_mutex);	
	
	va_end (ap);
}
Esempio n. 11
0
void NcrackOutputTable::addItemFormatted(unsigned int row, 
					  unsigned int column,
					  bool fullrow,
					  const char *fmt, ...) {
  struct NcrackOutputTableCell *cell;
  int mc = maxColLen[column];
  unsigned int res;
  va_list ap; 
  va_start(ap,fmt);
  char buf[4096];
  res = Vsnprintf(buf, sizeof(buf), fmt, ap);
  va_end(ap);

  if (res > sizeof(buf))
    fatal("NcrackOutputTable only supports adding up to 4096 to a cell via %s.", __func__);

  addItem(row, column, fullrow, true, buf, res);

  if(fullrow) {
    maxColLen[column] = mc;
    cell = getCellAddy(row, column);
    cell->fullrow = fullrow;
  }
}
Esempio n. 12
0
/* Convert new nsiod to pcap descriptor. Other parameters have the same meaning
 * as for pcap_open_live in pcap(3).
 *   device   : pcap-style device name
 *   snaplen  : size of packet to be copied to hanler
 *   promisc  : whether to open device in promiscuous mode
 *   bpf_fmt   : berkeley filter
 * return value: NULL if everything was okay, or error string if error occurred. */
char* nsock_pcap_open(nsock_pool nsp, nsock_iod nsiod, const char *pcap_device, int snaplen,
                      int promisc, const char *bpf_fmt, ...) {
  msiod *nsi = (msiod *)nsiod;
  mspool *ms = (mspool *)nsp;
  mspcap *mp = (mspcap *)nsi->pcap;
  static char errorbuf[128];
  char err0r[PCAP_ERRBUF_SIZE];
  /* packet filter string */
  char bpf[4096];
  va_list ap;
  int failed, datalink;
  char *e;

  gettimeofday(&nsock_tod, NULL);

#ifdef PCAP_CAN_DO_SELECT

#if PCAP_BSD_SELECT_HACK
  /* MacOsX reports error if to_ms is too big (like INT_MAX) with error
   *  FAILED. Reported error: BIOCSRTIMEOUT: Invalid argument
   *  INT_MAX/6 (=357913941) seems to be working... */
  int to_ms = 357913941;
#else
  int to_ms = 200;
#endif /* PCAP_BSD_SELECT_HACK */

#else
  int to_ms = 1;
#endif

  if (mp)
    return "nsock-pcap: this nsi already has pcap device opened";

  mp = (mspcap *)safe_zalloc(sizeof(mspcap));
  nsi->pcap = (void *)mp;

  va_start(ap, bpf_fmt);
  if (Vsnprintf(bpf, sizeof(bpf), bpf_fmt, ap) >= (int)sizeof(bpf)) {
    va_end(ap);
    return "nsock-pcap: nsock_pcap_open called with too-large bpf filter arg";
  }
  va_end(ap);

  if (ms->tracelevel > 0)
      nsock_trace(ms,
                  "PCAP requested on device '%s' with berkeley filter '%s' (promisc=%i snaplen=%i to_ms=%i) (IOD #%li)",
                  pcap_device,bpf, promisc, snaplen, to_ms, nsi->id);

  failed = 0;
  do {
    mp->pt = pcap_open_live((char* )pcap_device, snaplen, promisc, to_ms, err0r);
    if (mp->pt)  /* okay, opened!*/
      break;

    /* sorry, something failed*/
    if (++failed >= 3) {
      mp->pcap_device = strdup(pcap_device);
      fprintf(stderr,
              "Call to pcap_open_live(%s, %d, %d, %d) failed three times. Reported error: %s\n"
              "There are several possible reasons for this, depending on your operating system:\n"
              "LINUX: If you are getting Socket type not supported, try modprobe af_packet or recompile your kernel with PACKET enabled.\n"
              "*BSD:  If you are getting device not configured, you need to recompile your kernel with Berkeley Packet Filter support.  If you are getting No such file or directory, try creating the device (eg cd /dev; MAKEDEV <device>; or use mknod).\n"
              "*WINDOWS:  Nmap only supports ethernet interfaces on Windows for most operations because Microsoft disabled raw sockets as of Windows XP SP2.  Depending on the reason for this error, it is possible that the --unprivileged command-line argument will help.\n"
              "SOLARIS:  If you are trying to scan localhost and getting '/dev/lo0: No such file or directory', complain to Sun.  I don't think Solaris can support advanced localhost scans.  You can probably use \"-PN -sT localhost\" though.\n\n",
        pcap_device, snaplen, promisc, to_ms, err0r);
      return "nsock-pcap: can't open pcap! Are you root?";
    }

    fprintf(stderr,
            "pcap_open_live(%s, %d, %d, %d) FAILED. Reported error: %s. Will wait %d seconds then retry.\n",
            pcap_device, snaplen, promisc, to_ms, err0r, 4*failed);
    sleep(4* failed);
  } while (1);

  e = nsock_pcap_set_filter(mp->pt, pcap_device, bpf);
  if (e)
    return e;

#ifdef WIN32
  /* We want any responses back ASAP */
  pcap_setmintocopy(mp->pt, 1);
#endif

  mp->l3_offset = nsock_pcap_get_l3_offset(mp->pt, &datalink);
  mp->snaplen = snaplen;
  mp->datalink = datalink;
  mp->pcap_device = strdup(pcap_device);
#ifdef PCAP_CAN_DO_SELECT
  mp->pcap_desc = pcap_get_selectable_fd(mp->pt);
#else
  mp->pcap_desc = -1;
#endif
  mp->readsd_count = 0;

  /* Without setting this ioctl, some systems (BSDs, though it depends on the
   * release) will buffer packets in non-blocking mode and only return them in a
   * bunch when the buffer is full. Setting the ioctl makes each one be
   * delivered immediately. This is how Linux works by default. See the comments
   * surrounding the setting of BIOCIMMEDIATE in libpcap/pcap-bpf.c. */
#ifdef BIOCIMMEDIATE
  if (mp->pcap_desc != -1) {
    int immediate = 1;

    if (ioctl(mp->pcap_desc, BIOCIMMEDIATE, &immediate) < 0)
      fatal("Cannot set BIOCIMMEDIATE on pcap descriptor");
  }
#endif

  /* Set device non-blocking */
  if (pcap_setnonblock(mp->pt, 1, err0r) < 0) {
    /* I can't do select() on pcap! blocking + no_select is fatal */
    if(mp->pcap_desc < 0){
      Snprintf(errorbuf, sizeof(errorbuf),
               "nsock-pcap: Failed to set pcap descriptor on device %s to nonblocking state: %s",
               pcap_device, err0r);
      return errorbuf;
    }

    /* When we use bsd hack we also need to set non-blocking */
#ifdef PCAP_BSD_SELECT_HACK
    Snprintf(errorbuf, sizeof(errorbuf),
             "nsock-pcap: Failed to set pcap descriptor on device %s to nonblocking state: %s",
             pcap_device, err0r);
    return errorbuf;
#endif

    /* in other case, we can accept blocking pcap */
    fprintf(stderr, "Failed to set pcap descriptor on device %s to nonblocking state: %s",
            pcap_device, err0r);
  }

  if (ms->tracelevel > 0)
      nsock_trace(ms, "PCAP created successfully on device '%s' (pcap_desc=%i bsd_hack=%i to_valid=%i l3_offset=%i) (IOD #%li)",
      pcap_device,
      mp->pcap_desc,
#if PCAP_BSD_SELECT_HACK
      1,
#else
      0,
#endif
#if PCAP_RECV_TIMEVAL_VALID
      1,
#else
      0,
#endif
      mp->l3_offset,
      nsi->id);

  return NULL;
}
Esempio n. 13
0
/* Same as nsock_write except you can use a printf-style format and you can only use this for ASCII strings */
nsock_event_id nsock_printf(nsock_pool ms_pool, nsock_iod ms_iod,
          nsock_ev_handler handler, int timeout_msecs, void *userdata, char *format, ...) {
  mspool *nsp = (mspool *)ms_pool;
  msiod *nsi = (msiod *)ms_iod;
  msevent *nse;
  char buf[4096];
  char *buf2 = NULL;
  int res, res2;
  int strlength = 0;
  char displaystr[256];

  va_list ap;
  va_start(ap,format);

  nse = msevent_new(nsp, NSE_TYPE_WRITE, nsi, timeout_msecs, handler, userdata);
  assert(nse);

  res = Vsnprintf(buf, sizeof(buf), format, ap);
  va_end(ap);

  if (res != -1) {
    if (res > sizeof(buf)) {
      buf2 = (char * )safe_malloc(res + 16);
      res2 = Vsnprintf(buf2, sizeof(buf), format, ap);
      if (res2 == -1 || res2 > res) {
        free(buf2);
        buf2 = NULL;
      } else
        strlength = res2;
    } else {
      buf2 = buf;
      strlength = res;
    }
  }

  if (!buf2) {
    nse->event_done = 1;
    nse->status = NSE_STATUS_ERROR;
    nse->errnum = EMSGSIZE;
  } else {
    if (strlength == 0) {
      nse->event_done = 1;
      nse->status = NSE_STATUS_SUCCESS;
    } else {
      fs_cat(&nse->iobuf, buf2, strlength);
    }
  }

  if (nsp->loglevel == NSOCK_LOG_DBG_ALL && nse->status != NSE_STATUS_ERROR && strlength < 80) {
    memcpy(displaystr, ": ", 2);
    memcpy(displaystr + 2, buf2, strlength);
    displaystr[2 + strlength] = '\0';
    replacenonprintable(displaystr + 2, strlength, '.');
  } else {
    displaystr[0] = '\0';
  }

  nsock_log_debug(nsp, "Write request for %d bytes to IOD #%li EID %li [%s]%s",
                  strlength, nsi->id, nse->id, get_peeraddr_string(nsi), displaystr);

  if (buf2 != buf)
    free(buf2);

  nsp_add_event(nsp, nse);

  return nse->id;
}
Esempio n. 14
0
/* Convert new nsiod to pcap descriptor. Other parameters have
 * the same meaning as for pcap_open_live in pcap(3).
 *   device   : pcap-style device name
 *   snaplen  : size of packet to be copied to handler
 *   promisc  : whether to open device in promiscuous mode
 *   bpf_fmt   : berkeley filter
 * return value: NULL if everything was okay, or error string
 * if error occurred. */
int nsock_pcap_open(nsock_pool nsp, nsock_iod nsiod, const char *pcap_device,
                    int snaplen, int promisc, const char *bpf_fmt, ...) {
  struct niod *nsi = (struct niod *)nsiod;
  struct npool *ms = (struct npool *)nsp;
  mspcap *mp = (mspcap *)nsi->pcap;
  char errbuf[PCAP_ERRBUF_SIZE];
  char bpf[4096];
  va_list ap;
  int failed, datalink;
  int rc;

#ifdef PCAP_CAN_DO_SELECT
#if PCAP_BSD_SELECT_HACK
  /* MacOsX reports error if to_ms is too big (like INT_MAX) with error
   * FAILED. Reported error: BIOCSRTIMEOUT: Invalid argument
   * INT_MAX/6 (=357913941) seems to be working... */
  int to_ms = 357913941;
#else
  int to_ms = 200;
#endif /* PCAP_BSD_SELECT_HACK */

#else
  int to_ms = 1;
#endif

  gettimeofday(&nsock_tod, NULL);

  if (mp) {
    nsock_log_error(ms, "This nsi already has pcap device opened");
    return -1;
  }

  mp = (mspcap *)safe_zalloc(sizeof(mspcap));
  nsi->pcap = (void *)mp;

  va_start(ap, bpf_fmt);
  rc = Vsnprintf(bpf, sizeof(bpf), bpf_fmt, ap);
  va_end(ap);

  if (rc >= (int)sizeof(bpf)) {
    nsock_log_error(ms, "Too-large bpf filter argument");
    return -1;
  }

  nsock_log_info(ms, "PCAP requested on device '%s' with berkeley filter '%s' "
                 "(promisc=%i snaplen=%i to_ms=%i) (IOD #%li)",
                 pcap_device,bpf, promisc, snaplen, to_ms, nsi->id);

  failed = 0;
  do {
    rc = nsock_pcap_try_open(ms, mp, pcap_device, snaplen, promisc, to_ms, errbuf);
    if (rc) {
      failed++;
      nsock_log_error(ms, "Will wait %d seconds then retry.", 4 * failed);
      sleep(4 * failed);
    }
  } while (rc && failed < PCAP_OPEN_MAX_RETRIES);

  if (rc) {
    nsock_log_error(ms, "pcap_open_live(%s, %d, %d, %d) failed %d times.",
                    pcap_device, snaplen, promisc, to_ms, failed);
    nsock_log_error(ms, PCAP_FAILURE_EXPL_MESSAGE);
    nsock_log_error(ms, "Can't open pcap! Are you root?");
    return -1;
  }

  rc = nsock_pcap_set_filter(ms, mp->pt, pcap_device, bpf);
  if (rc)
    return rc;

#ifdef WIN32
  /* We want any responses back ASAP */
  pcap_setmintocopy(mp->pt, 1);
#endif

  mp->l3_offset = nsock_pcap_get_l3_offset(mp->pt, &datalink);
  mp->snaplen = snaplen;
  mp->datalink = datalink;
  mp->pcap_device = strdup(pcap_device);
#ifdef PCAP_CAN_DO_SELECT
  mp->pcap_desc = pcap_get_selectable_fd(mp->pt);
#else
  mp->pcap_desc = -1;
#endif
  mp->readsd_count = 0;

  /* Without setting this ioctl, some systems (BSDs, though it depends on the
   * release) will buffer packets in non-blocking mode and only return them in a
   * bunch when the buffer is full. Setting the ioctl makes each one be
   * delivered immediately. This is how Linux works by default. See the comments
   * surrounding the setting of BIOCIMMEDIATE in libpcap/pcap-bpf.c. */
#ifdef BIOCIMMEDIATE
  if (mp->pcap_desc != -1) {
    int immediate = 1;

    if (ioctl(mp->pcap_desc, BIOCIMMEDIATE, &immediate) < 0)
      fatal("Cannot set BIOCIMMEDIATE on pcap descriptor");
  }
#endif

  /* Set device non-blocking */
  rc = pcap_setnonblock(mp->pt, 1, errbuf);
  if (rc) {

    /* I can't do select() on pcap!
     * blocking + no_select is fatal */
#ifndef PCAP_BSD_SELECT_HACK
    if (mp->pcap_desc < 0)
#endif
    {
      nsock_log_error(ms, "Failed to set pcap descriptor on device %s "
                      "to nonblocking mode: %s", pcap_device, errbuf);
      return -1;
    }
    /* in other case, we can accept blocking pcap */
    nsock_log_info(ms, "Failed to set pcap descriptor on device %s "
                   "to nonblocking state: %s", pcap_device, errbuf);
  }

  if (ms->loglevel <= NSOCK_LOG_INFO) {
    #if PCAP_BSD_SELECT_HACK
      int bsd_select_hack = 1;
    #else
      int bsd_select_hack = 0;
    #endif

    #if PCAP_RECV_TIMEVAL_VALID
      int recv_timeval_valid = 1;
    #else
      int recv_timeval_valid = 0;
    #endif

    nsock_log_info(ms, "PCAP created successfully on device '%s' "
                   "(pcap_desc=%i bsd_hack=%i to_valid=%i l3_offset=%i) (IOD #%li)",
                   pcap_device, mp->pcap_desc, bsd_select_hack,
                   recv_timeval_valid, mp->l3_offset, nsi->id);
  }
  return 0;
}