static int xbuf_format_converter(char **outbuf, const char *fmt, va_list ap)
{
  register char *s = nullptr;
  char *q;
  int s_len;

  register int min_width = 0;
  int precision = 0;
  enum {
    LEFT, RIGHT
  } adjust;
  char pad_char;
  char prefix_char;

  double fp_num;
  wide_int i_num = (wide_int) 0;
  u_wide_int ui_num;

  char num_buf[NUM_BUF_SIZE];
  char char_buf[2];      /* for printing %% and %<unknown> */

#ifdef HAVE_LOCALE_H
  struct lconv *lconv = nullptr;
#endif

  /*
   * Flag variables
   */
  length_modifier_e modifier;
  boolean_e alternate_form;
  boolean_e print_sign;
  boolean_e print_blank;
  boolean_e adjust_precision;
  boolean_e adjust_width;
  int is_negative;

  int size = 240;
  char *result = (char *)malloc(size);
  int outpos = 0;

  while (*fmt) {
    if (*fmt != '%') {
      appendchar(&result, &outpos, &size, *fmt);
    } else {
      /*
       * Default variable settings
       */
      adjust = RIGHT;
      alternate_form = print_sign = print_blank = NO;
      pad_char = ' ';
      prefix_char = NUL;

      fmt++;

      /*
       * Try to avoid checking for flags, width or precision
       */
      if (isascii((int)*fmt) && !islower((int)*fmt)) {
        /*
         * Recognize flags: -, #, BLANK, +
         */
        for (;; fmt++) {
          if (*fmt == '-')
            adjust = LEFT;
          else if (*fmt == '+')
            print_sign = YES;
          else if (*fmt == '#')
            alternate_form = YES;
          else if (*fmt == ' ')
            print_blank = YES;
          else if (*fmt == '0')
            pad_char = '0';
          else
            break;
        }

        /*
         * Check if a width was specified
         */
        if (isdigit((int)*fmt)) {
          STR_TO_DEC(fmt, min_width);
          adjust_width = YES;
        } else if (*fmt == '*') {
          min_width = va_arg(ap, int);
          fmt++;
          adjust_width = YES;
          if (min_width < 0) {
            adjust = LEFT;
            min_width = -min_width;
          }
        } else
          adjust_width = NO;

        /*
         * Check if a precision was specified
         *
         * XXX: an unreasonable amount of precision may be specified
         * resulting in overflow of num_buf. Currently we
         * ignore this possibility.
         */
        if (*fmt == '.') {
          adjust_precision = YES;
          fmt++;
          if (isdigit((int)*fmt)) {
            STR_TO_DEC(fmt, precision);
          } else if (*fmt == '*') {
            precision = va_arg(ap, int);
            fmt++;
            if (precision < 0)
              precision = 0;
          } else
            precision = 0;
        } else
          adjust_precision = NO;
      } else
        adjust_precision = adjust_width = NO;

      /*
       * Modifier check
       */
      switch (*fmt) {
        case 'L':
          fmt++;
          modifier = LM_LONG_DOUBLE;
          break;
        case 'I':
          fmt++;
#if SIZEOF_LONG_LONG
          if (*fmt == '6' && *(fmt+1) == '4') {
            fmt += 2;
            modifier = LM_LONG_LONG;
          } else
#endif
            if (*fmt == '3' && *(fmt+1) == '2') {
              fmt += 2;
              modifier = LM_LONG;
            } else {
#ifdef _WIN64
              modifier = LM_LONG_LONG;
#else
              modifier = LM_LONG;
#endif
            }
          break;
        case 'l':
          fmt++;
#if SIZEOF_LONG_LONG
          if (*fmt == 'l') {
            fmt++;
            modifier = LM_LONG_LONG;
          } else
#endif
            modifier = LM_LONG;
          break;
        case 'z':
          fmt++;
          modifier = LM_SIZE_T;
          break;
        case 'j':
          fmt++;
#if SIZEOF_INTMAX_T
          modifier = LM_INTMAX_T;
#else
          modifier = LM_SIZE_T;
#endif
          break;
        case 't':
          fmt++;
#if SIZEOF_PTRDIFF_T
          modifier = LM_PTRDIFF_T;
#else
          modifier = LM_SIZE_T;
#endif
          break;
        case 'h':
          fmt++;
          if (*fmt == 'h') {
            fmt++;
          }
          /* these are promoted to int, so no break */
        default:
          modifier = LM_STD;
          break;
      }

      /*
       * Argument extraction and printing.
       * First we determine the argument type.
       * Then, we convert the argument to a string.
       * On exit from the switch, s points to the string that
       * must be printed, s_len has the length of the string
       * The precision requirements, if any, are reflected in s_len.
       *
       * NOTE: pad_char may be set to '0' because of the 0 flag.
       *   It is reset to ' ' by non-numeric formats
       */
      switch (*fmt) {
        case 'u':
          switch(modifier) {
            default:
              i_num = (wide_int) va_arg(ap, unsigned int);
              break;
            case LM_LONG_DOUBLE:
              goto fmt_error;
            case LM_LONG:
              i_num = (wide_int) va_arg(ap, unsigned long int);
              break;
            case LM_SIZE_T:
              i_num = (wide_int) va_arg(ap, size_t);
              break;
#if SIZEOF_LONG_LONG
            case LM_LONG_LONG:
              i_num = (wide_int) va_arg(ap, u_wide_int);
              break;
#endif
#if SIZEOF_INTMAX_T
            case LM_INTMAX_T:
              i_num = (wide_int) va_arg(ap, uintmax_t);
              break;
#endif
#if SIZEOF_PTRDIFF_T
            case LM_PTRDIFF_T:
              i_num = (wide_int) va_arg(ap, ptrdiff_t);
              break;
#endif
          }
          /*
           * The rest also applies to other integer formats, so fall
           * into that case.
           */
        case 'd':
        case 'i':
          /*
           * Get the arg if we haven't already.
           */
          if ((*fmt) != 'u') {
            switch(modifier) {
              default:
                i_num = (wide_int) va_arg(ap, int);
                break;
              case LM_LONG_DOUBLE:
                goto fmt_error;
              case LM_LONG:
                i_num = (wide_int) va_arg(ap, long int);
                break;
              case LM_SIZE_T:
#if SIZEOF_SSIZE_T
                i_num = (wide_int) va_arg(ap, ssize_t);
#else
                i_num = (wide_int) va_arg(ap, size_t);
#endif
                break;
#if SIZEOF_LONG_LONG
              case LM_LONG_LONG:
                i_num = (wide_int) va_arg(ap, wide_int);
                break;
#endif
#if SIZEOF_INTMAX_T
              case LM_INTMAX_T:
                i_num = (wide_int) va_arg(ap, intmax_t);
                break;
#endif
#if SIZEOF_PTRDIFF_T
              case LM_PTRDIFF_T:
                i_num = (wide_int) va_arg(ap, ptrdiff_t);
                break;
#endif
            }
          }
          s = ap_php_conv_10(i_num, (*fmt) == 'u', &is_negative,
                &num_buf[NUM_BUF_SIZE], &s_len);
          FIX_PRECISION(adjust_precision, precision, s, s_len);

          if (*fmt != 'u') {
            if (is_negative)
              prefix_char = '-';
            else if (print_sign)
              prefix_char = '+';
            else if (print_blank)
              prefix_char = ' ';
          }
          break;

        case 'o':
          switch(modifier) {
            default:
              ui_num = (u_wide_int) va_arg(ap, unsigned int);
              break;
            case LM_LONG_DOUBLE:
              goto fmt_error;
            case LM_LONG:
              ui_num = (u_wide_int) va_arg(ap, unsigned long int);
              break;
            case LM_SIZE_T:
              ui_num = (u_wide_int) va_arg(ap, size_t);
              break;
#if SIZEOF_LONG_LONG
            case LM_LONG_LONG:
              ui_num = (u_wide_int) va_arg(ap, u_wide_int);
              break;
#endif
#if SIZEOF_INTMAX_T
            case LM_INTMAX_T:
              ui_num = (u_wide_int) va_arg(ap, uintmax_t);
              break;
#endif
#if SIZEOF_PTRDIFF_T
            case LM_PTRDIFF_T:
              ui_num = (u_wide_int) va_arg(ap, ptrdiff_t);
              break;
#endif
          }
          s = ap_php_conv_p2(ui_num, 3, *fmt,
                &num_buf[NUM_BUF_SIZE], &s_len);
          FIX_PRECISION(adjust_precision, precision, s, s_len);
          if (alternate_form && *s != '0') {
            *--s = '0';
            s_len++;
          }
          break;

        case 'x':
        case 'X':
          switch(modifier) {
            default:
              ui_num = (u_wide_int) va_arg(ap, unsigned int);
              break;
            case LM_LONG_DOUBLE:
              goto fmt_error;
            case LM_LONG:
              ui_num = (u_wide_int) va_arg(ap, unsigned long int);
              break;
            case LM_SIZE_T:
              ui_num = (u_wide_int) va_arg(ap, size_t);
              break;
#if SIZEOF_LONG_LONG
            case LM_LONG_LONG:
              ui_num = (u_wide_int) va_arg(ap, u_wide_int);
              break;
#endif
#if SIZEOF_INTMAX_T
            case LM_INTMAX_T:
              ui_num = (u_wide_int) va_arg(ap, uintmax_t);
              break;
#endif
#if SIZEOF_PTRDIFF_T
            case LM_PTRDIFF_T:
              ui_num = (u_wide_int) va_arg(ap, ptrdiff_t);
              break;
#endif
          }
          s = ap_php_conv_p2(ui_num, 4, *fmt,
                &num_buf[NUM_BUF_SIZE], &s_len);
          FIX_PRECISION(adjust_precision, precision, s, s_len);
          if (alternate_form && i_num != 0) {
            *--s = *fmt;  /* 'x' or 'X' */
            *--s = '0';
            s_len += 2;
          }
          break;

        case 's':
        case 'v':
          s = va_arg(ap, char *);
          if (s != nullptr) {
            s_len = strlen(s);
            if (adjust_precision && precision < s_len)
              s_len = precision;
          } else {
            s = const_cast<char*>(s_null);
            s_len = S_NULL_LEN;
          }
          pad_char = ' ';
          break;

        case 'f':
        case 'F':
        case 'e':
        case 'E':
          switch(modifier) {
            case LM_LONG_DOUBLE:
              fp_num = (double) va_arg(ap, long double);
              break;
            case LM_STD:
              fp_num = va_arg(ap, double);
              break;
            default:
              goto fmt_error;
          }

          if (std::isnan(fp_num)) {
            s = const_cast<char*>("nan");
            s_len = 3;
          } else if (std::isinf(fp_num)) {
            s = const_cast<char*>("inf");
            s_len = 3;
          } else {
#ifdef HAVE_LOCALE_H
            if (!lconv) {
              lconv = localeconv();
            }
#endif
            s = php_conv_fp((*fmt == 'f')?'F':*fmt, fp_num, alternate_form,
             (adjust_precision == NO) ? FLOAT_DIGITS : precision,
             (*fmt == 'f')?LCONV_DECIMAL_POINT:'.',
                  &is_negative, &num_buf[1], &s_len);
            if (is_negative)
              prefix_char = '-';
            else if (print_sign)
              prefix_char = '+';
            else if (print_blank)
              prefix_char = ' ';
          }
          break;

        case 'g':
        case 'k':
        case 'G':
        case 'H':
          switch(modifier) {
            case LM_LONG_DOUBLE:
              fp_num = (double) va_arg(ap, long double);
              break;
            case LM_STD:
              fp_num = va_arg(ap, double);
              break;
            default:
              goto fmt_error;
          }

          if (std::isnan(fp_num)) {
             s = const_cast<char*>("NAN");
             s_len = 3;
             break;
           } else if (std::isinf(fp_num)) {
             if (fp_num > 0) {
               s = const_cast<char*>("INF");
               s_len = 3;
             } else {
               s = const_cast<char*>("-INF");
               s_len = 4;
             }
             break;
           }

          if (adjust_precision == NO)
            precision = FLOAT_DIGITS;
          else if (precision == 0)
            precision = 1;
          /*
           * * We use &num_buf[ 1 ], so that we have room for the sign
           */
#ifdef HAVE_LOCALE_H
          if (!lconv) {
            lconv = localeconv();
          }
#endif
          s = php_gcvt(fp_num, precision,
                       (*fmt=='H' || *fmt == 'k') ? '.' : LCONV_DECIMAL_POINT,
                       (*fmt == 'G' || *fmt == 'H')?'E':'e', &num_buf[1]);
          if (*s == '-')
            prefix_char = *s++;
          else if (print_sign)
            prefix_char = '+';
          else if (print_blank)
            prefix_char = ' ';

          s_len = strlen(s);

          if (alternate_form && (q = strchr(s, '.')) == nullptr)
            s[s_len++] = '.';
          break;

        case 'c':
          char_buf[0] = (char) (va_arg(ap, int));
          s = &char_buf[0];
          s_len = 1;
          pad_char = ' ';
          break;

        case '%':
          char_buf[0] = '%';
          s = &char_buf[0];
          s_len = 1;
          pad_char = ' ';
          break;

        case 'n':
          *(va_arg(ap, int *)) = outpos;
          goto skip_output;

          /*
           * Always extract the argument as a "char *" pointer. We
           * should be using "void *" but there are still machines
           * that don't understand it.
           * If the pointer size is equal to the size of an unsigned
           * integer we convert the pointer to a hex number, otherwise
           * we print "%p" to indicate that we don't handle "%p".
           */
        case 'p':
          if (sizeof(char *) <= sizeof(u_wide_int)) {
            ui_num = (u_wide_int)((size_t) va_arg(ap, char *));
            s = ap_php_conv_p2(ui_num, 4, 'x',
                &num_buf[NUM_BUF_SIZE], &s_len);
            if (ui_num != 0) {
              *--s = 'x';
              *--s = '0';
              s_len += 2;
            }
          } else {
            s = const_cast<char*>("%p");
            s_len = 2;
          }
          pad_char = ' ';
          break;

        case NUL:
          /*
           * The last character of the format string was %.
           * We ignore it.
           */
          continue;

fmt_error:
        throw Exception("Illegal length modifier specified '%c'", *fmt);

          /*
           * The default case is for unrecognized %'s.
           * We print %<char> to help the user identify what
           * option is not understood.
           * This is also useful in case the user wants to pass
           * the output of format_converter to another function
           * that understands some other %<char> (like syslog).
           * Note that we can't point s inside fmt because the
           * unknown <char> could be preceded by width etc.
           */
        default:
          char_buf[0] = '%';
          char_buf[1] = *fmt;
          s = char_buf;
          s_len = 2;
          pad_char = ' ';
          break;
      }

      if (prefix_char != NUL) {
        *--s = prefix_char;
        s_len++;
      }
      if (adjust_width && adjust == RIGHT && min_width > s_len) {
        if (pad_char == '0' && prefix_char != NUL) {
          appendchar(&result, &outpos, &size, *s);
          s++;
          s_len--;
          min_width--;
        }
        for (int i = 0; i < min_width - s_len; i++) {
          appendchar(&result, &outpos, &size, pad_char);
        }
      }
      /*
       * Print the (for now) non-null terminated string s.
       */
      appendsimplestring(&result, &outpos, &size, s, s_len);

      if (adjust_width && adjust == LEFT && min_width > s_len) {
        for (int i = 0; i < min_width - s_len; i++) {
          appendchar(&result, &outpos, &size, pad_char);
        }
      }
    }
skip_output:
    fmt++;
  }
  /*
   * Add the terminating null here since it wasn't added incrementally above
   * once the whole string has been composed.
   */
  result[outpos] = NUL;
  *outbuf = result;
  return outpos;
}


static const char * float32_avp ( diam_ctx_t * c , diam_avp_t * a , tvbuff_t * tvb , diam_sub_dis_t * diam_sub_dis_inf _U_ ) {
 char * label = NULL ;
 proto_item * pi ;
 gint length = tvb_reported_length ( tvb ) ;
 if ( length == 4 ) {
 if ( c -> tree ) {
 pi = proto_tree_add_item ( c -> tree , a -> hf_value , tvb , 0 , length , ENC_BIG_ENDIAN ) ;
 label = ( char * ) wmem_alloc ( wmem_packet_scope ( ) , ITEM_LABEL_LENGTH + 1 ) ;
 proto_item_fill_label ( PITEM_FINFO ( pi ) , label ) ;
 label = strstr ( label , ": " ) + 2 ;
 }
 }
 else {
 pi = proto_tree_add_bytes_format ( c -> tree , hf_diameter_avp_data_wrong_length , tvb , 0 , length , NULL , "Error! Bad Float32 Length" ) ;
 expert_add_info_format ( c -> pinfo , pi , & ei_diameter_avp_len , "Bad Float32 Length (%u)" , length ) ;
 PROTO_ITEM_SET_GENERATED ( pi ) ;
 }
 return label ;
 }


getword(f, word, newlinep, filename)
    FILE *f;
    char *word;
    int *newlinep;
    char *filename;
{
    int c, len, escape;
    int quoted, comment;
    int value, digit, got, n;

#define isoctal(c) ((c) >= '0' && (c) < '8')

    *newlinep = 0;
    len = 0;
    escape = 0;
    comment = 0;
    quoted = 0;

    /*
     * First skip white-space and comments.
     */
    for (;;) {
	c = getc(f);
	if (c == EOF)
	    break;

	/*
	 * A newline means the end of a comment; backslash-newline
	 * is ignored.  Note that we cannot have escape && comment.
	 */
	if (c == '\n') {
	    if (!escape) {
		*newlinep = 1;
		comment = 0;
	    } else
		escape = 0;
	    continue;
	}

	/*
	 * Ignore characters other than newline in a comment.
	 */
	if (comment)
	    continue;

	/*
	 * If this character is escaped, we have a word start.
	 */
	if (escape)
	    break;

	/*
	 * If this is the escape character, look at the next character.
	 */
	if (c == '\\') {
	    escape = 1;
	    continue;
	}

	/*
	 * If this is the start of a comment, ignore the rest of the line.
	 */
	if (c == '#') {
	    comment = 1;
	    continue;
	}

	/*
	 * A non-whitespace character is the start of a word.
	 */
	if (!isspace(c))
	    break;
    }

    /*
     * Process characters until the end of the word.
     */
    while (c != EOF) {
	if (escape) {
	    /*
	     * This character is escaped: backslash-newline is ignored,
	     * various other characters indicate particular values
	     * as for C backslash-escapes.
	     */
	    escape = 0;
	    if (c == '\n') {
	        c = getc(f);
		continue;
	    }

	    got = 0;
	    switch (c) {
	    case 'a':
		value = '\a';
		break;
	    case 'b':
		value = '\b';
		break;
	    case 'f':
		value = '\f';
		break;
	    case 'n':
		value = '\n';
		break;
	    case 'r':
		value = '\r';
		break;
	    case 's':
		value = ' ';
		break;
	    case 't':
		value = '\t';
		break;

	    default:
		if (isoctal(c)) {
		    /*
		     * \ddd octal sequence
		     */
		    value = 0;
		    for (n = 0; n < 3 && isoctal(c); ++n) {
			value = (value << 3) + (c & 07);
			c = getc(f);
		    }
		    got = 1;
		    break;
		}

		if (c == 'x') {
		    /*
		     * \x<hex_string> sequence
		     */
		    value = 0;
		    c = getc(f);
		    for (n = 0; n < 2 && isxdigit(c); ++n) {
			digit = toupper(c) - '0';
			if (digit > 10)
			    digit += '0' + 10 - 'A';
			value = (value << 4) + digit;
			c = getc (f);
		    }
		    got = 1;
		    break;
		}

		/*
		 * Otherwise the character stands for itself.
		 */
		value = c;
		break;
	    }

	    /*
	     * Store the resulting character for the escape sequence.
	     */
	    if (len < MAXWORDLEN-1)
		word[len] = value;
	    ++len;

	    if (!got)
		c = getc(f);
	    continue;
	}

	/*
	 * Backslash starts a new escape sequence.
	 */
	if (c == '\\') {
	    escape = 1;
	    c = getc(f);
	    continue;
	}

	/*
	 * Not escaped: check for the start or end of a quoted
	 * section and see if we've reached the end of the word.
	 */
	if (quoted) {
	    if (c == quoted) {
		quoted = 0;
		c = getc(f);
		continue;
	    }
	} else if (c == '"' || c == '\'') {
	    quoted = c;
	    c = getc(f);
	    continue;
	} else if (isspace(c) || c == '#') {
	    ungetc (c, f);
	    break;
	}

	/*
	 * An ordinary character: store it in the word and get another.
	 */
	if (len < MAXWORDLEN-1)
	    word[len] = c;
	++len;

	c = getc(f);
    }

    /*
     * End of the word: check for errors.
     */
    if (c == EOF) {
	if (ferror(f)) {
	    if (errno == 0)
		errno = EIO;
	    option_error("Error reading %s: %m", filename);
	    die(1);
	}
	/*
	 * If len is zero, then we didn't find a word before the
	 * end of the file.
	 */
	if (len == 0)
	    return 0;
	if (quoted)
	    option_error("warning: quoted word runs to end of file (%.20s...)",
			 filename, word);
    }

    /*
     * Warn if the word was too long, and append a terminating null.
     */
    if (len >= MAXWORDLEN) {
	option_error("warning: word in file %s too long (%.20s...)",
		     filename, word);
	len = MAXWORDLEN - 1;
    }
    word[len] = 0;

    return 1;

#undef isoctal

}


static void scsi_cd_class_initfn(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); SCSIDeviceClass *sc = SCSI_DEVICE_CLASS(klass); sc->init = scsi_cd_initfn; sc->destroy = scsi_destroy; sc->alloc_req = scsi_new_request; sc->unit_attention_reported = scsi_disk_unit_attention_reported; dc->fw_name = "disk"; dc->desc = "virtual SCSI CD-ROM"; dc->reset = scsi_disk_reset; dc->props = scsi_cd_properties; dc->vmsd = &vmstate_scsi_disk_state; }


eap_response(esp, inp, id, len)
eap_state *esp;
u_char *inp;
int id;
int len;
{
	u_char typenum;
	u_char vallen;
	int secret_len;
	char secret[MAXSECRETLEN];
	char rhostname[256];
	MD5_CTX mdContext;
	u_char hash[MD5_SIGNATURE_SIZE];
#ifdef USE_SRP
	struct t_server *ts;
	struct t_num A;
	SHA1_CTX ctxt;
	u_char dig[SHA_DIGESTSIZE];
#endif /* USE_SRP */

	if (esp->es_server.ea_id != id) {
		dbglog("EAP: discarding Response %d; expected ID %d", id,
		    esp->es_server.ea_id);
		return;
	}

	esp->es_server.ea_responses++;

	if (len <= 0) {
		error("EAP: empty Response message discarded");
		return;
	}

	GETCHAR(typenum, inp);
	len--;

	switch (typenum) {
	case EAPT_IDENTITY:
		if (esp->es_server.ea_state != eapIdentify) {
			dbglog("EAP discarding unwanted Identify \"%.q\"", len,
			    inp);
			break;
		}
		info("EAP: unauthenticated peer name \"%.*q\"", len, inp);
		if (esp->es_server.ea_peer != NULL &&
		    esp->es_server.ea_peer != remote_name)
			free(esp->es_server.ea_peer);
		esp->es_server.ea_peer = malloc(len + 1);
		if (esp->es_server.ea_peer == NULL) {
			esp->es_server.ea_peerlen = 0;
			eap_figure_next_state(esp, 1);
			break;
		}
		BCOPY(inp, esp->es_server.ea_peer, len);
		esp->es_server.ea_peer[len] = '\0';
		esp->es_server.ea_peerlen = len;
		eap_figure_next_state(esp, 0);
		break;

	case EAPT_NOTIFICATION:
		dbglog("EAP unexpected Notification; response discarded");
		break;

	case EAPT_NAK:
		if (len < 1) {
			info("EAP: Nak Response with no suggested protocol");
			eap_figure_next_state(esp, 1);
			break;
		}

		GETCHAR(vallen, inp);
		len--;

		if (!explicit_remote && esp->es_server.ea_state == eapIdentify){
			/* Peer cannot Nak Identify Request */
			eap_figure_next_state(esp, 1);
			break;
		}

		switch (vallen) {
		case EAPT_SRP:
			/* Run through SRP validator selection again. */
			esp->es_server.ea_state = eapIdentify;
			eap_figure_next_state(esp, 0);
			break;

		case EAPT_MD5CHAP:
			esp->es_server.ea_state = eapMD5Chall;
			break;

		default:
			dbglog("EAP: peer requesting unknown Type %d", vallen);
			switch (esp->es_server.ea_state) {
			case eapSRP1:
			case eapSRP2:
			case eapSRP3:
				esp->es_server.ea_state = eapMD5Chall;
				break;
			case eapMD5Chall:
			case eapSRP4:
				esp->es_server.ea_state = eapIdentify;
				eap_figure_next_state(esp, 0);
				break;
			default:
				break;
			}
			break;
		}
		break;

	case EAPT_MD5CHAP:
		if (esp->es_server.ea_state != eapMD5Chall) {
			error("EAP: unexpected MD5-Response");
			eap_figure_next_state(esp, 1);
			break;
		}
		if (len < 1) {
			error("EAP: received MD5-Response with no data");
			eap_figure_next_state(esp, 1);
			break;
		}
		GETCHAR(vallen, inp);
		len--;
		if (vallen != 16 || vallen > len) {
			error("EAP: MD5-Response with bad length %d", vallen);
			eap_figure_next_state(esp, 1);
			break;
		}

		/* Not so likely to happen. */
		if (vallen >= len + sizeof (rhostname)) {
			dbglog("EAP: trimming really long peer name down");
			BCOPY(inp + vallen, rhostname, sizeof (rhostname) - 1);
			rhostname[sizeof (rhostname) - 1] = '\0';
		} else {
			BCOPY(inp + vallen, rhostname, len - vallen);
			rhostname[len - vallen] = '\0';
		}

		/* In case the remote doesn't give us his name. */
		if (explicit_remote ||
		    (remote_name[0] != '\0' && vallen == len))
			strlcpy(rhostname, remote_name, sizeof (rhostname));

		/*
		 * Get the secret for authenticating the specified
		 * host.
		 */
		if (!get_secret(esp->es_unit, rhostname,
		    esp->es_server.ea_name, secret, &secret_len, 1)) {
			dbglog("EAP: no MD5 secret for auth of %q", rhostname);
			eap_send_failure(esp);
			break;
		}
		MD5_Init(&mdContext);
		MD5_Update(&mdContext, &esp->es_server.ea_id, 1);
		MD5_Update(&mdContext, (u_char *)secret, secret_len);
		BZERO(secret, sizeof (secret));
		MD5_Update(&mdContext, esp->es_challenge, esp->es_challen);
		MD5_Final(hash, &mdContext);
		if (BCMP(hash, inp, MD5_SIGNATURE_SIZE) != 0) {
			eap_send_failure(esp);
			break;
		}
		esp->es_server.ea_type = EAPT_MD5CHAP;
		eap_send_success(esp);
		eap_figure_next_state(esp, 0);
		if (esp->es_rechallenge != 0)
			TIMEOUT(eap_rechallenge, esp, esp->es_rechallenge);
		break;

#ifdef USE_SRP
	case EAPT_SRP:
		if (len < 1) {
			error("EAP: empty SRP Response");
			eap_figure_next_state(esp, 1);
			break;
		}
		GETCHAR(typenum, inp);
		len--;
		switch (typenum) {
		case EAPSRP_CKEY:
			if (esp->es_server.ea_state != eapSRP1) {
				error("EAP: unexpected SRP Subtype 1 Response");
				eap_figure_next_state(esp, 1);
				break;
			}
			A.data = inp;
			A.len = len;
			ts = (struct t_server *)esp->es_server.ea_session;
			assert(ts != NULL);
			esp->es_server.ea_skey = t_servergetkey(ts, &A);
			if (esp->es_server.ea_skey == NULL) {
				/* Client's A value is bogus; terminate now */
				error("EAP: bogus A value from client");
				eap_send_failure(esp);
			} else {
				eap_figure_next_state(esp, 0);
			}
			break;

		case EAPSRP_CVALIDATOR:
			if (esp->es_server.ea_state != eapSRP2) {
				error("EAP: unexpected SRP Subtype 2 Response");
				eap_figure_next_state(esp, 1);
				break;
			}
			if (len < sizeof (u_int32_t) + SHA_DIGESTSIZE) {
				error("EAP: M1 length %d < %d", len,
				    sizeof (u_int32_t) + SHA_DIGESTSIZE);
				eap_figure_next_state(esp, 1);
				break;
			}
			GETLONG(esp->es_server.ea_keyflags, inp);
			ts = (struct t_server *)esp->es_server.ea_session;
			assert(ts != NULL);
			if (t_serververify(ts, inp)) {
				info("EAP: unable to validate client identity");
				eap_send_failure(esp);
				break;
			}
			eap_figure_next_state(esp, 0);
			break;

		case EAPSRP_ACK:
			if (esp->es_server.ea_state != eapSRP3) {
				error("EAP: unexpected SRP Subtype 3 Response");
				eap_send_failure(esp);
				break;
			}
			esp->es_server.ea_type = EAPT_SRP;
			eap_send_success(esp);
			eap_figure_next_state(esp, 0);
			if (esp->es_rechallenge != 0)
				TIMEOUT(eap_rechallenge, esp,
				    esp->es_rechallenge);
			if (esp->es_lwrechallenge != 0)
				TIMEOUT(srp_lwrechallenge, esp,
				    esp->es_lwrechallenge);
			break;

		case EAPSRP_LWRECHALLENGE:
			if (esp->es_server.ea_state != eapSRP4) {
				info("EAP: unexpected SRP Subtype 4 Response");
				return;
			}
			if (len != SHA_DIGESTSIZE) {
				error("EAP: bad Lightweight rechallenge "
				    "response");
				return;
			}
			SHA1Init(&ctxt);
			vallen = id;
			SHA1Update(&ctxt, &vallen, 1);
			SHA1Update(&ctxt, esp->es_server.ea_skey,
			    SESSION_KEY_LEN);
			SHA1Update(&ctxt, esp->es_challenge, esp->es_challen);
			SHA1Update(&ctxt, esp->es_server.ea_peer,
			    esp->es_server.ea_peerlen);
			SHA1Final(dig, &ctxt);
			if (BCMP(dig, inp, SHA_DIGESTSIZE) != 0) {
				error("EAP: failed Lightweight rechallenge");
				eap_send_failure(esp);
				break;
			}
			esp->es_server.ea_state = eapOpen;
			if (esp->es_lwrechallenge != 0)
				TIMEOUT(srp_lwrechallenge, esp,
				    esp->es_lwrechallenge);
			break;
		}
		break;
#endif /* USE_SRP */

	default:
		/* This can't happen. */
		error("EAP: unknown Response type %d; ignored", typenum);
		return;
	}

	if (esp->es_server.ea_timeout > 0) {
		UNTIMEOUT(eap_server_timeout, (void *)esp);
	}

	if (esp->es_server.ea_state != eapBadAuth &&
	    esp->es_server.ea_state != eapOpen) {
		esp->es_server.ea_id++;
		eap_send_request(esp);
	}
}


static void vnc_init_basic_info_from_remote_addr(QIOChannelSocket *ioc, VncBasicInfo *info, Error **errp) { SocketAddress *addr = NULL; addr = qio_channel_socket_get_remote_address(ioc, errp); if (!addr) { return; } vnc_init_basic_info(addr, info, errp); qapi_free_SocketAddress(addr); }


void helper_mtc0_pagemask(CPUMIPSState *env, target_ulong arg1) { /* 1k pages not implemented */ env->CP0_PageMask = arg1 & (0x1FFFFFFF & (TARGET_PAGE_MASK << 1)); }


static struct page *get_arg_page(struct linux_binprm *bprm, unsigned long pos,
		int write)
{
	struct page *page;
	int ret;
	unsigned int gup_flags = FOLL_FORCE;

#ifdef CONFIG_STACK_GROWSUP
	if (write) {
		ret = expand_downwards(bprm->vma, pos);
		if (ret < 0)
			return NULL;
	}
#endif

	if (write)
		gup_flags |= FOLL_WRITE;

	/*
	 * We are doing an exec().  'current' is the process
	 * doing the exec and bprm->mm is the new process's mm.
	 */
	ret = get_user_pages_remote(current, bprm->mm, pos, 1, gup_flags,
			&page, NULL, NULL);
	if (ret <= 0)
		return NULL;

	if (write) {
		unsigned long size = bprm->vma->vm_end - bprm->vma->vm_start;
		struct rlimit *rlim;

		acct_arg_size(bprm, size / PAGE_SIZE);

		/*
		 * We've historically supported up to 32 pages (ARG_MAX)
		 * of argument strings even with small stacks
		 */
		if (size <= ARG_MAX)
			return page;

		/*
		 * Limit to 1/4-th the stack size for the argv+env strings.
		 * This ensures that:
		 *  - the remaining binfmt code will not run out of stack space,
		 *  - the program will have a reasonable amount of stack left
		 *    to work from.
		 */
		rlim = current->signal->rlim;
		if (size > ACCESS_ONCE(rlim[RLIMIT_STACK].rlim_cur) / 4) {
			put_page(page);
			return NULL;
		}
	}

	return page;
}


static void virtio_blk_reset(VirtIODevice *vdev) { VirtIOBlock *s = VIRTIO_BLK(vdev); AioContext *ctx; VirtIOBlockReq *req; ctx = blk_get_aio_context(s->blk); aio_context_acquire(ctx); blk_drain(s->blk); /* We drop queued requests after blk_drain() because blk_drain() itself can * produce them. */ while (s->rq) { req = s->rq; s->rq = req->next; virtqueue_detach_element(req->vq, &req->elem, 0); virtio_blk_free_request(req); } if (s->dataplane) { virtio_blk_data_plane_stop(s->dataplane); } aio_context_release(ctx); blk_set_enable_write_cache(s->blk, s->original_wce); }


static const char * integer32_avp ( diam_ctx_t * c , diam_avp_t * a , tvbuff_t * tvb , diam_sub_dis_t * diam_sub_dis_inf _U_ ) {
 char * label = NULL ;
 proto_item * pi ;
 gint length = tvb_reported_length ( tvb ) ;
 if ( length == 4 ) {
 if ( c -> tree ) {
 pi = proto_tree_add_item ( c -> tree , a -> hf_value , tvb , 0 , length , ENC_BIG_ENDIAN ) ;
 label = ( char * ) wmem_alloc ( wmem_packet_scope ( ) , ITEM_LABEL_LENGTH + 1 ) ;
 proto_item_fill_label ( PITEM_FINFO ( pi ) , label ) ;
 label = strstr ( label , ": " ) + 2 ;
 }
 }
 else {
 pi = proto_tree_add_bytes_format ( c -> tree , hf_diameter_avp_data_wrong_length , tvb , 0 , length , NULL , "Error! Bad Integer32 Length" ) ;
 expert_add_info_format ( c -> pinfo , pi , & ei_diameter_avp_len , "Bad Integer32 Length (%u)" , length ) ;
 PROTO_ITEM_SET_GENERATED ( pi ) ;
 }
 return label ;
 }


static void get_time_value ( tvbuff_t * tvb , const gint start , const gint length , const guint encoding , nstime_t * time_stamp , const gboolean is_relative ) {
 guint32 tmpsecs ;
 guint64 todsecs ;
 if ( is_relative && ( encoding != ( ENC_TIME_TIMESPEC | ENC_BIG_ENDIAN ) ) && ( encoding != ( ENC_TIME_TIMESPEC | ENC_LITTLE_ENDIAN ) ) ) {
 return ;
 }
 switch ( encoding ) {
 case ENC_TIME_TIMESPEC | ENC_BIG_ENDIAN : time_stamp -> secs = ( time_t ) tvb_get_ntohl ( tvb , start ) ;
 if ( length == 8 ) time_stamp -> nsecs = tvb_get_ntohl ( tvb , start + 4 ) ;
 else time_stamp -> nsecs = 0 ;
 break ;
 case ENC_TIME_TIMESPEC | ENC_LITTLE_ENDIAN : time_stamp -> secs = ( time_t ) tvb_get_letohl ( tvb , start ) ;
 if ( length == 8 ) time_stamp -> nsecs = tvb_get_letohl ( tvb , start + 4 ) ;
 else time_stamp -> nsecs = 0 ;
 break ;
 case ENC_TIME_TOD | ENC_BIG_ENDIAN : # define TOD_BASETIME G_GUINT64_CONSTANT ( 2208988800 ) todsecs = tvb_get_ntoh64 ( tvb , start ) >> 12 ;
 time_stamp -> secs = ( time_t ) ( ( todsecs / 1000000 ) - TOD_BASETIME ) ;
 time_stamp -> nsecs = ( int ) ( ( todsecs % 1000000 ) * 1000 ) ;
 break ;
 case ENC_TIME_TOD | ENC_LITTLE_ENDIAN : todsecs = tvb_get_letoh64 ( tvb , start ) >> 12 ;
 time_stamp -> secs = ( time_t ) ( ( todsecs / 1000000 ) - TOD_BASETIME ) ;
 time_stamp -> nsecs = ( int ) ( ( todsecs % 1000000 ) * 1000 ) ;
 break ;
 case ENC_TIME_NTP | ENC_BIG_ENDIAN : # define NTP_BASETIME G_GUINT64_CONSTANT ( 2208988800 ) tmpsecs = tvb_get_ntohl ( tvb , start ) ;
 if ( tmpsecs ) time_stamp -> secs = ( time_t ) ( tmpsecs - ( guint32 ) NTP_BASETIME ) ;
 else time_stamp -> secs = tmpsecs ;
 if ( length == 8 ) {
 time_stamp -> nsecs = ( int ) ( 1000000 * ( tvb_get_ntohl ( tvb , start + 4 ) / 4294967296.0 ) ) ;
 time_stamp -> nsecs *= 1000 ;
 }
 else {
 time_stamp -> nsecs = 0 ;
 }
 break ;
 case ENC_TIME_NTP | ENC_LITTLE_ENDIAN : tmpsecs = tvb_get_letohl ( tvb , start ) ;
 if ( tmpsecs ) time_stamp -> secs = ( time_t ) ( tmpsecs - ( guint32 ) NTP_BASETIME ) ;
 else time_stamp -> secs = tmpsecs ;
 if ( length == 8 ) {
 time_stamp -> nsecs = ( int ) ( 1000000 * ( tvb_get_letohl ( tvb , start + 4 ) / 4294967296.0 ) ) ;
 time_stamp -> nsecs *= 1000 ;
 }
 else {
 time_stamp -> nsecs = 0 ;
 }
 break ;
 case ENC_TIME_NTP_BASE_ZERO | ENC_BIG_ENDIAN : # define NTP_BASETIME_ZERO G_GUINT64_CONSTANT ( 0 ) tmpsecs = tvb_get_ntohl ( tvb , start ) ;
 if ( tmpsecs ) time_stamp -> secs = ( time_t ) ( tmpsecs - ( guint32 ) NTP_BASETIME_ZERO ) ;
 else time_stamp -> secs = tmpsecs ;
 if ( length == 8 ) {
 time_stamp -> nsecs = ( int ) ( 1000000 * ( tvb_get_ntohl ( tvb , start + 4 ) / 4294967296.0 ) ) ;
 time_stamp -> nsecs *= 1000 ;
 }
 else {
 time_stamp -> nsecs = 0 ;
 }
 break ;
 case ENC_TIME_NTP_BASE_ZERO | ENC_LITTLE_ENDIAN : tmpsecs = tvb_get_letohl ( tvb , start ) ;
 if ( tmpsecs ) time_stamp -> secs = ( time_t ) ( tmpsecs - ( guint32 ) NTP_BASETIME_ZERO ) ;
 else time_stamp -> secs = tmpsecs ;
 time_stamp -> secs = ( time_t ) tvb_get_letohl ( tvb , start ) ;
 if ( length == 8 ) {
 time_stamp -> nsecs = ( int ) ( 1000000 * ( tvb_get_letohl ( tvb , start + 4 ) / 4294967296.0 ) ) ;
 time_stamp -> nsecs *= 1000 ;
 }
 else {
 time_stamp -> nsecs = 0 ;
 }
 break ;
 default : DISSECTOR_ASSERT_NOT_REACHED ( ) ;
 break ;
 }
 }


static int qemuMonitorJSONCheckError ( virJSONValuePtr cmd , virJSONValuePtr reply ) {
 if ( virJSONValueObjectHasKey ( reply , "error" ) ) {
 virJSONValuePtr error = virJSONValueObjectGet ( reply , "error" ) ;
 char * cmdstr = virJSONValueToString ( cmd ) ;
 char * replystr = virJSONValueToString ( reply ) ;
 VIR_DEBUG ( "unable to execute QEMU command %s: %s" , cmdstr , replystr ) ;
 if ( ! error ) qemuReportError ( VIR_ERR_INTERNAL_ERROR , _ ( "unable to execute QEMU command '%s'" ) , qemuMonitorJSONCommandName ( cmd ) ) ;
 else qemuReportError ( VIR_ERR_INTERNAL_ERROR , _ ( "unable to execute QEMU command '%s': %s" ) , qemuMonitorJSONCommandName ( cmd ) , qemuMonitorJSONStringifyError ( error ) ) ;
 VIR_FREE ( cmdstr ) ;
 VIR_FREE ( replystr ) ;
 return - 1 ;
 }
 else if ( ! virJSONValueObjectHasKey ( reply , "return" ) ) {
 char * cmdstr = virJSONValueToString ( cmd ) ;
 char * replystr = virJSONValueToString ( reply ) ;
 VIR_DEBUG ( "Neither 'return' nor 'error' is set in the JSON reply %s: %s" , cmdstr , replystr ) ;
 qemuReportError ( VIR_ERR_INTERNAL_ERROR , _ ( "unable to execute QEMU command '%s'" ) , qemuMonitorJSONCommandName ( cmd ) ) ;
 VIR_FREE ( cmdstr ) ;
 VIR_FREE ( replystr ) ;
 return - 1 ;
 }
 return 0 ;
 }


static void test_aio_external_client(void) { int i, j; for (i = 1; i < 3; i++) { EventNotifierTestData data = { .n = 0, .active = 10, .auto_set = true }; event_notifier_init(&data.e, false); aio_set_event_notifier(ctx, &data.e, true, event_ready_cb); event_notifier_set(&data.e); for (j = 0; j < i; j++) { aio_disable_external(ctx); } for (j = 0; j < i; j++) { assert(!aio_poll(ctx, false)); assert(event_notifier_test_and_clear(&data.e)); event_notifier_set(&data.e); aio_enable_external(ctx); } assert(aio_poll(ctx, false)); event_notifier_cleanup(&data.e); } }


static struct search_state * search_state_new ( void ) {
 struct search_state * state = ( struct search_state * ) malloc ( sizeof ( struct search_state ) ) ;
 if ( ! state ) return NULL ;
 memset ( state , 0 , sizeof ( struct search_state ) ) ;
 state -> refcount = 1 ;
 state -> ndots = 1 ;
 return state ;
 }


grub_ext2_iterate_dir (grub_fshelp_node_t dir,
		       grub_fshelp_iterate_dir_hook_t hook, void *hook_data)
{
  unsigned int fpos = 0;
  struct grub_fshelp_node *diro = (struct grub_fshelp_node *) dir;

  if (! diro->inode_read)
    {
      grub_ext2_read_inode (diro->data, diro->ino, &diro->inode);
      if (grub_errno)
	return 0;
    }

  /* Search the file.  */
  while (fpos < grub_le_to_cpu32 (diro->inode.size))
    {
      struct ext2_dirent dirent;

      grub_ext2_read_file (diro, 0, 0, fpos, sizeof (struct ext2_dirent),
			   (char *) &dirent);
      if (grub_errno)
	return 0;

      if (dirent.direntlen == 0)
        return 0;

      if (dirent.inode != 0 && dirent.namelen != 0)
	{
	  char filename[dirent.namelen + 1];
	  struct grub_fshelp_node *fdiro;
	  enum grub_fshelp_filetype type = GRUB_FSHELP_UNKNOWN;

	  grub_ext2_read_file (diro, 0, 0, fpos + sizeof (struct ext2_dirent),
			       dirent.namelen, filename);
	  if (grub_errno)
	    return 0;

	  fdiro = grub_malloc (sizeof (struct grub_fshelp_node));
	  if (! fdiro)
	    return 0;

	  fdiro->data = diro->data;
	  fdiro->ino = grub_le_to_cpu32 (dirent.inode);

	  filename[dirent.namelen] = '\0';

	  if (dirent.filetype != FILETYPE_UNKNOWN)
	    {
	      fdiro->inode_read = 0;

	      if (dirent.filetype == FILETYPE_DIRECTORY)
		type = GRUB_FSHELP_DIR;
	      else if (dirent.filetype == FILETYPE_SYMLINK)
		type = GRUB_FSHELP_SYMLINK;
	      else if (dirent.filetype == FILETYPE_REG)
		type = GRUB_FSHELP_REG;
	    }
	  else
	    {
	      /* The filetype can not be read from the dirent, read
		 the inode to get more information.  */
	      grub_ext2_read_inode (diro->data,
                                    grub_le_to_cpu32 (dirent.inode),
				    &fdiro->inode);
	      if (grub_errno)
		{
		  grub_free (fdiro);
		  return 0;
		}

	      fdiro->inode_read = 1;

	      if ((grub_le_to_cpu16 (fdiro->inode.mode)
		   & FILETYPE_INO_MASK) == FILETYPE_INO_DIRECTORY)
		type = GRUB_FSHELP_DIR;
	      else if ((grub_le_to_cpu16 (fdiro->inode.mode)
			& FILETYPE_INO_MASK) == FILETYPE_INO_SYMLINK)
		type = GRUB_FSHELP_SYMLINK;
	      else if ((grub_le_to_cpu16 (fdiro->inode.mode)
			& FILETYPE_INO_MASK) == FILETYPE_INO_REG)
		type = GRUB_FSHELP_REG;
	    }

	  if (hook (filename, type, fdiro, hook_data))
	    return 1;
	}

      fpos += grub_le_to_cpu16 (dirent.direntlen);
    }

  return 0;
}


static int local_mkdir(FsContext *fs_ctx, V9fsPath *dir_path, const char *name, FsCred *credp) { char *path; int err = -1; int serrno = 0; V9fsString fullname; char *buffer = NULL; v9fs_string_init(&fullname); v9fs_string_sprintf(&fullname, "%s/%s", dir_path->data, name); path = fullname.data; /* Determine the security model */ if (fs_ctx->export_flags & V9FS_SM_MAPPED) { buffer = rpath(fs_ctx, path); err = mkdir(buffer, SM_LOCAL_DIR_MODE_BITS); if (err == -1) { goto out; } credp->fc_mode = credp->fc_mode|S_IFDIR; err = local_set_xattr(buffer, credp); if (err == -1) { serrno = errno; goto err_end; } } else if (fs_ctx->export_flags & V9FS_SM_MAPPED_FILE) { buffer = rpath(fs_ctx, path); err = mkdir(buffer, SM_LOCAL_DIR_MODE_BITS); if (err == -1) { goto out; } credp->fc_mode = credp->fc_mode|S_IFDIR; err = local_set_mapped_file_attr(fs_ctx, path, credp); if (err == -1) { serrno = errno; goto err_end; } } else if ((fs_ctx->export_flags & V9FS_SM_PASSTHROUGH) || (fs_ctx->export_flags & V9FS_SM_NONE)) { buffer = rpath(fs_ctx, path); err = mkdir(buffer, credp->fc_mode); if (err == -1) { goto out; } err = local_post_create_passthrough(fs_ctx, path, credp); if (err == -1) { serrno = errno; goto err_end; } } goto out; err_end: remove(buffer); errno = serrno; out: g_free(buffer); v9fs_string_free(&fullname); return err; }


static void load_tc(QEMUFile *f, TCState *tc) { int i; /* Save active TC */ for(i = 0; i < 32; i++) qemu_get_betls(f, &tc->gpr[i]); qemu_get_betls(f, &tc->PC); for(i = 0; i < MIPS_DSP_ACC; i++) qemu_get_betls(f, &tc->HI[i]); for(i = 0; i < MIPS_DSP_ACC; i++) qemu_get_betls(f, &tc->LO[i]); for(i = 0; i < MIPS_DSP_ACC; i++) qemu_get_betls(f, &tc->ACX[i]); qemu_get_betls(f, &tc->DSPControl); qemu_get_sbe32s(f, &tc->CP0_TCStatus); qemu_get_sbe32s(f, &tc->CP0_TCBind); qemu_get_betls(f, &tc->CP0_TCHalt); qemu_get_betls(f, &tc->CP0_TCContext); qemu_get_betls(f, &tc->CP0_TCSchedule); qemu_get_betls(f, &tc->CP0_TCScheFBack); qemu_get_sbe32s(f, &tc->CP0_Debug_tcstatus); }


int dtls1_get_record(SSL *s)
	{
	int ssl_major,ssl_minor;
	int i,n;
	SSL3_RECORD *rr;
	unsigned char *p = NULL;
	unsigned short version;
	DTLS1_BITMAP *bitmap;
	unsigned int is_next_epoch;

	rr= &(s->s3->rrec);

	/* The epoch may have changed.  If so, process all the
	 * pending records.  This is a non-blocking operation. */
	dtls1_process_buffered_records(s);

	/* if we're renegotiating, then there may be buffered records */
	if (dtls1_get_processed_record(s))
		return 1;

	/* get something from the wire */
again:
	/* check if we have the header */
	if (	(s->rstate != SSL_ST_READ_BODY) ||
		(s->packet_length < DTLS1_RT_HEADER_LENGTH))
		{
		n=ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
		/* read timeout is handled by dtls1_read_bytes */
		if (n <= 0) return(n); /* error or non-blocking */

		/* this packet contained a partial record, dump it */
		if (s->packet_length != DTLS1_RT_HEADER_LENGTH)
			{
			s->packet_length = 0;
			goto again;
			}

		s->rstate=SSL_ST_READ_BODY;

		p=s->packet;

		if (s->msg_callback)
			s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);

		/* Pull apart the header into the DTLS1_RECORD */
		rr->type= *(p++);
		ssl_major= *(p++);
		ssl_minor= *(p++);
		version=(ssl_major<<8)|ssl_minor;

		/* sequence number is 64 bits, with top 2 bytes = epoch */
		n2s(p,rr->epoch);

		memcpy(&(s->s3->read_sequence[2]), p, 6);
		p+=6;

		n2s(p,rr->length);

		/* Lets check version */
		if (!s->first_packet)
			{
			if (version != s->version)
				{
				/* unexpected version, silently discard */
				rr->length = 0;
				s->packet_length = 0;
				goto again;
				}
			}

		if ((version & 0xff00) != (s->version & 0xff00))
			{
			/* wrong version, silently discard record */
			rr->length = 0;
			s->packet_length = 0;
			goto again;
			}

		if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
			{
			/* record too long, silently discard it */
			rr->length = 0;
			s->packet_length = 0;
			goto again;
			}

		/* now s->rstate == SSL_ST_READ_BODY */
		}

	/* s->rstate == SSL_ST_READ_BODY, get and decode the data */

	if (rr->length > s->packet_length-DTLS1_RT_HEADER_LENGTH)
		{
		/* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
		i=rr->length;
		n=ssl3_read_n(s,i,i,1);
		/* this packet contained a partial record, dump it */
		if ( n != i)
			{
			rr->length = 0;
			s->packet_length = 0;
			goto again;
			}

		/* now n == rr->length,
		 * and s->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */
		}
	s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */

	/* match epochs.  NULL means the packet is dropped on the floor */
	bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
	if ( bitmap == NULL)
		{
		rr->length = 0;
		s->packet_length = 0;  /* dump this record */
		goto again;   /* get another record */
		}

#ifndef OPENSSL_NO_SCTP
	/* Only do replay check if no SCTP bio */
	if (!BIO_dgram_is_sctp(SSL_get_rbio(s)))
  		{
#endif
		/* Check whether this is a repeat, or aged record.
		 * Don't check if we're listening and this message is
		 * a ClientHello. They can look as if they're replayed,
		 * since they arrive from different connections and
		 * would be dropped unnecessarily.
		 */
		if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE &&
		    s->packet_length > DTLS1_RT_HEADER_LENGTH &&
		    s->packet[DTLS1_RT_HEADER_LENGTH] == SSL3_MT_CLIENT_HELLO) &&
		    !dtls1_record_replay_check(s, bitmap))
			{
			rr->length = 0;
			s->packet_length=0; /* dump this record */
			goto again;     /* get another record */
			}
#ifndef OPENSSL_NO_SCTP
  		}
#endif

	/* just read a 0 length packet */
	if (rr->length == 0) goto again;

	/* If this record is from the next epoch (either HM or ALERT),
	 * and a handshake is currently in progress, buffer it since it
	 * cannot be processed at this time. However, do not buffer
	 * anything while listening.
	 */
	if (is_next_epoch)
		{
		if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen)
			{
			dtls1_buffer_record(s, &(s->d1->unprocessed_rcds), rr->seq_num);
			}
		rr->length = 0;
		s->packet_length = 0;
		goto again;
		}

	if (!dtls1_process_record(s))
		{
		rr->length = 0;
		s->packet_length = 0;  /* dump this record */
		goto again;   /* get another record */
		}

	return(1);

	}


_gcry_mpi_powm (gcry_mpi_t res,
                gcry_mpi_t base, gcry_mpi_t expo, gcry_mpi_t mod)
{
  /* Pointer to the limbs of the arguments, their size and signs. */
  mpi_ptr_t  rp, ep, mp, bp;
  mpi_size_t esize, msize, bsize, rsize;
  int               msign, bsign, rsign;
  /* Flags telling the secure allocation status of the arguments.  */
  int        esec,  msec,  bsec;
  /* Size of the result including space for temporary values.  */
  mpi_size_t size;
  /* Helper.  */
  int mod_shift_cnt;
  int negative_result;
  mpi_ptr_t mp_marker = NULL;
  mpi_ptr_t bp_marker = NULL;
  mpi_ptr_t ep_marker = NULL;
  mpi_ptr_t xp_marker = NULL;
  unsigned int mp_nlimbs = 0;
  unsigned int bp_nlimbs = 0;
  unsigned int ep_nlimbs = 0;
  unsigned int xp_nlimbs = 0;
  mpi_ptr_t precomp[SIZE_PRECOMP]; /* Pre-computed array: BASE^1, ^3, ^5, ... */
  mpi_size_t precomp_size[SIZE_PRECOMP];
  mpi_size_t W;
  mpi_ptr_t base_u;
  mpi_size_t base_u_size;
  mpi_size_t max_u_size;

  esize = expo->nlimbs;
  msize = mod->nlimbs;
  size = 2 * msize;
  msign = mod->sign;

  ep = expo->d;
  MPN_NORMALIZE(ep, esize);

  if (esize * BITS_PER_MPI_LIMB > 512)
    W = 5;
  else if (esize * BITS_PER_MPI_LIMB > 256)
    W = 4;
  else if (esize * BITS_PER_MPI_LIMB > 128)
    W = 3;
  else if (esize * BITS_PER_MPI_LIMB > 64)
    W = 2;
  else
    W = 1;

  esec = mpi_is_secure(expo);
  msec = mpi_is_secure(mod);
  bsec = mpi_is_secure(base);

  rp = res->d;

  if (!msize)
    _gcry_divide_by_zero();

  if (!esize)
    {
      /* Exponent is zero, result is 1 mod MOD, i.e., 1 or 0 depending
         on if MOD equals 1.  */
      res->nlimbs = (msize == 1 && mod->d[0] == 1) ? 0 : 1;
      if (res->nlimbs)
        {
          RESIZE_IF_NEEDED (res, 1);
          rp = res->d;
          rp[0] = 1;
        }
      res->sign = 0;
      goto leave;
    }

  /* Normalize MOD (i.e. make its most significant bit set) as
     required by mpn_divrem.  This will make the intermediate values
     in the calculation slightly larger, but the correct result is
     obtained after a final reduction using the original MOD value. */
  mp_nlimbs = msec? msize:0;
  mp = mp_marker = mpi_alloc_limb_space(msize, msec);
  count_leading_zeros (mod_shift_cnt, mod->d[msize-1]);
  if (mod_shift_cnt)
    _gcry_mpih_lshift (mp, mod->d, msize, mod_shift_cnt);
  else
    MPN_COPY( mp, mod->d, msize );

  bsize = base->nlimbs;
  bsign = base->sign;
  if (bsize > msize)
    {
      /* The base is larger than the module.  Reduce it.

         Allocate (BSIZE + 1) with space for remainder and quotient.
         (The quotient is (bsize - msize + 1) limbs.)  */
      bp_nlimbs = bsec ? (bsize + 1):0;
      bp = bp_marker = mpi_alloc_limb_space( bsize + 1, bsec );
      MPN_COPY ( bp, base->d, bsize );
      /* We don't care about the quotient, store it above the
       * remainder, at BP + MSIZE.  */
      _gcry_mpih_divrem( bp + msize, 0, bp, bsize, mp, msize );
      bsize = msize;
      /* Canonicalize the base, since we are going to multiply with it
         quite a few times.  */
      MPN_NORMALIZE( bp, bsize );
    }
  else
    bp = base->d;

  if (!bsize)
    {
      res->nlimbs = 0;
      res->sign = 0;
      goto leave;
    }

  /* Make BASE, EXPO not overlap with RES.  We don't need to check MOD
     because that has already been copied to the MP var.  */
  if ( rp == bp )
    {
      /* RES and BASE are identical.  Allocate temp. space for BASE.  */
      gcry_assert (!bp_marker);
      bp_nlimbs = bsec? bsize:0;
      bp = bp_marker = mpi_alloc_limb_space( bsize, bsec );
      MPN_COPY(bp, rp, bsize);
    }
  if ( rp == ep )
    {
      /* RES and EXPO are identical.  Allocate temp. space for EXPO.  */
      ep_nlimbs = esec? esize:0;
      ep = ep_marker = mpi_alloc_limb_space( esize, esec );
      MPN_COPY(ep, rp, esize);
    }

  /* Copy base to the result.  */
  if (res->alloced < size)
    {
      mpi_resize (res, size);
      rp = res->d;
    }

  /* Main processing.  */
  {
    mpi_size_t i, j, k;
    mpi_ptr_t xp;
    mpi_size_t xsize;
    int c;
    mpi_limb_t e;
    mpi_limb_t carry_limb;
    struct karatsuba_ctx karactx;
    mpi_ptr_t tp;

    xp_nlimbs = msec? (2 * (msize + 1)):0;
    xp = xp_marker = mpi_alloc_limb_space( 2 * (msize + 1), msec );

    memset( &karactx, 0, sizeof karactx );
    negative_result = (ep[0] & 1) && bsign;

    /* Precompute PRECOMP[], BASE^(2 * i + 1), BASE^1, ^3, ^5, ... */
    if (W > 1)                  /* X := BASE^2 */
      mul_mod (xp, &xsize, bp, bsize, bp, bsize, mp, msize, &karactx);
    base_u = precomp[0] = mpi_alloc_limb_space (bsize, esec);
    base_u_size = max_u_size = precomp_size[0] = bsize;
    MPN_COPY (precomp[0], bp, bsize);
    for (i = 1; i < (1 << (W - 1)); i++)
      {                         /* PRECOMP[i] = BASE^(2 * i + 1) */
        if (xsize >= base_u_size)
          mul_mod (rp, &rsize, xp, xsize, base_u, base_u_size,
                   mp, msize, &karactx);
        else
          mul_mod (rp, &rsize, base_u, base_u_size, xp, xsize,
                   mp, msize, &karactx);
        base_u = precomp[i] = mpi_alloc_limb_space (rsize, esec);
        base_u_size = precomp_size[i] = rsize;
        if (max_u_size < base_u_size)
          max_u_size = base_u_size;
        MPN_COPY (precomp[i], rp, rsize);
      }

    base_u = mpi_alloc_limb_space (max_u_size, esec);
    MPN_ZERO (base_u, max_u_size);

    i = esize - 1;

    /* Main loop.

       Make the result be pointed to alternately by XP and RP.  This
       helps us avoid block copying, which would otherwise be
       necessary with the overlap restrictions of
       _gcry_mpih_divmod. With 50% probability the result after this
       loop will be in the area originally pointed by RP (==RES->d),
       and with 50% probability in the area originally pointed to by XP. */
    rsign = 0;
    if (W == 1)
      {
        rsize = bsize;
      }
    else
      {
        rsize = msize;
        MPN_ZERO (rp, rsize);
      }
    MPN_COPY ( rp, bp, bsize );

    e = ep[i];
    count_leading_zeros (c, e);
    e = (e << c) << 1;
    c = BITS_PER_MPI_LIMB - 1 - c;

    j = 0;

    for (;;)
      if (e == 0)
        {
          j += c;
          if ( --i < 0 )
            break;

          e = ep[i];
          c = BITS_PER_MPI_LIMB;
        }
      else
        {
          int c0;
          mpi_limb_t e0;

          count_leading_zeros (c0, e);
          e = (e << c0);
          c -= c0;
          j += c0;

          e0 = (e >> (BITS_PER_MPI_LIMB - W));
          if (c >= W)
            c0 = 0;
          else
            {
              if ( --i < 0 )
                {
                  e0 = (e >> (BITS_PER_MPI_LIMB - c));
                  j += c - W;
                  goto last_step;
                }
              else
                {
                  c0 = c;
                  e = ep[i];
                  c = BITS_PER_MPI_LIMB;
                  e0 |= (e >> (BITS_PER_MPI_LIMB - (W - c0)));
                }
            }

          e = e << (W - c0);
          c -= (W - c0);

        last_step:
          count_trailing_zeros (c0, e0);
          e0 = (e0 >> c0) >> 1;

          /*
           *  base_u <= precomp[e0]
           *  base_u_size <= precomp_size[e0]
           */
          base_u_size = 0;
          for (k = 0; k < (1<< (W - 1)); k++)
            {
              struct gcry_mpi w, u;
              w.alloced = w.nlimbs = precomp_size[k];
              u.alloced = u.nlimbs = precomp_size[k];
              w.sign = u.sign = 0;
              w.flags = u.flags = 0;
              w.d = base_u;
              u.d = precomp[k];

              mpi_set_cond (&w, &u, k == e0);
              base_u_size |= ( precomp_size[k] & ((mpi_size_t)0 - (k == e0)) );
            }

          for (j += W - c0; j >= 0; j--)
            {
              mul_mod (xp, &xsize, rp, rsize,
                       j == 0 ? base_u : rp, j == 0 ? base_u_size : rsize,
                       mp, msize, &karactx);
              tp = rp; rp = xp; xp = tp;
              rsize = xsize;
            }

          j = c0;
          if ( i < 0 )
            break;
        }

    while (j--)
      {
        mul_mod (xp, &xsize, rp, rsize, rp, rsize, mp, msize, &karactx);
        tp = rp; rp = xp; xp = tp;
        rsize = xsize;
      }

    /* We shifted MOD, the modulo reduction argument, left
       MOD_SHIFT_CNT steps.  Adjust the result by reducing it with the
       original MOD.

       Also make sure the result is put in RES->d (where it already
       might be, see above).  */
    if ( mod_shift_cnt )
      {
        carry_limb = _gcry_mpih_lshift( res->d, rp, rsize, mod_shift_cnt);
        rp = res->d;
        if ( carry_limb )
          {
            rp[rsize] = carry_limb;
            rsize++;
          }
      }
    else if (res->d != rp)
      {
        MPN_COPY (res->d, rp, rsize);
        rp = res->d;
      }

    if ( rsize >= msize )
      {
        _gcry_mpih_divrem(rp + msize, 0, rp, rsize, mp, msize);
        rsize = msize;
      }

    /* Remove any leading zero words from the result.  */
    if ( mod_shift_cnt )
      _gcry_mpih_rshift( rp, rp, rsize, mod_shift_cnt);
    MPN_NORMALIZE (rp, rsize);

    _gcry_mpih_release_karatsuba_ctx (&karactx );
    for (i = 0; i < (1 << (W - 1)); i++)
      _gcry_mpi_free_limb_space( precomp[i], esec ? precomp_size[i] : 0 );
    _gcry_mpi_free_limb_space (base_u, esec ? max_u_size : 0);
  }

  /* Fixup for negative results.  */
  if ( negative_result && rsize )
    {
      if ( mod_shift_cnt )
        _gcry_mpih_rshift( mp, mp, msize, mod_shift_cnt);
      _gcry_mpih_sub( rp, mp, msize, rp, rsize);
      rsize = msize;
      rsign = msign;
      MPN_NORMALIZE(rp, rsize);
    }
  gcry_assert (res->d == rp);
  res->nlimbs = rsize;
  res->sign = rsign;

 leave:
  if (mp_marker)
    _gcry_mpi_free_limb_space( mp_marker, mp_nlimbs );
  if (bp_marker)
    _gcry_mpi_free_limb_space( bp_marker, bp_nlimbs );
  if (ep_marker)
    _gcry_mpi_free_limb_space( ep_marker, ep_nlimbs );
  if (xp_marker)
    _gcry_mpi_free_limb_space( xp_marker, xp_nlimbs );
}


void rdma_start_outgoing_migration(void *opaque, const char *host_port, Error **errp) { MigrationState *s = opaque; Error *local_err = NULL, **temp = &local_err; RDMAContext *rdma = qemu_rdma_data_init(host_port, &local_err); int ret = 0; if (rdma == NULL) { ERROR(temp, "Failed to initialize RDMA data structures! %d", ret); goto err; } ret = qemu_rdma_source_init(rdma, &local_err, s->enabled_capabilities[MIGRATION_CAPABILITY_RDMA_PIN_ALL]); if (ret) { goto err; } trace_rdma_start_outgoing_migration_after_rdma_source_init(); ret = qemu_rdma_connect(rdma, &local_err); if (ret) { goto err; } trace_rdma_start_outgoing_migration_after_rdma_connect(); s->to_dst_file = qemu_fopen_rdma(rdma, "wb"); migrate_fd_connect(s); return; err: error_propagate(errp, local_err); g_free(rdma); migrate_fd_error(s); }


void stats_config ( int item , const char * invalue ) {
 FILE * fp ;
 const char * value ;
 int len ;
 double old_drift ;
 # ifndef VMS const char temp_ext [ ] = ".TEMP" ;
 # else const char temp_ext [ ] = "-TEMP" ;
 # endif # ifdef SYS_WINNT char newvalue [ MAX_PATH ] , parameter [ MAX_PATH ] ;
 if ( ! ExpandEnvironmentStrings ( invalue , newvalue , MAX_PATH ) ) {
 switch ( item ) {
 case STATS_FREQ_FILE : strncpy ( parameter , "STATS_FREQ_FILE" , sizeof ( parameter ) ) ;
 break ;
 case STATS_LEAP_FILE : strncpy ( parameter , "STATS_LEAP_FILE" , sizeof ( parameter ) ) ;
 break ;
 case STATS_STATSDIR : strncpy ( parameter , "STATS_STATSDIR" , sizeof ( parameter ) ) ;
 break ;
 case STATS_PID_FILE : strncpy ( parameter , "STATS_PID_FILE" , sizeof ( parameter ) ) ;
 break ;
 default : strncpy ( parameter , "UNKNOWN" , sizeof ( parameter ) ) ;
 break ;
 }
 value = invalue ;
 msyslog ( LOG_ERR , "ExpandEnvironmentStrings(%s) failed: %m\n" , parameter ) ;
 }
 else {
 value = newvalue ;
 }
 # else value = invalue ;
 # endif switch ( item ) {
 case STATS_FREQ_FILE : if ( ! value || ( len = strlen ( value ) ) == 0 ) break ;
 stats_drift_file = erealloc ( stats_drift_file , len + 1 ) ;
 stats_temp_file = erealloc ( stats_temp_file , len + sizeof ( ".TEMP" ) ) ;
 memcpy ( stats_drift_file , value , ( size_t ) ( len + 1 ) ) ;
 memcpy ( stats_temp_file , value , ( size_t ) len ) ;
 memcpy ( stats_temp_file + len , temp_ext , sizeof ( temp_ext ) ) ;
 if ( ( fp = fopen ( stats_drift_file , "r" ) ) == NULL ) break ;
 if ( fscanf ( fp , "%lf" , & old_drift ) != 1 ) {
 msyslog ( LOG_ERR , "format error frequency file %s" , stats_drift_file ) ;
 fclose ( fp ) ;
 break ;
 }
 fclose ( fp ) ;
 loop_config ( LOOP_FREQ , old_drift ) ;
 prev_drift_comp = drift_comp ;
 break ;
 case STATS_STATSDIR : if ( strlen ( value ) >= sizeof ( statsdir ) ) {
 msyslog ( LOG_ERR , "statsdir too long (>%d, sigh)" , ( int ) sizeof ( statsdir ) - 1 ) ;
 }
 else {
 l_fp now ;
 int add_dir_sep ;
 int value_l = strlen ( value ) ;
 if ( value_l == 0 ) add_dir_sep = 0 ;
 else add_dir_sep = ( DIR_SEP != value [ value_l - 1 ] ) ;
 if ( add_dir_sep ) snprintf ( statsdir , sizeof ( statsdir ) , "%s%c" , value , DIR_SEP ) ;
 else snprintf ( statsdir , sizeof ( statsdir ) , "%s" , value ) ;
 get_systime ( & now ) ;
 if ( peerstats . prefix == & statsdir [ 0 ] && peerstats . fp != NULL ) {
 fclose ( peerstats . fp ) ;
 peerstats . fp = NULL ;
 filegen_setup ( & peerstats , now . l_ui ) ;
 }
 if ( loopstats . prefix == & statsdir [ 0 ] && loopstats . fp != NULL ) {
 fclose ( loopstats . fp ) ;
 loopstats . fp = NULL ;
 filegen_setup ( & loopstats , now . l_ui ) ;
 }
 if ( clockstats . prefix == & statsdir [ 0 ] && clockstats . fp != NULL ) {
 fclose ( clockstats . fp ) ;
 clockstats . fp = NULL ;
 filegen_setup ( & clockstats , now . l_ui ) ;
 }
 if ( rawstats . prefix == & statsdir [ 0 ] && rawstats . fp != NULL ) {
 fclose ( rawstats . fp ) ;
 rawstats . fp = NULL ;
 filegen_setup ( & rawstats , now . l_ui ) ;
 }
 if ( sysstats . prefix == & statsdir [ 0 ] && sysstats . fp != NULL ) {
 fclose ( sysstats . fp ) ;
 sysstats . fp = NULL ;
 filegen_setup ( & sysstats , now . l_ui ) ;
 }
 if ( protostats . prefix == & statsdir [ 0 ] && protostats . fp != NULL ) {
 fclose ( protostats . fp ) ;
 protostats . fp = NULL ;
 filegen_setup ( & protostats , now . l_ui ) ;
 }
 # ifdef AUTOKEY if ( cryptostats . prefix == & statsdir [ 0 ] && cryptostats . fp != NULL ) {
 fclose ( cryptostats . fp ) ;
 cryptostats . fp = NULL ;
 filegen_setup ( & cryptostats , now . l_ui ) ;
 }
 # endif # ifdef DEBUG_TIMING if ( timingstats . prefix == & statsdir [ 0 ] && timingstats . fp != NULL ) {
 fclose ( timingstats . fp ) ;
 timingstats . fp = NULL ;
 filegen_setup ( & timingstats , now . l_ui ) ;
 }
 # endif }
 break ;
 case STATS_PID_FILE : if ( ( fp = fopen ( value , "w" ) ) == NULL ) {
 msyslog ( LOG_ERR , "pid file %s: %m" , value ) ;
 break ;
 }
 fprintf ( fp , "%d" , ( int ) getpid ( ) ) ;
 fclose ( fp ) ;
 ;
 break ;
 case STATS_LEAP_FILE : if ( ( fp = fopen ( value , "r" ) ) == NULL ) {
 msyslog ( LOG_ERR , "leapseconds file %s: %m" , value ) ;
 break ;
 }
 if ( leap_file ( fp ) < 0 ) msyslog ( LOG_ERR , "format error leapseconds file %s" , value ) ;
 else mprintf_event ( EVNT_TAI , NULL , "%d leap %s expire %s" , leap_tai , fstostr ( leap_sec ) , fstostr ( leap_expire ) ) ;
 fclose ( fp ) ;
 break ;
 default : break ;
 }
 }


void dissect_coap_payload ( tvbuff_t * tvb , packet_info * pinfo , proto_tree * coap_tree , proto_tree * parent_tree , gint offset , gint offset_end , guint8 code_class , coap_info * coinfo , coap_common_dissect_t * dissect_hf , gboolean oscore ) {
 proto_tree * payload_tree ;
 proto_item * payload_item , * length_item ;
 tvbuff_t * payload_tvb ;
 guint payload_length = offset_end - offset ;
 const char * coap_ctype_str_dis ;
 char str_payload [ 80 ] ;
 if ( coinfo -> ctype_value == DEFAULT_COAP_CTYPE_VALUE ) {
 if ( ( code_class >= 4 ) && ( code_class <= 5 ) ) {
 coinfo -> ctype_str = "text/plain;
 charset=utf-8" ;
 coap_ctype_str_dis = "text/plain" ;
 }
 else {
 coinfo -> ctype_str = "application/octet-stream" ;
 coap_ctype_str_dis = coinfo -> ctype_str ;
 }
 }
 else if ( coinfo -> ctype_value == 0 ) {
 coap_ctype_str_dis = "text/plain" ;
 }
 else {
 coap_ctype_str_dis = coinfo -> ctype_str ;
 }
 g_snprintf ( str_payload , sizeof ( str_payload ) , "Payload Content-Format: %s%s, Length: %u" , coinfo -> ctype_str , coinfo -> ctype_value == DEFAULT_COAP_CTYPE_VALUE ? " (no Content-Format)" : "" , payload_length ) ;
 payload_item = proto_tree_add_string ( coap_tree , dissect_hf -> hf . payload , tvb , offset , payload_length , str_payload ) ;
 payload_tree = proto_item_add_subtree ( payload_item , dissect_hf -> ett . payload ) ;
 proto_tree_add_string ( payload_tree , dissect_hf -> hf . payload_desc , tvb , offset , 0 , coinfo -> ctype_str ) ;
 length_item = proto_tree_add_uint ( payload_tree , dissect_hf -> hf . payload_length , tvb , offset , 0 , payload_length ) ;
 PROTO_ITEM_SET_GENERATED ( length_item ) ;
 payload_tvb = tvb_new_subset_length ( tvb , offset , payload_length ) ;
 dissector_try_string ( media_type_dissector_table , coap_ctype_str_dis , payload_tvb , pinfo , parent_tree , NULL ) ;
 if ( coinfo -> object_security && ! oscore ) {
 proto_item_set_text ( payload_item , "Encrypted OSCORE Data" ) ;
 call_dissector_with_data ( oscore_handle , payload_tvb , pinfo , parent_tree , coinfo -> oscore_info ) ;
 }
 }


int av_crc_init(AVCRC *ctx, int le, int bits, uint32_t poly, int ctx_size){ int i, j; uint32_t c; if (bits < 8 || bits > 32 || poly >= (1LL<<bits)) return -1; if (ctx_size != sizeof(AVCRC)*257 && ctx_size != sizeof(AVCRC)*1024) return -1; for (i = 0; i < 256; i++) { if (le) { for (c = i, j = 0; j < 8; j++) c = (c>>1)^(poly & (-(c&1))); ctx[i] = c; } else { for (c = i << 24, j = 0; j < 8; j++) c = (c<<1) ^ ((poly<<(32-bits)) & (((int32_t)c)>>31) ); ctx[i] = av_bswap32(c); } } ctx[256]=1; #if !CONFIG_SMALL if(ctx_size >= sizeof(AVCRC)*1024) for (i = 0; i < 256; i++) for(j=0; j<3; j++) ctx[256*(j+1) + i]= (ctx[256*j + i]>>8) ^ ctx[ ctx[256*j + i]&0xFF ]; #endif return 0; }


dtls1_process_record(SSL *s)
{
	int i,al;
	int enc_err;
	SSL_SESSION *sess;
	SSL3_RECORD *rr;
	unsigned int mac_size;
	unsigned char md[EVP_MAX_MD_SIZE];

	rr= &(s->s3->rrec);
	sess = s->session;

	/* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
	 * and we have that many bytes in s->packet
	 */
	rr->input= &(s->packet[DTLS1_RT_HEADER_LENGTH]);

	/* ok, we can now read from 's->packet' data into 'rr'
	 * rr->input points at rr->length bytes, which
	 * need to be copied into rr->data by either
	 * the decryption or by the decompression
	 * When the data is 'copied' into the rr->data buffer,
	 * rr->input will be pointed at the new buffer */

	/* We now have - encrypted [ MAC [ compressed [ plain ] ] ]
	 * rr->length bytes of encrypted compressed stuff. */

	/* check is not needed I believe */
	if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
		{
		al=SSL_AD_RECORD_OVERFLOW;
		SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
		goto f_err;
		}

	/* decrypt in place in 'rr->input' */
	rr->data=rr->input;
	rr->orig_len=rr->length;

	enc_err = s->method->ssl3_enc->enc(s,0);
	/* enc_err is:
	 *    0: (in non-constant time) if the record is publically invalid.
	 *    1: if the padding is valid
	 *    -1: if the padding is invalid */
	if (enc_err == 0)
		{
		/* For DTLS we simply ignore bad packets. */
		rr->length = 0;
		s->packet_length = 0;
		goto err;
		}

#ifdef TLS_DEBUG
printf("dec %d\n",rr->length);
{ unsigned int z; for (z=0; z<rr->length; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); }
printf("\n");
#endif

	/* r->length is now the compressed data plus mac */
	if ((sess != NULL) &&
	    (s->enc_read_ctx != NULL) &&
	    (EVP_MD_CTX_md(s->read_hash) != NULL))
		{
		/* s->read_hash != NULL => mac_size != -1 */
		unsigned char *mac = NULL;
		unsigned char mac_tmp[EVP_MAX_MD_SIZE];
		mac_size=EVP_MD_CTX_size(s->read_hash);
		OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);

		/* orig_len is the length of the record before any padding was
		 * removed. This is public information, as is the MAC in use,
		 * therefore we can safely process the record in a different
		 * amount of time if it's too short to possibly contain a MAC.
		 */
		if (rr->orig_len < mac_size ||
		    /* CBC records must have a padding length byte too. */
		    (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
		     rr->orig_len < mac_size+1))
			{
			al=SSL_AD_DECODE_ERROR;
			SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_LENGTH_TOO_SHORT);
			goto f_err;
			}

		if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE)
			{
			/* We update the length so that the TLS header bytes
			 * can be constructed correctly but we need to extract
			 * the MAC in constant time from within the record,
			 * without leaking the contents of the padding bytes.
			 * */
			mac = mac_tmp;
			ssl3_cbc_copy_mac(mac_tmp, rr, mac_size);
			rr->length -= mac_size;
			}
		else
			{
			/* In this case there's no padding, so |rec->orig_len|
			 * equals |rec->length| and we checked that there's
			 * enough bytes for |mac_size| above. */
			rr->length -= mac_size;
			mac = &rr->data[rr->length];
			}

		i=s->method->ssl3_enc->mac(s,md,0 /* not send */);
		if (i < 0 || mac == NULL || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
			enc_err = -1;
		if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+mac_size)
			enc_err = -1;
		}

	if (enc_err < 0)
		{
		/* decryption failed, silently discard message */
		rr->length = 0;
		s->packet_length = 0;
		goto err;
		}

	/* r->length is now just compressed */
	if (s->expand != NULL)
		{
		if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH)
			{
			al=SSL_AD_RECORD_OVERFLOW;
			SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG);
			goto f_err;
			}
		if (!ssl3_do_uncompress(s))
			{
			al=SSL_AD_DECOMPRESSION_FAILURE;
			SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_BAD_DECOMPRESSION);
			goto f_err;
			}
		}

	if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH)
		{
		al=SSL_AD_RECORD_OVERFLOW;
		SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_DATA_LENGTH_TOO_LONG);
		goto f_err;
		}

	rr->off=0;
	/*-
	 * So at this point the following is true
	 * ssl->s3->rrec.type 	is the type of record
	 * ssl->s3->rrec.length	== number of bytes in record
	 * ssl->s3->rrec.off	== offset to first valid byte
	 * ssl->s3->rrec.data	== where to take bytes from, increment
	 *			   after use :-).
	 */

	/* we have pulled in a full packet so zero things */
	s->packet_length=0;
	dtls1_record_bitmap_update(s, &(s->d1->bitmap));/* Mark receipt of record. */
	return(1);

f_err:
	ssl3_send_alert(s,SSL3_AL_FATAL,al);
err:
	return(0);
}


uint16_t acpi_pm1_evt_get_sts(ACPIREGS *ar, int64_t overflow_time) { int64_t d = acpi_pm_tmr_get_clock(); if (d >= overflow_time) { ar->pm1.evt.sts |= ACPI_BITMASK_TIMER_STATUS; } return ar->pm1.evt.sts; }


ImagingPcdDecode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
{
    int x;
    int chunk;
    UINT8* out;
    UINT8* ptr;

    ptr = buf;

    chunk = 3 * state->xsize;

    for (;;) {

	/* We need data for two full lines before we can do anything */
	if (bytes < chunk)
	    return ptr - buf;

	/* Unpack first line */
	out = state->buffer;
	for (x = 0; x < state->xsize; x++) {
	    out[0] = ptr[x];
	    out[1] = ptr[(x+4*state->xsize)/2];
	    out[2] = ptr[(x+5*state->xsize)/2];
	    out += 4;
	}

	state->shuffle((UINT8*) im->image[state->y],
		       state->buffer, state->xsize);

	if (++state->y >= state->ysize)
	    return -1; /* This can hardly happen */

	/* Unpack second line */
	out = state->buffer;
	for (x = 0; x < state->xsize; x++) {
	    out[0] = ptr[x+state->xsize];
	    out[1] = ptr[(x+4*state->xsize)/2];
	    out[2] = ptr[(x+5*state->xsize)/2];
	    out += 4;
	}

	state->shuffle((UINT8*) im->image[state->y],
		       state->buffer, state->xsize);

	if (++state->y >= state->ysize)
	    return -1;

	ptr += chunk;
	bytes -= chunk;

    }
}


static void ohci_async_complete_packet ( USBPort * port , USBPacket * packet ) {
 OHCIState * ohci = container_of ( packet , OHCIState , usb_packet ) ;
 trace_usb_ohci_async_complete ( ) ;
 ohci -> async_complete = true ;
 ohci_process_lists ( ohci , 1 ) ;
 }


void IGDstartelt(void * d, const char * name, int l)
{
	struct IGDdatas * datas = (struct IGDdatas *)d;
	memcpy( datas->cureltname, name, l);
	datas->cureltname[l] = '\0';
	datas->level++;
	if( (l==7) && !memcmp(name, "service", l) ) {
		datas->tmp.controlurl[0] = '\0';
		datas->tmp.eventsuburl[0] = '\0';
		datas->tmp.scpdurl[0] = '\0';
		datas->tmp.servicetype[0] = '\0';
	}
}


static void SRP_user_pwd_set_gN ( SRP_user_pwd * vinfo , const BIGNUM * g , const BIGNUM * N ) {
 vinfo -> N = N ;
 vinfo -> g = g ;
 }


void processRequest(struct reqelem * req)
{
	ssize_t n;
	unsigned int l, m;
	unsigned char buf[2048];
	const unsigned char * p;
	int type;
	struct device * d = devlist;
	unsigned char rbuf[4096];
	unsigned char * rp = rbuf+1;
	unsigned char nrep = 0;
	time_t t;
	struct service * newserv = NULL;
	struct service * serv;

	n = read(req->socket, buf, sizeof(buf));
	if(n<0) {
		if(errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)
			return;	/* try again later */
		syslog(LOG_ERR, "(s=%d) processRequest(): read(): %m", req->socket);
		goto error;
	}
	if(n==0) {
		syslog(LOG_INFO, "(s=%d) request connection closed", req->socket);
		goto error;
	}
	t = time(NULL);
	type = buf[0];
	p = buf + 1;
	DECODELENGTH_CHECKLIMIT(l, p, buf + n);
	if(p+l > buf+n) {
		syslog(LOG_WARNING, "bad request (length encoding)");
		goto error;
	}
	if(l == 0 && type != 3) {
		syslog(LOG_WARNING, "bad request (length=0)");
		goto error;
	}
	syslog(LOG_INFO, "(s=%d) request type=%d str='%.*s'",
	       req->socket, type, l, p);
	switch(type) {
	case 1:	/* request by type */
	case 2:	/* request by USN (unique id) */
	case 3:	/* everything */
		while(d && (nrep < 255)) {
			if(d->t < t) {
				syslog(LOG_INFO, "outdated device");
			} else {
				/* test if we can put more responses in the buffer */
				if(d->headers[HEADER_LOCATION].l + d->headers[HEADER_NT].l
				  + d->headers[HEADER_USN].l + 6
				  + (rp - rbuf) >= (int)sizeof(rbuf))
					break;
				if( (type==1 && 0==memcmp(d->headers[HEADER_NT].p, p, l))
				  ||(type==2 && 0==memcmp(d->headers[HEADER_USN].p, p, l))
				  ||(type==3) ) {
					/* response :
					 * 1 - Location
					 * 2 - NT (device/service type)
					 * 3 - usn */
					m = d->headers[HEADER_LOCATION].l;
					CODELENGTH(m, rp);
					memcpy(rp, d->headers[HEADER_LOCATION].p, d->headers[HEADER_LOCATION].l);
					rp += d->headers[HEADER_LOCATION].l;
					m = d->headers[HEADER_NT].l;
					CODELENGTH(m, rp);
					memcpy(rp, d->headers[HEADER_NT].p, d->headers[HEADER_NT].l);
					rp += d->headers[HEADER_NT].l;
					m = d->headers[HEADER_USN].l;
					CODELENGTH(m, rp);
					memcpy(rp, d->headers[HEADER_USN].p, d->headers[HEADER_USN].l);
					rp += d->headers[HEADER_USN].l;
					nrep++;
				}
			}
			d = d->next;
		}
		/* Also look in service list */
		for(serv = servicelisthead.lh_first;
		    serv && (nrep < 255);
		    serv = serv->entries.le_next) {
			/* test if we can put more responses in the buffer */
			if(strlen(serv->location) + strlen(serv->st)
			  + strlen(serv->usn) + 6 + (rp - rbuf) >= sizeof(rbuf))
			  	break;
			if( (type==1 && 0==strncmp(serv->st, (const char *)p, l))
			  ||(type==2 && 0==strncmp(serv->usn, (const char *)p, l))
			  ||(type==3) ) {
				/* response :
				 * 1 - Location
				 * 2 - NT (device/service type)
				 * 3 - usn */
				m = strlen(serv->location);
				CODELENGTH(m, rp);
				memcpy(rp, serv->location, m);
				rp += m;
				m = strlen(serv->st);
				CODELENGTH(m, rp);
				memcpy(rp, serv->st, m);
				rp += m;
				m = strlen(serv->usn);
				CODELENGTH(m, rp);
				memcpy(rp, serv->usn, m);
				rp += m;
				nrep++;
			}
		}
		rbuf[0] = nrep;
		syslog(LOG_DEBUG, "(s=%d) response : %d device%s",
		       req->socket, nrep, (nrep > 1) ? "s" : "");
		if(write(req->socket, rbuf, rp - rbuf) < 0) {
			syslog(LOG_ERR, "(s=%d) write: %m", req->socket);
			goto error;
		}
		break;
	case 4:	/* submit service */
		newserv = malloc(sizeof(struct service));
		if(!newserv) {
			syslog(LOG_ERR, "cannot allocate memory");
			goto error;
		}
		memset(newserv, 0, sizeof(struct service));	/* set pointers to NULL */
		if(containsForbiddenChars(p, l)) {
			syslog(LOG_ERR, "bad request (st contains forbidden chars)");
			goto error;
		}
		newserv->st = malloc(l + 1);
		if(!newserv->st) {
			syslog(LOG_ERR, "cannot allocate memory");
			goto error;
		}
		memcpy(newserv->st, p, l);
		newserv->st[l] = '\0';
		p += l;
		if(p >= buf + n) {
			syslog(LOG_WARNING, "bad request (missing usn)");
			goto error;
		}
		DECODELENGTH_CHECKLIMIT(l, p, buf + n);
		if(p+l > buf+n) {
			syslog(LOG_WARNING, "bad request (length encoding)");
			goto error;
		}
		if(containsForbiddenChars(p, l)) {
			syslog(LOG_ERR, "bad request (usn contains forbidden chars)");
			goto error;
		}
		syslog(LOG_INFO, "usn='%.*s'", l, p);
		newserv->usn = malloc(l + 1);
		if(!newserv->usn) {
			syslog(LOG_ERR, "cannot allocate memory");
			goto error;
		}
		memcpy(newserv->usn, p, l);
		newserv->usn[l] = '\0';
		p += l;
		DECODELENGTH_CHECKLIMIT(l, p, buf + n);
		if(p+l > buf+n) {
			syslog(LOG_WARNING, "bad request (length encoding)");
			goto error;
		}
		if(containsForbiddenChars(p, l)) {
			syslog(LOG_ERR, "bad request (server contains forbidden chars)");
			goto error;
		}
		syslog(LOG_INFO, "server='%.*s'", l, p);
		newserv->server = malloc(l + 1);
		if(!newserv->server) {
			syslog(LOG_ERR, "cannot allocate memory");
			goto error;
		}
		memcpy(newserv->server, p, l);
		newserv->server[l] = '\0';
		p += l;
		DECODELENGTH_CHECKLIMIT(l, p, buf + n);
		if(p+l > buf+n) {
			syslog(LOG_WARNING, "bad request (length encoding)");
			goto error;
		}
		if(containsForbiddenChars(p, l)) {
			syslog(LOG_ERR, "bad request (location contains forbidden chars)");
			goto error;
		}
		syslog(LOG_INFO, "location='%.*s'", l, p);
		newserv->location = malloc(l + 1);
		if(!newserv->location) {
			syslog(LOG_ERR, "cannot allocate memory");
			goto error;
		}
		memcpy(newserv->location, p, l);
		newserv->location[l] = '\0';
		/* look in service list for duplicate */
		for(serv = servicelisthead.lh_first;
		    serv;
		    serv = serv->entries.le_next) {
			if(0 == strcmp(newserv->usn, serv->usn)
			  && 0 == strcmp(newserv->st, serv->st)) {
				syslog(LOG_INFO, "Service allready in the list. Updating...");
				free(newserv->st);
				free(newserv->usn);
				free(serv->server);
				serv->server = newserv->server;
				free(serv->location);
				serv->location = newserv->location;
				free(newserv);
				newserv = NULL;
				return;
			}
		}
		/* Inserting new service */
		LIST_INSERT_HEAD(&servicelisthead, newserv, entries);
		newserv = NULL;
		/*rbuf[0] = '\0';
		if(write(req->socket, rbuf, 1) < 0)
			syslog(LOG_ERR, "(s=%d) write: %m", req->socket);
		*/
		break;
	default:
		syslog(LOG_WARNING, "Unknown request type %d", type);
		rbuf[0] = '\0';
		if(write(req->socket, rbuf, 1) < 0) {
			syslog(LOG_ERR, "(s=%d) write: %m", req->socket);
			goto error;
		}
	}
	return;
error:
	if(newserv) {
		free(newserv->st);
		free(newserv->usn);
		free(newserv->server);
		free(newserv->location);
		free(newserv);
		newserv = NULL;
	}
	close(req->socket);
	req->socket = -1;
	return;
}


static void lsi_reg_writeb(LSIState *s, int offset, uint8_t val) { #define CASE_SET_REG24(name, addr) \ case addr : s->name &= 0xffffff00; s->name |= val; break; \ case addr + 1: s->name &= 0xffff00ff; s->name |= val << 8; break; \ case addr + 2: s->name &= 0xff00ffff; s->name |= val << 16; break; #define CASE_SET_REG32(name, addr) \ case addr : s->name &= 0xffffff00; s->name |= val; break; \ case addr + 1: s->name &= 0xffff00ff; s->name |= val << 8; break; \ case addr + 2: s->name &= 0xff00ffff; s->name |= val << 16; break; \ case addr + 3: s->name &= 0x00ffffff; s->name |= val << 24; break; #ifdef DEBUG_LSI_REG DPRINTF("Write reg %x = %02x\n", offset, val); #endif switch (offset) { case 0x00: /* SCNTL0 */ s->scntl0 = val; if (val & LSI_SCNTL0_START) { BADF("Start sequence not implemented\n"); } break; case 0x01: /* SCNTL1 */ s->scntl1 = val & ~LSI_SCNTL1_SST; if (val & LSI_SCNTL1_IARB) { BADF("Immediate Arbritration not implemented\n"); } if (val & LSI_SCNTL1_RST) { if (!(s->sstat0 & LSI_SSTAT0_RST)) { BusChild *kid; QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) { DeviceState *dev = kid->child; device_reset(dev); } s->sstat0 |= LSI_SSTAT0_RST; lsi_script_scsi_interrupt(s, LSI_SIST0_RST, 0); } } else { s->sstat0 &= ~LSI_SSTAT0_RST; } break; case 0x02: /* SCNTL2 */ val &= ~(LSI_SCNTL2_WSR | LSI_SCNTL2_WSS); s->scntl2 = val; break; case 0x03: /* SCNTL3 */ s->scntl3 = val; break; case 0x04: /* SCID */ s->scid = val; break; case 0x05: /* SXFER */ s->sxfer = val; break; case 0x06: /* SDID */ if ((val & 0xf) != (s->ssid & 0xf)) BADF("Destination ID does not match SSID\n"); s->sdid = val & 0xf; break; case 0x07: /* GPREG0 */ break; case 0x08: /* SFBR */ /* The CPU is not allowed to write to this register. However the SCRIPTS register move instructions are. */ s->sfbr = val; break; case 0x0a: case 0x0b: /* Openserver writes to these readonly registers on startup */ return; case 0x0c: case 0x0d: case 0x0e: case 0x0f: /* Linux writes to these readonly registers on startup. */ return; CASE_SET_REG32(dsa, 0x10) case 0x14: /* ISTAT0 */ s->istat0 = (s->istat0 & 0x0f) | (val & 0xf0); if (val & LSI_ISTAT0_ABRT) { lsi_script_dma_interrupt(s, LSI_DSTAT_ABRT); } if (val & LSI_ISTAT0_INTF) { s->istat0 &= ~LSI_ISTAT0_INTF; lsi_update_irq(s); } if (s->waiting == 1 && val & LSI_ISTAT0_SIGP) { DPRINTF("Woken by SIGP\n"); s->waiting = 0; s->dsp = s->dnad; lsi_execute_script(s); } if (val & LSI_ISTAT0_SRST) { lsi_soft_reset(s); } break; case 0x16: /* MBOX0 */ s->mbox0 = val; break; case 0x17: /* MBOX1 */ s->mbox1 = val; break; case 0x1a: /* CTEST2 */ s->ctest2 = val & LSI_CTEST2_PCICIE; break; case 0x1b: /* CTEST3 */ s->ctest3 = val & 0x0f; break; CASE_SET_REG32(temp, 0x1c) case 0x21: /* CTEST4 */ if (val & 7) { BADF("Unimplemented CTEST4-FBL 0x%x\n", val); } s->ctest4 = val; break; case 0x22: /* CTEST5 */ if (val & (LSI_CTEST5_ADCK | LSI_CTEST5_BBCK)) { BADF("CTEST5 DMA increment not implemented\n"); } s->ctest5 = val; break; CASE_SET_REG24(dbc, 0x24) CASE_SET_REG32(dnad, 0x28) case 0x2c: /* DSP[0:7] */ s->dsp &= 0xffffff00; s->dsp |= val; break; case 0x2d: /* DSP[8:15] */ s->dsp &= 0xffff00ff; s->dsp |= val << 8; break; case 0x2e: /* DSP[16:23] */ s->dsp &= 0xff00ffff; s->dsp |= val << 16; break; case 0x2f: /* DSP[24:31] */ s->dsp &= 0x00ffffff; s->dsp |= val << 24; if ((s->dmode & LSI_DMODE_MAN) == 0 && (s->istat1 & LSI_ISTAT1_SRUN) == 0) lsi_execute_script(s); break; CASE_SET_REG32(dsps, 0x30) CASE_SET_REG32(scratch[0], 0x34) case 0x38: /* DMODE */ if (val & (LSI_DMODE_SIOM | LSI_DMODE_DIOM)) { BADF("IO mappings not implemented\n"); } s->dmode = val; break; case 0x39: /* DIEN */ s->dien = val; lsi_update_irq(s); break; case 0x3a: /* SBR */ s->sbr = val; break; case 0x3b: /* DCNTL */ s->dcntl = val & ~(LSI_DCNTL_PFF | LSI_DCNTL_STD); if ((val & LSI_DCNTL_STD) && (s->istat1 & LSI_ISTAT1_SRUN) == 0) lsi_execute_script(s); break; case 0x40: /* SIEN0 */ s->sien0 = val; lsi_update_irq(s); break; case 0x41: /* SIEN1 */ s->sien1 = val; lsi_update_irq(s); break; case 0x47: /* GPCNTL0 */ break; case 0x48: /* STIME0 */ s->stime0 = val; break; case 0x49: /* STIME1 */ if (val & 0xf) { DPRINTF("General purpose timer not implemented\n"); /* ??? Raising the interrupt immediately seems to be sufficient to keep the FreeBSD driver happy. */ lsi_script_scsi_interrupt(s, 0, LSI_SIST1_GEN); } break; case 0x4a: /* RESPID0 */ s->respid0 = val; break; case 0x4b: /* RESPID1 */ s->respid1 = val; break; case 0x4d: /* STEST1 */ s->stest1 = val; break; case 0x4e: /* STEST2 */ if (val & 1) { BADF("Low level mode not implemented\n"); } s->stest2 = val; break; case 0x4f: /* STEST3 */ if (val & 0x41) { BADF("SCSI FIFO test mode not implemented\n"); } s->stest3 = val; break; case 0x56: /* CCNTL0 */ s->ccntl0 = val; break; case 0x57: /* CCNTL1 */ s->ccntl1 = val; break; CASE_SET_REG32(mmrs, 0xa0) CASE_SET_REG32(mmws, 0xa4) CASE_SET_REG32(sfs, 0xa8) CASE_SET_REG32(drs, 0xac) CASE_SET_REG32(sbms, 0xb0) CASE_SET_REG32(dbms, 0xb4) CASE_SET_REG32(dnad64, 0xb8) CASE_SET_REG32(pmjad1, 0xc0) CASE_SET_REG32(pmjad2, 0xc4) CASE_SET_REG32(rbc, 0xc8) CASE_SET_REG32(ua, 0xcc) CASE_SET_REG32(ia, 0xd4) CASE_SET_REG32(sbc, 0xd8) CASE_SET_REG32(csbc, 0xdc) default: if (offset >= 0x5c && offset < 0xa0) { int n; int shift; n = (offset - 0x58) >> 2; shift = (offset & 3) * 8; s->scratch[n] &= ~(0xff << shift); s->scratch[n] |= (val & 0xff) << shift; } else { BADF("Unhandled writeb 0x%x = 0x%x\n", offset, val); } } #undef CASE_SET_REG24 #undef CASE_SET_REG32 }


static void upnp_event_prepare(struct upnp_event_notify * obj)
{
	static const char notifymsg[] =
		"NOTIFY %s HTTP/1.1\r\n"
		"Host: %s%s\r\n"
#if (UPNP_VERSION_MAJOR == 1) && (UPNP_VERSION_MINOR == 0)
		"Content-Type: text/xml\r\n"	/* UDA v1.0 */
#else
		"Content-Type: text/xml; charset=\"utf-8\"\r\n"	/* UDA v1.1 or later */
#endif
		"Content-Length: %d\r\n"
		"NT: upnp:event\r\n"
		"NTS: upnp:propchange\r\n"
		"SID: %s\r\n"
		"SEQ: %u\r\n"
		"Connection: close\r\n"
		"Cache-Control: no-cache\r\n"
		"\r\n"
		"%.*s\r\n";
	char * xml;
	int l;
	if(obj->sub == NULL) {
		obj->state = EError;
		return;
	}
	switch(obj->sub->service) {
	case EWanCFG:
		xml = getVarsWANCfg(&l);
		break;
	case EWanIPC:
		xml = getVarsWANIPCn(&l);
		break;
#ifdef ENABLE_L3F_SERVICE
	case EL3F:
		xml = getVarsL3F(&l);
		break;
#endif
#ifdef ENABLE_6FC_SERVICE
	case E6FC:
		xml = getVars6FC(&l);
		break;
#endif
#ifdef ENABLE_DP_SERVICE
	case EDP:
		xml = getVarsDP(&l);
		break;
#endif
	default:
		xml = NULL;
		l = 0;
	}
	obj->buffersize = 1024;
	for (;;) {
		obj->buffer = malloc(obj->buffersize);
		if(!obj->buffer) {
			syslog(LOG_ERR, "%s: malloc returned NULL", "upnp_event_prepare");
			if(xml) {
				free(xml);
			}
			obj->state = EError;
			return;
		}
		obj->tosend = snprintf(obj->buffer, obj->buffersize, notifymsg,
		                       obj->path, obj->addrstr, obj->portstr, l+2,
		                       obj->sub->uuid, obj->sub->seq,
		                       l, xml);
		if (obj->tosend < 0) {
			syslog(LOG_ERR, "%s: snprintf() failed", "upnp_event_prepare");
			if(xml) {
				free(xml);
			}
			obj->state = EError;
			return;
		} else if (obj->tosend < obj->buffersize) {
			break; /* the buffer was large enough */
		}
		/* Try again with a buffer big enough */
		free(obj->buffer);
		obj->buffersize = obj->tosend + 1;	/* reserve space for the final 0 */
	}
	if(xml) {
		free(xml);
		xml = NULL;
	}
	obj->state = ESending;
}


build_rsdp(GArray *rsdp_table, BIOSLinker *linker, unsigned rsdt_tbl_offset) { AcpiRsdpDescriptor *rsdp = acpi_data_push(rsdp_table, sizeof *rsdp); unsigned rsdt_pa_size = sizeof(rsdp->rsdt_physical_address); unsigned rsdt_pa_offset = (char *)&rsdp->rsdt_physical_address - rsdp_table->data; bios_linker_loader_alloc(linker, ACPI_BUILD_RSDP_FILE, rsdp_table, 16, true /* fseg memory */); memcpy(&rsdp->signature, "RSD PTR ", sizeof(rsdp->signature)); memcpy(rsdp->oem_id, ACPI_BUILD_APPNAME6, sizeof(rsdp->oem_id)); rsdp->length = cpu_to_le32(sizeof(*rsdp)); rsdp->revision = 0x02; /* Address to be filled by Guest linker */ bios_linker_loader_add_pointer(linker, ACPI_BUILD_RSDP_FILE, rsdt_pa_offset, rsdt_pa_size, ACPI_BUILD_TABLE_FILE, rsdt_tbl_offset); rsdp->checksum = 0; /* Checksum to be filled by Guest linker */ bios_linker_loader_add_checksum(linker, ACPI_BUILD_RSDP_FILE, rsdp, sizeof *rsdp, &rsdp->checksum); return rsdp_table; }


brcmf_cfg80211_mgmt_tx(struct wiphy *wiphy, struct wireless_dev *wdev,
		       struct cfg80211_mgmt_tx_params *params, u64 *cookie)
{
	struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
	struct ieee80211_channel *chan = params->chan;
	const u8 *buf = params->buf;
	size_t len = params->len;
	const struct ieee80211_mgmt *mgmt;
	struct brcmf_cfg80211_vif *vif;
	s32 err = 0;
	s32 ie_offset;
	s32 ie_len;
	struct brcmf_fil_action_frame_le *action_frame;
	struct brcmf_fil_af_params_le *af_params;
	bool ack;
	s32 chan_nr;
	u32 freq;

	brcmf_dbg(TRACE, "Enter\n");

	*cookie = 0;

	mgmt = (const struct ieee80211_mgmt *)buf;

	if (!ieee80211_is_mgmt(mgmt->frame_control)) {
		brcmf_err("Driver only allows MGMT packet type\n");
		return -EPERM;
	}

	vif = container_of(wdev, struct brcmf_cfg80211_vif, wdev);

	if (ieee80211_is_probe_resp(mgmt->frame_control)) {
		/* Right now the only reason to get a probe response */
		/* is for p2p listen response or for p2p GO from     */
		/* wpa_supplicant. Unfortunately the probe is send   */
		/* on primary ndev, while dongle wants it on the p2p */
		/* vif. Since this is only reason for a probe        */
		/* response to be sent, the vif is taken from cfg.   */
		/* If ever desired to send proberesp for non p2p     */
		/* response then data should be checked for          */
		/* "DIRECT-". Note in future supplicant will take    */
		/* dedicated p2p wdev to do this and then this 'hack'*/
		/* is not needed anymore.                            */
		ie_offset =  DOT11_MGMT_HDR_LEN +
			     DOT11_BCN_PRB_FIXED_LEN;
		ie_len = len - ie_offset;
		if (vif == cfg->p2p.bss_idx[P2PAPI_BSSCFG_PRIMARY].vif)
			vif = cfg->p2p.bss_idx[P2PAPI_BSSCFG_DEVICE].vif;
		err = brcmf_vif_set_mgmt_ie(vif,
					    BRCMF_VNDR_IE_PRBRSP_FLAG,
					    &buf[ie_offset],
					    ie_len);
		cfg80211_mgmt_tx_status(wdev, *cookie, buf, len, true,
					GFP_KERNEL);
	} else if (ieee80211_is_action(mgmt->frame_control)) {
		af_params = kzalloc(sizeof(*af_params), GFP_KERNEL);
		if (af_params == NULL) {
			brcmf_err("unable to allocate frame\n");
			err = -ENOMEM;
			goto exit;
		}
		action_frame = &af_params->action_frame;
		/* Add the packet Id */
		action_frame->packet_id = cpu_to_le32(*cookie);
		/* Add BSSID */
		memcpy(&action_frame->da[0], &mgmt->da[0], ETH_ALEN);
		memcpy(&af_params->bssid[0], &mgmt->bssid[0], ETH_ALEN);
		/* Add the length exepted for 802.11 header  */
		action_frame->len = cpu_to_le16(len - DOT11_MGMT_HDR_LEN);
		/* Add the channel. Use the one specified as parameter if any or
		 * the current one (got from the firmware) otherwise
		 */
		if (chan)
			freq = chan->center_freq;
		else
			brcmf_fil_cmd_int_get(vif->ifp, BRCMF_C_GET_CHANNEL,
					      &freq);
		chan_nr = ieee80211_frequency_to_channel(freq);
		af_params->channel = cpu_to_le32(chan_nr);

		memcpy(action_frame->data, &buf[DOT11_MGMT_HDR_LEN],
		       le16_to_cpu(action_frame->len));

		brcmf_dbg(TRACE, "Action frame, cookie=%lld, len=%d, freq=%d\n",
			  *cookie, le16_to_cpu(action_frame->len), freq);

		ack = brcmf_p2p_send_action_frame(cfg, cfg_to_ndev(cfg),
						  af_params);

		cfg80211_mgmt_tx_status(wdev, *cookie, buf, len, ack,
					GFP_KERNEL);
		kfree(af_params);
	} else {
		brcmf_dbg(TRACE, "Unhandled, fc=%04x!!\n", mgmt->frame_control);
		brcmf_dbg_hex_dump(true, buf, len, "payload, len=%zu\n", len);
	}

exit:
	return err;
}


GetOutboundPinholeTimeout(struct upnphttp * h, const char * action, const char * ns)
{
	int r;

	static const char resp[] =
		"<u:%sResponse "
		"xmlns:u=\"%s\">"
		"<OutboundPinholeTimeout>%d</OutboundPinholeTimeout>"
		"</u:%sResponse>";

	char body[512];
	int bodylen;
	struct NameValueParserData data;
	char * int_ip, * int_port, * rem_host, * rem_port, * protocol;
	int opt=0;
	/*int proto=0;*/
	unsigned short iport, rport;

	if (GETFLAG(IPV6FCFWDISABLEDMASK))
	{
		SoapError(h, 702, "FirewallDisabled");
		return;
	}

	ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
	int_ip = GetValueFromNameValueList(&data, "InternalClient");
	int_port = GetValueFromNameValueList(&data, "InternalPort");
	rem_host = GetValueFromNameValueList(&data, "RemoteHost");
	rem_port = GetValueFromNameValueList(&data, "RemotePort");
	protocol = GetValueFromNameValueList(&data, "Protocol");

	if (!int_port || !rem_port || !protocol)
	{
		ClearNameValueList(&data);
		SoapError(h, 402, "Invalid Args");
		return;
	}

	rport = (unsigned short)atoi(rem_port);
	iport = (unsigned short)atoi(int_port);
	/*proto = atoi(protocol);*/

	syslog(LOG_INFO, "%s: retrieving timeout for outbound pinhole from [%s]:%hu to [%s]:%hu protocol %s", action, int_ip, iport,rem_host, rport, protocol);

	/* TODO */
	r = -1;/*upnp_check_outbound_pinhole(proto, &opt);*/

	switch(r)
	{
		case 1:	/* success */
			bodylen = snprintf(body, sizeof(body), resp,
			                   action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/,
			                   opt, action);
			BuildSendAndCloseSoapResp(h, body, bodylen);
			break;
		case -5:	/* Protocol not supported */
			SoapError(h, 705, "ProtocolNotSupported");
			break;
		default:
			SoapError(h, 501, "ActionFailed");
	}
	ClearNameValueList(&data);
}


static void exception_action ( CPUArchState * env1 ) {
 # if defined ( TARGET_I386 ) raise_exception_err ( env1 , env1 -> exception_index , env1 -> error_code ) ;
 # else cpu_loop_exit ( env1 ) ;
 # endif }


static coroutine_fn int nbd_negotiate(NBDClientNewData *data)
{
    NBDClient *client = data->client;
    char buf[8 + 8 + 8 + 128];
    int rc;
    const uint16_t myflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_TRIM |
                              NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_FUA |
                              NBD_FLAG_SEND_WRITE_ZEROES);
    bool oldStyle;
    size_t len;

    /* Old style negotiation header without options
        [ 0 ..   7]   passwd       ("NBDMAGIC")
        [ 8 ..  15]   magic        (NBD_CLIENT_MAGIC)
        [16 ..  23]   size
        [24 ..  25]   server flags (0)
        [26 ..  27]   export flags
        [28 .. 151]   reserved     (0)

       New style negotiation header with options
        [ 0 ..   7]   passwd       ("NBDMAGIC")
        [ 8 ..  15]   magic        (NBD_OPTS_MAGIC)
        [16 ..  17]   server flags (0)
        ....options sent....
        [18 ..  25]   size
        [26 ..  27]   export flags
        [28 .. 151]   reserved     (0, omit if no_zeroes)
     */

    qio_channel_set_blocking(client->ioc, false, NULL);
    rc = -EINVAL;

    TRACE("Beginning negotiation.");
    memset(buf, 0, sizeof(buf));
    memcpy(buf, "NBDMAGIC", 8);

    oldStyle = client->exp != NULL && !client->tlscreds;
    if (oldStyle) {
        TRACE("advertising size %" PRIu64 " and flags %x",
              client->exp->size, client->exp->nbdflags | myflags);
        stq_be_p(buf + 8, NBD_CLIENT_MAGIC);
        stq_be_p(buf + 16, client->exp->size);
        stw_be_p(buf + 26, client->exp->nbdflags | myflags);
    } else {
        stq_be_p(buf + 8, NBD_OPTS_MAGIC);
        stw_be_p(buf + 16, NBD_FLAG_FIXED_NEWSTYLE | NBD_FLAG_NO_ZEROES);
    }

    if (oldStyle) {
        if (client->tlscreds) {
            TRACE("TLS cannot be enabled with oldstyle protocol");
            goto fail;
        }
        if (nbd_negotiate_write(client->ioc, buf, sizeof(buf)) < 0) {
            LOG("write failed");
            goto fail;
        }
    } else {
        if (nbd_negotiate_write(client->ioc, buf, 18) < 0) {
            LOG("write failed");
            goto fail;
        }
        rc = nbd_negotiate_options(client);
        if (rc != 0) {
            LOG("option negotiation failed");
            goto fail;
        }

        TRACE("advertising size %" PRIu64 " and flags %x",
              client->exp->size, client->exp->nbdflags | myflags);
        stq_be_p(buf + 18, client->exp->size);
        stw_be_p(buf + 26, client->exp->nbdflags | myflags);
        len = client->no_zeroes ? 10 : sizeof(buf) - 18;
        if (nbd_negotiate_write(client->ioc, buf + 18, len) < 0) {
            LOG("write failed");
            goto fail;
        }
    }

    TRACE("Negotiation succeeded.");
    rc = 0;
fail:
    return rc;
}


static int nbd_negotiate_handle_export_name(NBDClient *client, uint32_t length)
{
    int rc = -EINVAL;
    char name[NBD_MAX_NAME_SIZE + 1];

    /* Client sends:
        [20 ..  xx]   export name (length bytes)
     */
    TRACE("Checking length");
    if (length >= sizeof(name)) {
        LOG("Bad length received");
        goto fail;
    }
    if (nbd_negotiate_read(client->ioc, name, length) < 0) {
        LOG("read failed");
        goto fail;
    }
    name[length] = '\0';

    TRACE("Client requested export '%s'", name);

    client->exp = nbd_export_find(name);
    if (!client->exp) {
        LOG("export not found");
        goto fail;
    }

    QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
    nbd_export_get(client->exp);
    rc = 0;
fail:
    return rc;
}


int ff_ape_write_tag(AVFormatContext *s) { AVDictionaryEntry *e = NULL; int64_t start, end; int size, count = 0; if (!s->pb->seekable) return 0; start = avio_tell(s->pb); // header avio_write(s->pb, "APETAGEX", 8); // id avio_wl32 (s->pb, APE_TAG_VERSION); // version avio_wl32(s->pb, 0); // reserve space for size avio_wl32(s->pb, 0); // reserve space for tag count // flags avio_wl32(s->pb, APE_TAG_FLAG_CONTAINS_HEADER | APE_TAG_FLAG_CONTAINS_FOOTER | APE_TAG_FLAG_IS_HEADER); ffio_fill(s->pb, 0, 8); // reserved while ((e = av_dict_get(s->metadata, "", e, AV_DICT_IGNORE_SUFFIX))) { int val_len = strlen(e->value); avio_wl32(s->pb, val_len); // value length avio_wl32(s->pb, 0); // item flags avio_put_str(s->pb, e->key); // key avio_write(s->pb, e->value, val_len); // value count++; } size = avio_tell(s->pb) - start; // footer avio_write(s->pb, "APETAGEX", 8); // id avio_wl32 (s->pb, APE_TAG_VERSION); // version avio_wl32(s->pb, size); // size avio_wl32(s->pb, count); // tag count // flags avio_wl32(s->pb, APE_TAG_FLAG_CONTAINS_HEADER | APE_TAG_FLAG_CONTAINS_FOOTER); ffio_fill(s->pb, 0, 8); // reserved // update values in the header end = avio_tell(s->pb); avio_seek(s->pb, start + 12, SEEK_SET); avio_wl32(s->pb, size); avio_wl32(s->pb, count); avio_seek(s->pb, end, SEEK_SET); return 0; }


void *address_space_map(AddressSpace *as, hwaddr addr, hwaddr *plen, bool is_write) { hwaddr len = *plen; hwaddr done = 0; hwaddr l, xlat, base; MemoryRegion *mr, *this_mr; ram_addr_t raddr; if (len == 0) { return NULL; } l = len; mr = address_space_translate(as, addr, &xlat, &l, is_write); if (!memory_access_is_direct(mr, is_write)) { if (bounce.buffer) { return NULL; } /* Avoid unbounded allocations */ l = MIN(l, TARGET_PAGE_SIZE); bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l); bounce.addr = addr; bounce.len = l; memory_region_ref(mr); bounce.mr = mr; if (!is_write) { address_space_read(as, addr, bounce.buffer, l); } *plen = l; return bounce.buffer; } base = xlat; raddr = memory_region_get_ram_addr(mr); for (;;) { len -= l; addr += l; done += l; if (len == 0) { break; } l = len; this_mr = address_space_translate(as, addr, &xlat, &l, is_write); if (this_mr != mr || xlat != base + done) { break; } } memory_region_ref(mr); *plen = done; return qemu_ram_ptr_length(raddr + base, plen); }


static double calc_frame_boost ( const TWO_PASS * twopass , const FIRSTPASS_STATS * this_frame , double this_frame_mv_in_out ) {
 double frame_boost ;
 if ( this_frame -> intra_error > twopass -> gf_intra_err_min ) frame_boost = ( IIFACTOR * this_frame -> intra_error / DOUBLE_DIVIDE_CHECK ( this_frame -> coded_error ) ) ;
 else frame_boost = ( IIFACTOR * twopass -> gf_intra_err_min / DOUBLE_DIVIDE_CHECK ( this_frame -> coded_error ) ) ;
 if ( this_frame_mv_in_out > 0.0 ) frame_boost += frame_boost * ( this_frame_mv_in_out * 2.0 ) ;
 else frame_boost += frame_boost * ( this_frame_mv_in_out / 2.0 ) ;
 return MIN ( frame_boost , GF_RMAX ) ;
 }


static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs, int64_t sector_num, QEMUIOVector *qiov, int nb_sectors, BlockDriverCompletionFunc *cb, void *opaque) { const uint8_t *first_buf; int first_buf_index = 0, i; /* This is probably being paranoid, but handle cases of zero size vectors. */ for (i = 0; i < qiov->niov; i++) { if (qiov->iov[i].iov_len) { assert(qiov->iov[i].iov_len >= 512); first_buf_index = i; break; } } first_buf = qiov->iov[first_buf_index].iov_base; if (check_write_unsafe(bs, sector_num, first_buf, nb_sectors)) { RawScrubberBounce *b; int ret; /* write the first sector using sync I/O */ ret = raw_write_scrubbed_bootsect(bs, first_buf); if (ret < 0) { return NULL; } /* adjust request to be everything but first sector */ b = qemu_malloc(sizeof(*b)); b->cb = cb; b->opaque = opaque; qemu_iovec_init(&b->qiov, qiov->nalloc); qemu_iovec_concat(&b->qiov, qiov, qiov->size); b->qiov.size -= 512; b->qiov.iov[first_buf_index].iov_base += 512; b->qiov.iov[first_buf_index].iov_len -= 512; return bdrv_aio_writev(bs->file, sector_num + 1, &b->qiov, nb_sectors - 1, raw_aio_writev_scrubbed, b); } return bdrv_aio_writev(bs->file, sector_num, qiov, nb_sectors, cb, opaque); }


QPDFObjectHandle::newIndirect(QPDF* qpdf, int objid, int generation)
{
    return QPDFObjectHandle(qpdf, objid, generation);
}