static int dirac_unpack_idwt_params(DiracContext *s) { GetBitContext *gb = &s->gb; int i, level; unsigned tmp; #define CHECKEDREAD(dst, cond, errmsg) \ tmp = svq3_get_ue_golomb(gb); \ if (cond) { \ av_log(s->avctx, AV_LOG_ERROR, errmsg); \ return -1; \ }\ dst = tmp; align_get_bits(gb); s->zero_res = s->num_refs ? get_bits1(gb) : 0; if (s->zero_res) return 0; /*[DIRAC_STD] 11.3.1 Transform parameters. transform_parameters() */ CHECKEDREAD(s->wavelet_idx, tmp > 6, "wavelet_idx is too big\n") CHECKEDREAD(s->wavelet_depth, tmp > MAX_DWT_LEVELS || tmp < 1, "invalid number of DWT decompositions\n") if (!s->low_delay) { /* Codeblock parameters (core syntax only) */ if (get_bits1(gb)) { for (i = 0; i <= s->wavelet_depth; i++) { CHECKEDREAD(s->codeblock[i].width , tmp < 1, "codeblock width invalid\n") CHECKEDREAD(s->codeblock[i].height, tmp < 1, "codeblock height invalid\n") } CHECKEDREAD(s->codeblock_mode, tmp > 1, "unknown codeblock mode\n") } else for (i = 0; i <= s->wavelet_depth; i++) s->codeblock[i].width = s->codeblock[i].height = 1; } else { /* Slice parameters + quantization matrix*/ /*[DIRAC_STD] 11.3.4 Slice coding Parameters (low delay syntax only). slice_parameters() */ s->lowdelay.num_x = svq3_get_ue_golomb(gb); s->lowdelay.num_y = svq3_get_ue_golomb(gb); s->lowdelay.bytes.num = svq3_get_ue_golomb(gb); s->lowdelay.bytes.den = svq3_get_ue_golomb(gb); if (s->lowdelay.bytes.den <= 0) { av_log(s->avctx,AV_LOG_ERROR,"Invalid lowdelay.bytes.den\n"); return AVERROR_INVALIDDATA; } /* [DIRAC_STD] 11.3.5 Quantisation matrices (low-delay syntax). quant_matrix() */ if (get_bits1(gb)) { av_log(s->avctx,AV_LOG_DEBUG,"Low Delay: Has Custom Quantization Matrix!\n"); /* custom quantization matrix */ s->lowdelay.quant[0][0] = svq3_get_ue_golomb(gb); for (level = 0; level < s->wavelet_depth; level++) { s->lowdelay.quant[level][1] = svq3_get_ue_golomb(gb); s->lowdelay.quant[level][2] = svq3_get_ue_golomb(gb); s->lowdelay.quant[level][3] = svq3_get_ue_golomb(gb); } } else { if (s->wavelet_depth > 4) { av_log(s->avctx,AV_LOG_ERROR,"Mandatory custom low delay matrix missing for depth %d\n", s->wavelet_depth); return AVERROR_INVALIDDATA; } /* default quantization matrix */ for (level = 0; level < s->wavelet_depth; level++) for (i = 0; i < 4; i++) { s->lowdelay.quant[level][i] = default_qmat[s->wavelet_idx][level][i]; /* haar with no shift differs for different depths */ if (s->wavelet_idx == 3) s->lowdelay.quant[level][i] += 4*(s->wavelet_depth-1 - level); } } } return 0; }


static CURLcode imap_state_fetch_resp(struct connectdata *conn, int imapcode,
                                      imapstate instate)
{
  CURLcode result = CURLE_OK;
  struct Curl_easy *data = conn->data;
  struct imap_conn *imapc = &conn->proto.imapc;
  struct pingpong *pp = &imapc->pp;
  const char *ptr = data->state.buffer;
  bool parsed = FALSE;
  curl_off_t size = 0;

  (void)instate; /* no use for this yet */

  if(imapcode != '*') {
    Curl_pgrsSetDownloadSize(data, -1);
    state(conn, IMAP_STOP);
    return CURLE_REMOTE_FILE_NOT_FOUND; /* TODO: Fix error code */
  }

  /* Something like this is received "* 1 FETCH (BODY[TEXT] {2021}\r" so parse
     the continuation data contained within the curly brackets */
  while(*ptr && (*ptr != '{'))
    ptr++;

  if(*ptr == '{') {
    char *endptr;
    if(!curlx_strtoofft(ptr + 1, &endptr, 10, &size)) {
      if(endptr - ptr > 1 && endptr[0] == '}' &&
         endptr[1] == '\r' && endptr[2] == '\0')
        parsed = TRUE;
    }
  }

  if(parsed) {
    infof(data, "Found %" CURL_FORMAT_CURL_OFF_TU " bytes to download\n",
          size);
    Curl_pgrsSetDownloadSize(data, size);

    if(pp->cache) {
      /* At this point there is a bunch of data in the header "cache" that is
         actually body content, send it as body and then skip it. Do note
         that there may even be additional "headers" after the body. */
      size_t chunk = pp->cache_size;

      if(chunk > (size_t)size)
        /* The conversion from curl_off_t to size_t is always fine here */
        chunk = (size_t)size;

      result = Curl_client_write(conn, CLIENTWRITE_BODY, pp->cache, chunk);
      if(result)
        return result;

      data->req.bytecount += chunk;

      infof(data, "Written %" CURL_FORMAT_CURL_OFF_TU
            " bytes, %" CURL_FORMAT_CURL_OFF_TU
            " bytes are left for transfer\n", (curl_off_t)chunk,
            size - chunk);

      /* Have we used the entire cache or just part of it?*/
      if(pp->cache_size > chunk) {
        /* Only part of it so shrink the cache to fit the trailing data */
        memmove(pp->cache, pp->cache + chunk, pp->cache_size - chunk);
        pp->cache_size -= chunk;
      }
      else {
        /* Free the cache */
        Curl_safefree(pp->cache);

        /* Reset the cache size */
        pp->cache_size = 0;
      }
    }

    if(data->req.bytecount == size)
      /* The entire data is already transferred! */
      Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
    else {
      /* IMAP download */
      data->req.maxdownload = size;
      Curl_setup_transfer(conn, FIRSTSOCKET, size, FALSE, NULL, -1, NULL);
    }
  }
  else {
    /* We don't know how to parse this line */
    failf(pp->conn->data, "Failed to parse FETCH response.");
    result = CURLE_WEIRD_SERVER_REPLY;
  }

  /* End of DO phase */
  state(conn, IMAP_STOP);

  return result;
}


static void HandleType3Reference ( IO * wrapper , EntityChar * ec , real transform [ 6 ] , char * tokbuf , int toksize ) {
 int tok ;
 real dval ;
 char * glyphname ;
 RefChar * ref ;
 tok = nextpstoken ( wrapper , & dval , tokbuf , toksize ) ;
 if ( strcmp ( tokbuf , "get" ) != 0 ) return ;
 tok = nextpstoken ( wrapper , & dval , tokbuf , toksize ) ;
 if ( tok != pt_namelit ) return ;
 glyphname = copy ( tokbuf ) ;
 tok = nextpstoken ( wrapper , & dval , tokbuf , toksize ) ;
 if ( strcmp ( tokbuf , "get" ) != 0 ) {
 free ( glyphname ) ;
 return ;
 }
 tok = nextpstoken ( wrapper , & dval , tokbuf , toksize ) ;
 if ( strcmp ( tokbuf , "exec" ) != 0 ) {
 free ( glyphname ) ;
 return ;
 }
 ref = RefCharCreate ( ) ;
 memcpy ( ref -> transform , transform , sizeof ( ref -> transform ) ) ;
 ref -> sc = ( SplineChar * ) glyphname ;
 ref -> next = ec -> refs ;
 ec -> refs = ref ;
 }


static int yop_probe(AVProbeData *probe_packet) { if (AV_RB16(probe_packet->buf) == AV_RB16("YO") && probe_packet->buf[6] && probe_packet->buf[7] && !(probe_packet->buf[8] & 1) && !(probe_packet->buf[10] & 1)) return AVPROBE_SCORE_MAX * 3 / 4; return 0; }


av_cold int ff_vp8_decode_init(AVCodecContext *avctx) { VP8Context *s = avctx->priv_data; int ret; s->avctx = avctx; avctx->pix_fmt = AV_PIX_FMT_YUV420P; avctx->internal->allocate_progress = 1; ff_videodsp_init(&s->vdsp, 8); ff_h264_pred_init(&s->hpc, AV_CODEC_ID_VP8, 8, 1); ff_vp8dsp_init(&s->vp8dsp); if ((ret = vp8_init_frames(s)) < 0) { ff_vp8_decode_free(avctx); return ret; } return 0; }


TSReturnCode TSMimeHdrFieldValuesClear ( TSMBuffer bufp , TSMLoc hdr , TSMLoc field ) {
 sdk_assert ( sdk_sanity_check_mbuffer ( bufp ) == TS_SUCCESS ) ;
 sdk_assert ( ( sdk_sanity_check_mime_hdr_handle ( hdr ) == TS_SUCCESS ) || ( sdk_sanity_check_http_hdr_handle ( hdr ) == TS_SUCCESS ) ) ;
 sdk_assert ( sdk_sanity_check_field_handle ( field , hdr ) == TS_SUCCESS ) ;
 if ( ! isWriteable ( bufp ) ) {
 return TS_ERROR ;
 }
 MIMEFieldSDKHandle * handle = ( MIMEFieldSDKHandle * ) field ;
 HdrHeap * heap = ( ( HdrHeapSDKHandle * ) bufp ) -> m_heap ;
 mime_field_value_set ( heap , handle -> mh , handle -> field_ptr , nullptr , 0 , true ) ;
 return TS_SUCCESS ;
 }


bool send_metakey ( connection_t * c ) {
 bool x ;
 int len = RSA_size ( c -> rsa_key ) ;
 char buffer [ 2 * len + 1 ] ;
 c -> outkey = xrealloc ( c -> outkey , len ) ;
 if ( ! c -> outctx ) {
 c -> outctx = EVP_CIPHER_CTX_new ( ) ;
 if ( ! c -> outctx ) {
 abort ( ) ;
 }
 }
 if ( 1 != RAND_bytes ( ( unsigned char * ) c -> outkey , len ) ) {
 int err = ERR_get_error ( ) ;
 logger ( LOG_ERR , "Failed to generate meta key (%s)" , ERR_error_string ( err , NULL ) ) ;
 return false ;
 }
 c -> outkey [ 0 ] &= 0x7F ;
 ifdebug ( SCARY_THINGS ) {
 bin2hex ( c -> outkey , buffer , len ) ;
 buffer [ len * 2 ] = '\0' ;
 logger ( LOG_DEBUG , "Generated random meta key (unencrypted): %s" , buffer ) ;
 }
 if ( RSA_public_encrypt ( len , ( unsigned char * ) c -> outkey , ( unsigned char * ) buffer , c -> rsa_key , RSA_NO_PADDING ) != len ) {
 logger ( LOG_ERR , "Error during encryption of meta key for %s (%s): %s" , c -> name , c -> hostname , ERR_error_string ( ERR_get_error ( ) , NULL ) ) ;
 return false ;
 }
 bin2hex ( buffer , buffer , len ) ;
 buffer [ len * 2 ] = '\0' ;
 x = send_request ( c , "%d %d %d %d %d %s" , METAKEY , c -> outcipher ? EVP_CIPHER_nid ( c -> outcipher ) : 0 , c -> outdigest ? EVP_MD_type ( c -> outdigest ) : 0 , c -> outmaclength , c -> outcompression , buffer ) ;
 if ( c -> outcipher ) {
 if ( ! EVP_EncryptInit ( c -> outctx , c -> outcipher , ( unsigned char * ) c -> outkey + len - EVP_CIPHER_key_length ( c -> outcipher ) , ( unsigned char * ) c -> outkey + len - EVP_CIPHER_key_length ( c -> outcipher ) - EVP_CIPHER_iv_length ( c -> outcipher ) ) ) {
 logger ( LOG_ERR , "Error during initialisation of cipher for %s (%s): %s" , c -> name , c -> hostname , ERR_error_string ( ERR_get_error ( ) , NULL ) ) ;
 return false ;
 }
 c -> outbudget = byte_budget ( c -> outcipher ) ;
 c -> status . encryptout = true ;
 }
 return x ;
 }


print_attr_string(netdissect_options *ndo,
                  register const u_char *data, u_int length, u_short attr_code)
{
   register u_int i;

   ND_TCHECK2(data[0],length);

   switch(attr_code)
   {
      case TUNNEL_PASS:
           if (length < 3)
           {
              ND_PRINT((ndo, "%s", tstr));
              return;
           }
           if (*data && (*data <=0x1F) )
              ND_PRINT((ndo, "Tag[%u] ", *data));
           else
              ND_PRINT((ndo, "Tag[Unused] "));
           data++;
           length--;
           ND_PRINT((ndo, "Salt %u ", EXTRACT_16BITS(data)));
           data+=2;
           length-=2;
        break;
      case TUNNEL_CLIENT_END:
      case TUNNEL_SERVER_END:
      case TUNNEL_PRIV_GROUP:
      case TUNNEL_ASSIGN_ID:
      case TUNNEL_CLIENT_AUTH:
      case TUNNEL_SERVER_AUTH:
           if (*data <= 0x1F)
           {
              if (length < 1)
              {
                 ND_PRINT((ndo, "%s", tstr));
                 return;
              }
              if (*data)
                ND_PRINT((ndo, "Tag[%u] ", *data));
              else
                ND_PRINT((ndo, "Tag[Unused] "));
              data++;
              length--;
           }
        break;
      case EGRESS_VLAN_NAME:
           ND_PRINT((ndo, "%s (0x%02x) ",
                  tok2str(rfc4675_tagged,"Unknown tag",*data),
                  *data));
           data++;
           length--;
        break;
   }

   for (i=0; *data && i < length ; i++, data++)
       ND_PRINT((ndo, "%c", (*data < 32 || *data > 126) ? '.' : *data));

   return;

   trunc:
      ND_PRINT((ndo, "%s", tstr));
}


bool check_grant_db ( THD * thd , const char * db ) {
 Security_context * sctx = thd -> security_ctx ;
 char helping [ NAME_LEN + USERNAME_LENGTH + 2 ] ;
 uint len ;
 bool error = TRUE ;
 size_t copy_length ;
 copy_length = ( size_t ) ( strlen ( sctx -> priv_user ? sctx -> priv_user : "" ) + strlen ( db ? db : "" ) ) + 1 ;
 if ( copy_length >= ( NAME_LEN + USERNAME_LENGTH + 2 ) ) return 1 ;
 len = ( uint ) ( strmov ( strmov ( helping , sctx -> priv_user ) + 1 , db ) - helping ) + 1 ;
 rw_rdlock ( & LOCK_grant ) ;
 for ( uint idx = 0 ;
 idx < column_priv_hash . records ;
 idx ++ ) {
 GRANT_TABLE * grant_table = ( GRANT_TABLE * ) hash_element ( & column_priv_hash , idx ) ;
 if ( len < grant_table -> key_length && ! memcmp ( grant_table -> hash_key , helping , len ) && compare_hostname ( & grant_table -> host , sctx -> host , sctx -> ip ) ) {
 error = FALSE ;
 break ;
 }
 }
 if ( error ) error = check_grant_db_routine ( thd , db , & proc_priv_hash ) && check_grant_db_routine ( thd , db , & func_priv_hash ) ;
 rw_unlock ( & LOCK_grant ) ;
 return error ;
 }


static int mlib_YUV2ABGR420_32(SwsContext *c, uint8_t* src[], int srcStride[], int srcSliceY, int srcSliceH, uint8_t* dst[], int dstStride[]){ if(c->srcFormat == PIX_FMT_YUV422P){ srcStride[1] *= 2; srcStride[2] *= 2; } assert(srcStride[1] == srcStride[2]); mlib_VideoColorYUV2ABGR420(dst[0]+srcSliceY*dstStride[0], src[0], src[1], src[2], c->dstW, srcSliceH, dstStride[0], srcStride[0], srcStride[1]); return srcSliceH; }


static int alloc_frame_buffer ( MpegEncContext * s , Picture * pic ) {
 int r , ret ;
 if ( s -> avctx -> hwaccel ) {
 assert ( ! pic -> hwaccel_picture_private ) ;
 if ( s -> avctx -> hwaccel -> priv_data_size ) {
 pic -> hwaccel_picture_private = av_mallocz ( s -> avctx -> hwaccel -> priv_data_size ) ;
 if ( ! pic -> hwaccel_picture_private ) {
 av_log ( s -> avctx , AV_LOG_ERROR , "alloc_frame_buffer() failed (hwaccel private data allocation)\n" ) ;
 return - 1 ;
 }
 }
 }
 pic -> tf . f = & pic -> f ;
 if ( s -> codec_id != AV_CODEC_ID_WMV3IMAGE && s -> codec_id != AV_CODEC_ID_VC1IMAGE && s -> codec_id != AV_CODEC_ID_MSS2 ) r = ff_thread_get_buffer ( s -> avctx , & pic -> tf , pic -> reference ? AV_GET_BUFFER_FLAG_REF : 0 ) ;
 else {
 pic -> f . width = s -> avctx -> width ;
 pic -> f . height = s -> avctx -> height ;
 pic -> f . format = s -> avctx -> pix_fmt ;
 r = avcodec_default_get_buffer2 ( s -> avctx , & pic -> f , 0 ) ;
 }
 if ( r < 0 || ! pic -> f . data [ 0 ] ) {
 av_log ( s -> avctx , AV_LOG_ERROR , "get_buffer() failed (%d %p)\n" , r , pic -> f . data [ 0 ] ) ;
 av_freep ( & pic -> hwaccel_picture_private ) ;
 return - 1 ;
 }
 if ( s -> linesize && ( s -> linesize != pic -> f . linesize [ 0 ] || s -> uvlinesize != pic -> f . linesize [ 1 ] ) ) {
 av_log ( s -> avctx , AV_LOG_ERROR , "get_buffer() failed (stride changed)\n" ) ;
 ff_mpeg_unref_picture ( s , pic ) ;
 return - 1 ;
 }
 if ( pic -> f . linesize [ 1 ] != pic -> f . linesize [ 2 ] ) {
 av_log ( s -> avctx , AV_LOG_ERROR , "get_buffer() failed (uv stride mismatch)\n" ) ;
 ff_mpeg_unref_picture ( s , pic ) ;
 return - 1 ;
 }
 if ( ! s -> edge_emu_buffer && ( ret = ff_mpv_frame_size_alloc ( s , pic -> f . linesize [ 0 ] ) ) < 0 ) {
 av_log ( s -> avctx , AV_LOG_ERROR , "get_buffer() failed to allocate context scratch buffers.\n" ) ;
 ff_mpeg_unref_picture ( s , pic ) ;
 return ret ;
 }
 return 0 ;
 }


av_cold static int auto_matrix(SwrContext *s) { int i, j, out_i; double matrix[NUM_NAMED_CHANNELS][NUM_NAMED_CHANNELS]={{0}}; int64_t unaccounted, in_ch_layout, out_ch_layout; double maxcoef=0; char buf[128]; const int matrix_encoding = s->matrix_encoding; float maxval; in_ch_layout = clean_layout(s, s->in_ch_layout); out_ch_layout = clean_layout(s, s->out_ch_layout); if( out_ch_layout == AV_CH_LAYOUT_STEREO_DOWNMIX && (in_ch_layout & AV_CH_LAYOUT_STEREO_DOWNMIX) == 0 ) out_ch_layout = AV_CH_LAYOUT_STEREO; if( in_ch_layout == AV_CH_LAYOUT_STEREO_DOWNMIX && (out_ch_layout & AV_CH_LAYOUT_STEREO_DOWNMIX) == 0 ) in_ch_layout = AV_CH_LAYOUT_STEREO; if(!sane_layout(in_ch_layout)){ av_get_channel_layout_string(buf, sizeof(buf), -1, s->in_ch_layout); av_log(s, AV_LOG_ERROR, "Input channel layout '%s' is not supported\n", buf); return AVERROR(EINVAL); } if(!sane_layout(out_ch_layout)){ av_get_channel_layout_string(buf, sizeof(buf), -1, s->out_ch_layout); av_log(s, AV_LOG_ERROR, "Output channel layout '%s' is not supported\n", buf); return AVERROR(EINVAL); } memset(s->matrix, 0, sizeof(s->matrix)); for(i=0; i<FF_ARRAY_ELEMS(matrix); i++){ if(in_ch_layout & out_ch_layout & (1ULL<<i)) matrix[i][i]= 1.0; } unaccounted= in_ch_layout & ~out_ch_layout; //FIXME implement dolby surround //FIXME implement full ac3 if(unaccounted & AV_CH_FRONT_CENTER){ if((out_ch_layout & AV_CH_LAYOUT_STEREO) == AV_CH_LAYOUT_STEREO){ if(in_ch_layout & AV_CH_LAYOUT_STEREO) { matrix[ FRONT_LEFT][FRONT_CENTER]+= s->clev; matrix[FRONT_RIGHT][FRONT_CENTER]+= s->clev; } else { matrix[ FRONT_LEFT][FRONT_CENTER]+= M_SQRT1_2; matrix[FRONT_RIGHT][FRONT_CENTER]+= M_SQRT1_2; } }else av_assert0(0); } if(unaccounted & AV_CH_LAYOUT_STEREO){ if(out_ch_layout & AV_CH_FRONT_CENTER){ matrix[FRONT_CENTER][ FRONT_LEFT]+= M_SQRT1_2; matrix[FRONT_CENTER][FRONT_RIGHT]+= M_SQRT1_2; if(in_ch_layout & AV_CH_FRONT_CENTER) matrix[FRONT_CENTER][ FRONT_CENTER] = s->clev*sqrt(2); }else av_assert0(0); } if(unaccounted & AV_CH_BACK_CENTER){ if(out_ch_layout & AV_CH_BACK_LEFT){ matrix[ BACK_LEFT][BACK_CENTER]+= M_SQRT1_2; matrix[BACK_RIGHT][BACK_CENTER]+= M_SQRT1_2; }else if(out_ch_layout & AV_CH_SIDE_LEFT){ matrix[ SIDE_LEFT][BACK_CENTER]+= M_SQRT1_2; matrix[SIDE_RIGHT][BACK_CENTER]+= M_SQRT1_2; }else if(out_ch_layout & AV_CH_FRONT_LEFT){ if (matrix_encoding == AV_MATRIX_ENCODING_DOLBY || matrix_encoding == AV_MATRIX_ENCODING_DPLII) { if (unaccounted & (AV_CH_BACK_LEFT | AV_CH_SIDE_LEFT)) { matrix[FRONT_LEFT ][BACK_CENTER] -= s->slev * M_SQRT1_2; matrix[FRONT_RIGHT][BACK_CENTER] += s->slev * M_SQRT1_2; } else { matrix[FRONT_LEFT ][BACK_CENTER] -= s->slev; matrix[FRONT_RIGHT][BACK_CENTER] += s->slev; } } else { matrix[ FRONT_LEFT][BACK_CENTER]+= s->slev*M_SQRT1_2; matrix[FRONT_RIGHT][BACK_CENTER]+= s->slev*M_SQRT1_2; } }else if(out_ch_layout & AV_CH_FRONT_CENTER){ matrix[ FRONT_CENTER][BACK_CENTER]+= s->slev*M_SQRT1_2; }else av_assert0(0); } if(unaccounted & AV_CH_BACK_LEFT){ if(out_ch_layout & AV_CH_BACK_CENTER){ matrix[BACK_CENTER][ BACK_LEFT]+= M_SQRT1_2; matrix[BACK_CENTER][BACK_RIGHT]+= M_SQRT1_2; }else if(out_ch_layout & AV_CH_SIDE_LEFT){ if(in_ch_layout & AV_CH_SIDE_LEFT){ matrix[ SIDE_LEFT][ BACK_LEFT]+= M_SQRT1_2; matrix[SIDE_RIGHT][BACK_RIGHT]+= M_SQRT1_2; }else{ matrix[ SIDE_LEFT][ BACK_LEFT]+= 1.0; matrix[SIDE_RIGHT][BACK_RIGHT]+= 1.0; } }else if(out_ch_layout & AV_CH_FRONT_LEFT){ if (matrix_encoding == AV_MATRIX_ENCODING_DOLBY) { matrix[FRONT_LEFT ][BACK_LEFT ] -= s->slev * M_SQRT1_2; matrix[FRONT_LEFT ][BACK_RIGHT] -= s->slev * M_SQRT1_2; matrix[FRONT_RIGHT][BACK_LEFT ] += s->slev * M_SQRT1_2; matrix[FRONT_RIGHT][BACK_RIGHT] += s->slev * M_SQRT1_2; } else if (matrix_encoding == AV_MATRIX_ENCODING_DPLII) { matrix[FRONT_LEFT ][BACK_LEFT ] -= s->slev * SQRT3_2; matrix[FRONT_LEFT ][BACK_RIGHT] -= s->slev * M_SQRT1_2; matrix[FRONT_RIGHT][BACK_LEFT ] += s->slev * M_SQRT1_2; matrix[FRONT_RIGHT][BACK_RIGHT] += s->slev * SQRT3_2; } else { matrix[ FRONT_LEFT][ BACK_LEFT] += s->slev; matrix[FRONT_RIGHT][BACK_RIGHT] += s->slev; } }else if(out_ch_layout & AV_CH_FRONT_CENTER){ matrix[ FRONT_CENTER][BACK_LEFT ]+= s->slev*M_SQRT1_2; matrix[ FRONT_CENTER][BACK_RIGHT]+= s->slev*M_SQRT1_2; }else av_assert0(0); } if(unaccounted & AV_CH_SIDE_LEFT){ if(out_ch_layout & AV_CH_BACK_LEFT){ /* if back channels do not exist in the input, just copy side channels to back channels, otherwise mix side into back */ if (in_ch_layout & AV_CH_BACK_LEFT) { matrix[BACK_LEFT ][SIDE_LEFT ] += M_SQRT1_2; matrix[BACK_RIGHT][SIDE_RIGHT] += M_SQRT1_2; } else { matrix[BACK_LEFT ][SIDE_LEFT ] += 1.0; matrix[BACK_RIGHT][SIDE_RIGHT] += 1.0; } }else if(out_ch_layout & AV_CH_BACK_CENTER){ matrix[BACK_CENTER][ SIDE_LEFT]+= M_SQRT1_2; matrix[BACK_CENTER][SIDE_RIGHT]+= M_SQRT1_2; }else if(out_ch_layout & AV_CH_FRONT_LEFT){ if (matrix_encoding == AV_MATRIX_ENCODING_DOLBY) { matrix[FRONT_LEFT ][SIDE_LEFT ] -= s->slev * M_SQRT1_2; matrix[FRONT_LEFT ][SIDE_RIGHT] -= s->slev * M_SQRT1_2; matrix[FRONT_RIGHT][SIDE_LEFT ] += s->slev * M_SQRT1_2; matrix[FRONT_RIGHT][SIDE_RIGHT] += s->slev * M_SQRT1_2; } else if (matrix_encoding == AV_MATRIX_ENCODING_DPLII) { matrix[FRONT_LEFT ][SIDE_LEFT ] -= s->slev * SQRT3_2; matrix[FRONT_LEFT ][SIDE_RIGHT] -= s->slev * M_SQRT1_2; matrix[FRONT_RIGHT][SIDE_LEFT ] += s->slev * M_SQRT1_2; matrix[FRONT_RIGHT][SIDE_RIGHT] += s->slev * SQRT3_2; } else { matrix[ FRONT_LEFT][ SIDE_LEFT] += s->slev; matrix[FRONT_RIGHT][SIDE_RIGHT] += s->slev; } }else if(out_ch_layout & AV_CH_FRONT_CENTER){ matrix[ FRONT_CENTER][SIDE_LEFT ]+= s->slev*M_SQRT1_2; matrix[ FRONT_CENTER][SIDE_RIGHT]+= s->slev*M_SQRT1_2; }else av_assert0(0); } if(unaccounted & AV_CH_FRONT_LEFT_OF_CENTER){ if(out_ch_layout & AV_CH_FRONT_LEFT){ matrix[ FRONT_LEFT][ FRONT_LEFT_OF_CENTER]+= 1.0; matrix[FRONT_RIGHT][FRONT_RIGHT_OF_CENTER]+= 1.0; }else if(out_ch_layout & AV_CH_FRONT_CENTER){ matrix[ FRONT_CENTER][ FRONT_LEFT_OF_CENTER]+= M_SQRT1_2; matrix[ FRONT_CENTER][FRONT_RIGHT_OF_CENTER]+= M_SQRT1_2; }else av_assert0(0); } /* mix LFE into front left/right or center */ if (unaccounted & AV_CH_LOW_FREQUENCY) { if (out_ch_layout & AV_CH_FRONT_CENTER) { matrix[FRONT_CENTER][LOW_FREQUENCY] += s->lfe_mix_level; } else if (out_ch_layout & AV_CH_FRONT_LEFT) { matrix[FRONT_LEFT ][LOW_FREQUENCY] += s->lfe_mix_level * M_SQRT1_2; matrix[FRONT_RIGHT][LOW_FREQUENCY] += s->lfe_mix_level * M_SQRT1_2; } else av_assert0(0); } for(out_i=i=0; i<64; i++){ double sum=0; int in_i=0; for(j=0; j<64; j++){ if (i < FF_ARRAY_ELEMS(matrix) && j < FF_ARRAY_ELEMS(matrix[0])) s->matrix[out_i][in_i]= matrix[i][j]; else s->matrix[out_i][in_i]= i == j && (in_ch_layout & out_ch_layout & (1ULL<<i)); sum += fabs(s->matrix[out_i][in_i]); if(in_ch_layout & (1ULL<<j)) in_i++; } maxcoef= FFMAX(maxcoef, sum); if(out_ch_layout & (1ULL<<i)) out_i++; } if(s->rematrix_volume < 0) maxcoef = -s->rematrix_volume; if (s->rematrix_maxval > 0) { maxval = s->rematrix_maxval; } else if ( av_get_packed_sample_fmt(s->out_sample_fmt) < AV_SAMPLE_FMT_FLT || av_get_packed_sample_fmt(s->int_sample_fmt) < AV_SAMPLE_FMT_FLT) { maxval = 1.0; } else maxval = INT_MAX; if(maxcoef > maxval || s->rematrix_volume < 0){ maxcoef /= maxval; for(i=0; i<SWR_CH_MAX; i++) for(j=0; j<SWR_CH_MAX; j++){ s->matrix[i][j] /= maxcoef; } } if(s->rematrix_volume > 0){ for(i=0; i<SWR_CH_MAX; i++) for(j=0; j<SWR_CH_MAX; j++){ s->matrix[i][j] *= s->rematrix_volume; } } for(i=0; i<av_get_channel_layout_nb_channels(out_ch_layout); i++){ for(j=0; j<av_get_channel_layout_nb_channels(in_ch_layout); j++){ av_log(NULL, AV_LOG_DEBUG, "%f ", s->matrix[i][j]); } av_log(NULL, AV_LOG_DEBUG, "\n"); } return 0; }


static int local_renameat(FsContext *ctx, V9fsPath *olddir, const char *old_name, V9fsPath *newdir, const char *new_name) { int ret; int odirfd, ndirfd; odirfd = local_opendir_nofollow(ctx, olddir->data); if (odirfd == -1) { return -1; } ndirfd = local_opendir_nofollow(ctx, newdir->data); if (ndirfd == -1) { close_preserve_errno(odirfd); return -1; } ret = renameat(odirfd, old_name, ndirfd, new_name); if (ret < 0) { goto out; } if (ctx->export_flags & V9FS_SM_MAPPED_FILE) { int omap_dirfd, nmap_dirfd; ret = mkdirat(ndirfd, VIRTFS_META_DIR, 0700); if (ret < 0 && errno != EEXIST) { goto err_undo_rename; } omap_dirfd = openat(odirfd, VIRTFS_META_DIR, O_RDONLY | O_DIRECTORY | O_NOFOLLOW); if (omap_dirfd == -1) { goto err; } nmap_dirfd = openat(ndirfd, VIRTFS_META_DIR, O_RDONLY | O_DIRECTORY | O_NOFOLLOW); if (nmap_dirfd == -1) { close_preserve_errno(omap_dirfd); goto err; } /* rename the .virtfs_metadata files */ ret = renameat(omap_dirfd, old_name, nmap_dirfd, new_name); close_preserve_errno(nmap_dirfd); close_preserve_errno(omap_dirfd); if (ret < 0 && errno != ENOENT) { goto err_undo_rename; } ret = 0; } goto out; err: ret = -1; err_undo_rename: renameat_preserve_errno(ndirfd, new_name, odirfd, old_name); out: close_preserve_errno(ndirfd); close_preserve_errno(odirfd); return ret; }


extract_VOMS_info( globus_gsi_cred_handle_t cred_handle, int verify_type, char **voname, char **firstfqan, char **quoted_DN_and_FQAN)
{

#if !defined(HAVE_EXT_VOMS)
	return 1;
#else

	int ret;
	struct vomsdata *voms_data = NULL;
	struct voms *voms_cert  = NULL;
	char *subject_name = NULL;
	char **fqan = NULL;
	int voms_err;
	int fqan_len = 0;
	char *retfqan = NULL;
	char *tmp_scan_ptr = NULL;

	STACK_OF(X509) *chain = NULL;
	X509 *cert = NULL;

	char* x509_fqan_delimiter = NULL;

	if ( activate_globus_gsi() != 0 ) {
		return 1;
	}

	// calling this function on something that doesn't have VOMS attributes
	// should return error 1.  when the config knob disables VOMS, behave the
	// same way.
	if (!param_boolean_int("USE_VOMS_ATTRIBUTES", 1)) {
		return 1;
	}

	ret = (*globus_gsi_cred_get_cert_chain_ptr)(cred_handle, &chain);
	if(ret != GLOBUS_SUCCESS) {
		ret = 10;
		goto end;
	}

	ret = (*globus_gsi_cred_get_cert_ptr)(cred_handle, &cert);
	if(ret != GLOBUS_SUCCESS) {
		ret = 11;
		goto end;
	}

	if ((*globus_gsi_cred_get_identity_name_ptr)(cred_handle, &subject_name)) {
		set_error_string( "unable to extract subject name" );
		ret = 12;
		goto end;
	}

	voms_data = (*VOMS_Init_ptr)(NULL, NULL);
	if (voms_data == NULL) {
		ret = 13;
		goto end;
	}

	if (verify_type == 0) {
		ret = (*VOMS_SetVerificationType_ptr)( VERIFY_NONE, voms_data, &voms_err );
		if (ret == 0) {
			(*VOMS_ErrorMessage_ptr)(voms_data, voms_err, NULL, 0);
			ret = voms_err;
			goto end;
		}
	}

	ret = (*VOMS_Retrieve_ptr)(cert, chain, RECURSE_CHAIN,
						voms_data, &voms_err);
	if (ret == 0) {
		if (voms_err == VERR_NOEXT) {
			// No VOMS extensions present
			ret = 1;
			goto end;
		} else {
			(*VOMS_ErrorMessage_ptr)(voms_data, voms_err, NULL, 0);
			ret = voms_err;
			goto end;
		}
	}

	// we only support one cert for now.  serializing and encoding all the
	// attributes is bad enough, i don't want to deal with doing this to
	// multiple certs.
	voms_cert = voms_data->data[0];

	// fill in the unquoted versions of things
	if(voname) {
		*voname = strdup(voms_cert->voname);
	}

	if(firstfqan) {
		*firstfqan = strdup(voms_cert->fqan[0]);
	}

	// only construct the quoted_DN_and_FQAN if needed
	if (quoted_DN_and_FQAN) {
		// get our delimiter and trim it
		if (!(x509_fqan_delimiter = param("X509_FQAN_DELIMITER"))) {
			x509_fqan_delimiter = strdup(",");
		}
		tmp_scan_ptr = trim_quotes(x509_fqan_delimiter);
		free(x509_fqan_delimiter);
		x509_fqan_delimiter = tmp_scan_ptr;

		// calculate the length
		fqan_len = 0;

		// start with the length of the quoted DN
		tmp_scan_ptr = quote_x509_string( subject_name );
		fqan_len += strlen( tmp_scan_ptr );
		free(tmp_scan_ptr);

		// add the length of delimiter plus each voms attribute
		for (fqan = voms_cert->fqan; fqan && *fqan; fqan++) {
			// delimiter
			fqan_len += strlen(x509_fqan_delimiter);

			tmp_scan_ptr = quote_x509_string( *fqan );
			fqan_len += strlen( tmp_scan_ptr );
			free(tmp_scan_ptr);
		}

		// now malloc enough room for the quoted DN, quoted attrs, delimiters, and
		// NULL terminator
		retfqan = (char*) malloc (fqan_len+1);
		*retfqan = 0;  // set null terminiator

		// reset length counter -- we use this for efficient appending.
		fqan_len = 0;

		// start with the quoted DN
		tmp_scan_ptr = quote_x509_string( subject_name );
		strcat(retfqan, tmp_scan_ptr);
		fqan_len += strlen( tmp_scan_ptr );
		free(tmp_scan_ptr);

		// add the delimiter plus each voms attribute
		for (fqan = voms_cert->fqan; fqan && *fqan; fqan++) {
			// delimiter
			strcat(&(retfqan[fqan_len]), x509_fqan_delimiter);
			fqan_len += strlen(x509_fqan_delimiter);

			tmp_scan_ptr = quote_x509_string( *fqan );
			strcat(&(retfqan[fqan_len]), tmp_scan_ptr);
			fqan_len += strlen( tmp_scan_ptr );
			free(tmp_scan_ptr);
		}

		*quoted_DN_and_FQAN = retfqan;
	}

	ret = 0;

end:
	free(subject_name);
	free(x509_fqan_delimiter);
	if (voms_data)
		(*VOMS_Destroy_ptr)(voms_data);
	if (cert)
		X509_free(cert);
	if(chain)
		sk_X509_pop_free(chain, X509_free);

	return ret;
#endif

}


mp_dss_print(netdissect_options *ndo,
             const u_char *opt, u_int opt_len, u_char flags)
{
        const struct mp_dss *mdss = (const struct mp_dss *) opt;

        if ((opt_len != mp_dss_len(mdss, 1) &&
             opt_len != mp_dss_len(mdss, 0)) || flags & TH_SYN)
                return 0;

        if (mdss->flags & MP_DSS_F)
                ND_PRINT((ndo, " fin"));

        opt += 4;
        if (mdss->flags & MP_DSS_A) {
                ND_PRINT((ndo, " ack "));
                if (mdss->flags & MP_DSS_a) {
                        ND_PRINT((ndo, "%" PRIu64, EXTRACT_64BITS(opt)));
                        opt += 8;
                } else {
                        ND_PRINT((ndo, "%u", EXTRACT_32BITS(opt)));
                        opt += 4;
                }
        }

        if (mdss->flags & MP_DSS_M) {
                ND_PRINT((ndo, " seq "));
                if (mdss->flags & MP_DSS_m) {
                        ND_PRINT((ndo, "%" PRIu64, EXTRACT_64BITS(opt)));
                        opt += 8;
                } else {
                        ND_PRINT((ndo, "%u", EXTRACT_32BITS(opt)));
                        opt += 4;
                }
                ND_PRINT((ndo, " subseq %u", EXTRACT_32BITS(opt)));
                opt += 4;
                ND_PRINT((ndo, " len %u", EXTRACT_16BITS(opt)));
                opt += 2;

                if (opt_len == mp_dss_len(mdss, 1))
                        ND_PRINT((ndo, " csum 0x%x", EXTRACT_16BITS(opt)));
        }
        return 1;
}


static int calculate_password(String *str, char *buffer)
{
  DBUG_ASSERT(str);
  if (str->length() == 0) // PASSWORD('') returns ''
    return 0;

  int buffer_len= 0;
  THD *thd= current_thd;
  int old_passwords= 0;
  if (thd)
    old_passwords= thd->variables.old_passwords;

#if defined(HAVE_OPENSSL)
  if (old_passwords == 2)
  {
    my_make_scrambled_password(buffer, str->ptr(),
                               str->length());
    buffer_len= (int) strlen(buffer) + 1;
  }
  else
#endif
  if (old_passwords == 0)
  {
    my_make_scrambled_password_sha1(buffer, str->ptr(),
                                    str->length());
    buffer_len= SCRAMBLED_PASSWORD_CHAR_LENGTH;
  }
  else
  if (old_passwords == 1)
  {
    my_make_scrambled_password_323(buffer, str->ptr(),
                                   str->length());
    buffer_len= SCRAMBLED_PASSWORD_CHAR_LENGTH_323;
  }
  return buffer_len;
}


PHP_NAMED_FUNCTION ( zif_locale_set_default ) {
 char * locale_name = NULL ;
 int len = 0 ;
 if ( zend_parse_parameters ( ZEND_NUM_ARGS ( ) TSRMLS_CC , "s" , & locale_name , & len ) == FAILURE ) {
 intl_error_set ( NULL , U_ILLEGAL_ARGUMENT_ERROR , "locale_set_default: unable to parse input params" , 0 TSRMLS_CC ) ;
 RETURN_FALSE ;
 }
 if ( len == 0 ) {
 locale_name = ( char * ) uloc_getDefault ( ) ;
 len = strlen ( locale_name ) ;
 }
 zend_alter_ini_entry ( LOCALE_INI_NAME , sizeof ( LOCALE_INI_NAME ) , locale_name , len , PHP_INI_USER , PHP_INI_STAGE_RUNTIME ) ;
 RETURN_TRUE ;
 }


static int sha256_password_authenticate(MYSQL_PLUGIN_VIO *vio,
                                        MYSQL_SERVER_AUTH_INFO *info)
{
  uchar *pkt;
  int pkt_len;
  char  *user_salt_begin;
  char  *user_salt_end;
  char scramble[SCRAMBLE_LENGTH + 1];
  char stage2[CRYPT_MAX_PASSWORD_SIZE + 1];
  String scramble_response_packet;
#if !defined(HAVE_YASSL)
  int cipher_length= 0;
  unsigned char plain_text[MAX_CIPHER_LENGTH];
  RSA *private_key= NULL;
  RSA *public_key= NULL;
#endif

  DBUG_ENTER("sha256_password_authenticate");

  generate_user_salt(scramble, SCRAMBLE_LENGTH + 1);

  /*
    Note: The nonce is split into 8 + 12 bytes according to
http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::HandshakeV10
    Native authentication sent 20 bytes + '\0' character = 21 bytes.
    This plugin must do the same to stay consistent with historical behavior
    if it is set to operate as a default plugin.
  */
  scramble[SCRAMBLE_LENGTH] = '\0';
  if (vio->write_packet(vio, (unsigned char *) scramble, SCRAMBLE_LENGTH + 1))
    DBUG_RETURN(CR_ERROR);

  /*
    After the call to read_packet() the user name will appear in
    mpvio->acl_user and info will contain current data.
  */
  if ((pkt_len= vio->read_packet(vio, &pkt)) == -1)
    DBUG_RETURN(CR_ERROR);

  /*
    If first packet is a 0 byte then the client isn't sending any password
    else the client will send a password.

    The original intention was that the password is a string[NUL] but this
    never got enforced properly so now we have to accept that an empty packet
    is a blank password, thus the check for pkt_len == 0 has to be made too.
  */
  if ((pkt_len == 0 || pkt_len == 1) && *pkt == 0)
  {
    info->password_used= PASSWORD_USED_NO;
    /*
      Send OK signal; the authentication might still be rejected based on
      host mask.
    */
    if (info->auth_string_length == 0)
      DBUG_RETURN(CR_OK);
    else
      DBUG_RETURN(CR_ERROR);
  }
  else
    info->password_used= PASSWORD_USED_YES;

  if (!my_vio_is_encrypted(vio))
  {
 #if !defined(HAVE_YASSL)
    /*
      Since a password is being used it must be encrypted by RSA since no
      other encryption is being active.
    */
    private_key= g_rsa_keys.get_private_key();
    public_key=  g_rsa_keys.get_public_key();

    /*
      Without the keys encryption isn't possible.
    */
    if (private_key == NULL || public_key == NULL)
    {
      my_plugin_log_message(&plugin_info_ptr, MY_ERROR_LEVEL,
        "Authentication requires either RSA keys or SSL encryption");
      DBUG_RETURN(CR_ERROR);
    }

    if ((cipher_length= g_rsa_keys.get_cipher_length()) > MAX_CIPHER_LENGTH)
    {
      my_plugin_log_message(&plugin_info_ptr, MY_ERROR_LEVEL,
        "RSA key cipher length of %u is too long. Max value is %u.",
        g_rsa_keys.get_cipher_length(), MAX_CIPHER_LENGTH);
      DBUG_RETURN(CR_ERROR);
    }

    /*
      Client sent a "public key request"-packet ?
      If the first packet is 1 then the client will require a public key before
      encrypting the password.
    */
    if (pkt_len == 1 && *pkt == 1)
    {
      uint pem_length= strlen(g_rsa_keys.get_public_key_as_pem());
      if (vio->write_packet(vio,
                            (unsigned char *)g_rsa_keys.get_public_key_as_pem(),
                            pem_length))
        DBUG_RETURN(CR_ERROR);
      /* Get the encrypted response from the client */
      if ((pkt_len= vio->read_packet(vio, &pkt)) == -1)
        DBUG_RETURN(CR_ERROR);
    }

    /*
      The packet will contain the cipher used. The length of the packet
      must correspond to the expected cipher length.
    */
    if (pkt_len != cipher_length)
      DBUG_RETURN(CR_ERROR);

    /* Decrypt password */
    RSA_private_decrypt(cipher_length, pkt, plain_text, private_key,
                        RSA_PKCS1_OAEP_PADDING);

    plain_text[cipher_length]= '\0'; // safety
    xor_string((char *) plain_text, cipher_length,
               (char *) scramble, SCRAMBLE_LENGTH);

    /*
      Set packet pointers and length for the hash digest function below
    */
    pkt= plain_text;
    pkt_len= strlen((char *) plain_text) + 1; // include \0 intentionally.

    if (pkt_len == 1)
      DBUG_RETURN(CR_ERROR);
#else
    DBUG_RETURN(CR_ERROR);
#endif
  } // if(!my_vio_is_encrypter())

  /* A password was sent to an account without a password */
  if (info->auth_string_length == 0)
    DBUG_RETURN(CR_ERROR);

  /*
    Fetch user authentication_string and extract the password salt
  */
  user_salt_begin= (char *) info->auth_string;
  user_salt_end= (char *) (info->auth_string + info->auth_string_length);
  if (extract_user_salt(&user_salt_begin, &user_salt_end) != CRYPT_SALT_LENGTH)
  {
    /* User salt is not correct */
    my_plugin_log_message(&plugin_info_ptr, MY_ERROR_LEVEL,
      "Password salt for user '%s' is corrupt.",
      info->user_name);
    DBUG_RETURN(CR_ERROR);
  }

  /* Create hash digest */
  my_crypt_genhash(stage2,
                     CRYPT_MAX_PASSWORD_SIZE,
                     (char *) pkt,
                     pkt_len-1,
                     (char *) user_salt_begin,
                     (const char **) 0);

  /* Compare the newly created hash digest with the password record */
  int result= memcmp(info->auth_string,
                     stage2,
                     info->auth_string_length);

  if (result == 0)
    DBUG_RETURN(CR_OK);

  DBUG_RETURN(CR_ERROR);
}


static int usb_console_setup(struct console *co, char *options)
{
	struct usbcons_info *info = &usbcons_info;
	int baud = 9600;
	int bits = 8;
	int parity = 'n';
	int doflow = 0;
	int cflag = CREAD | HUPCL | CLOCAL;
	char *s;
	struct usb_serial *serial;
	struct usb_serial_port *port;
	int retval;
	struct tty_struct *tty = NULL;
	struct ktermios dummy;

	if (options) {
		baud = simple_strtoul(options, NULL, 10);
		s = options;
		while (*s >= '0' && *s <= '9')
			s++;
		if (*s)
			parity = *s++;
		if (*s)
			bits   = *s++ - '0';
		if (*s)
			doflow = (*s++ == 'r');
	}

	/* Sane default */
	if (baud == 0)
		baud = 9600;

	switch (bits) {
	case 7:
		cflag |= CS7;
		break;
	default:
	case 8:
		cflag |= CS8;
		break;
	}
	switch (parity) {
	case 'o': case 'O':
		cflag |= PARODD;
		break;
	case 'e': case 'E':
		cflag |= PARENB;
		break;
	}
	co->cflag = cflag;

	/*
	 * no need to check the index here: if the index is wrong, console
	 * code won't call us
	 */
	port = usb_serial_port_get_by_minor(co->index);
	if (port == NULL) {
		/* no device is connected yet, sorry :( */
		pr_err("No USB device connected to ttyUSB%i\n", co->index);
		return -ENODEV;
	}
	serial = port->serial;

	retval = usb_autopm_get_interface(serial->interface);
	if (retval)
		goto error_get_interface;

	tty_port_tty_set(&port->port, NULL);

	info->port = port;

	++port->port.count;
	if (!tty_port_initialized(&port->port)) {
		if (serial->type->set_termios) {
			/*
			 * allocate a fake tty so the driver can initialize
			 * the termios structure, then later call set_termios to
			 * configure according to command line arguments
			 */
			tty = kzalloc(sizeof(*tty), GFP_KERNEL);
			if (!tty) {
				retval = -ENOMEM;
				goto reset_open_count;
			}
			kref_init(&tty->kref);
			tty->driver = usb_serial_tty_driver;
			tty->index = co->index;
			init_ldsem(&tty->ldisc_sem);
			spin_lock_init(&tty->files_lock);
			INIT_LIST_HEAD(&tty->tty_files);
			kref_get(&tty->driver->kref);
			__module_get(tty->driver->owner);
			tty->ops = &usb_console_fake_tty_ops;
			tty_init_termios(tty);
			tty_port_tty_set(&port->port, tty);
		}

		/* only call the device specific open if this
		 * is the first time the port is opened */
		retval = serial->type->open(NULL, port);
		if (retval) {
			dev_err(&port->dev, "could not open USB console port\n");
			goto fail;
		}

		if (serial->type->set_termios) {
			tty->termios.c_cflag = cflag;
			tty_termios_encode_baud_rate(&tty->termios, baud, baud);
			memset(&dummy, 0, sizeof(struct ktermios));
			serial->type->set_termios(tty, port, &dummy);

			tty_port_tty_set(&port->port, NULL);
			tty_kref_put(tty);
		}
		tty_port_set_initialized(&port->port, 1);
	}
	/* Now that any required fake tty operations are completed restore
	 * the tty port count */
	--port->port.count;
	/* The console is special in terms of closing the device so
	 * indicate this port is now acting as a system console. */
	port->port.console = 1;

	mutex_unlock(&serial->disc_mutex);
	return retval;

 fail:
	tty_port_tty_set(&port->port, NULL);
	tty_kref_put(tty);
 reset_open_count:
	port->port.count = 0;
	usb_autopm_put_interface(serial->interface);
 error_get_interface:
	usb_serial_put(serial);
	mutex_unlock(&serial->disc_mutex);
	return retval;
}


unpeer_node * create_unpeer_node ( address_node * addr ) {
 unpeer_node * my_node ;
 u_int u ;
 char * pch ;
 my_node = emalloc_zero ( sizeof ( * my_node ) ) ;
 pch = addr -> address ;
 while ( * pch && isdigit ( * pch ) ) pch ++ ;
 if ( ! * pch && 1 == sscanf ( addr -> address , "%u" , & u ) && u <= ASSOCID_MAX ) {
 my_node -> assocID = ( associd_t ) u ;
 destroy_address_node ( addr ) ;
 my_node -> addr = NULL ;
 }
 else {
 my_node -> assocID = 0 ;
 my_node -> addr = addr ;
 }
 return my_node ;
 }


static int dvbsub_parse_region_segment(AVCodecContext *avctx, const uint8_t *buf, int buf_size) { DVBSubContext *ctx = avctx->priv_data; const uint8_t *buf_end = buf + buf_size; int region_id, object_id; int av_unused version; DVBSubRegion *region; DVBSubObject *object; DVBSubObjectDisplay *display; int fill; int ret; if (buf_size < 10) return AVERROR_INVALIDDATA; region_id = *buf++; region = get_region(ctx, region_id); if (!region) { region = av_mallocz(sizeof(DVBSubRegion)); if (!region) return AVERROR(ENOMEM); region->id = region_id; region->version = -1; region->next = ctx->region_list; ctx->region_list = region; version = ((*buf)>>4) & 15; fill = ((*buf++) >> 3) & 1; region->width = AV_RB16(buf); buf += 2; region->height = AV_RB16(buf); buf += 2; if (region->width * region->height != region->buf_size) { av_free(region->pbuf); region->buf_size = region->width * region->height; region->pbuf = av_malloc(region->buf_size); if (!region->pbuf) { region->buf_size = region->width = region->height = 0; return AVERROR(ENOMEM); fill = 1; region->dirty = 0; region->depth = 1 << (((*buf++) >> 2) & 7); if(region->depth<2 || region->depth>8){ av_log(avctx, AV_LOG_ERROR, "region depth %d is invalid\n", region->depth); region->depth= 4; region->clut = *buf++; if (region->depth == 8) { region->bgcolor = *buf++; buf += 1; } else { buf += 1; if (region->depth == 4) region->bgcolor = (((*buf++) >> 4) & 15); else region->bgcolor = (((*buf++) >> 2) & 3); ff_dlog(avctx, "Region %d, (%dx%d)\n", region_id, region->width, region->height); if (fill) { memset(region->pbuf, region->bgcolor, region->buf_size); ff_dlog(avctx, "Fill region (%d)\n", region->bgcolor); delete_region_display_list(ctx, region); while (buf + 5 < buf_end) { object_id = AV_RB16(buf); buf += 2; object = get_object(ctx, object_id); if (!object) { object = av_mallocz(sizeof(DVBSubObject)); if (!object) return AVERROR(ENOMEM); object->id = object_id; object->next = ctx->object_list; ctx->object_list = object; object->type = (*buf) >> 6; display = av_mallocz(sizeof(DVBSubObjectDisplay)); if (!display) return AVERROR(ENOMEM); display->object_id = object_id; display->region_id = region_id; display->x_pos = AV_RB16(buf) & 0xfff; buf += 2; display->y_pos = AV_RB16(buf) & 0xfff; buf += 2; if ((object->type == 1 || object->type == 2) && buf+1 < buf_end) { display->fgcolor = *buf++; display->bgcolor = *buf++; display->region_list_next = region->display_list; region->display_list = display; display->object_list_next = object->display_list; object->display_list = display; return 0;


static unsigned int hb_icu_unicode_eastasian_width ( hb_unicode_funcs_t * ufuncs HB_UNUSED , hb_codepoint_t unicode , void * user_data HB_UNUSED ) {
 switch ( u_getIntPropertyValue ( unicode , UCHAR_EAST_ASIAN_WIDTH ) ) {
 case U_EA_WIDE : case U_EA_FULLWIDTH : return 2 ;
 case U_EA_NEUTRAL : case U_EA_AMBIGUOUS : case U_EA_HALFWIDTH : case U_EA_NARROW : return 1 ;
 }
 return 1 ;
 }


static void purple_add_buddy ( struct im_connection * ic , char * who , char * group ) {
 PurpleBuddy * pb ;
 PurpleGroup * pg = NULL ;
 struct purple_data * pd = ic -> proto_data ;
 if ( group && ! ( pg = purple_find_group ( group ) ) ) {
 pg = purple_group_new ( group ) ;
 purple_blist_add_group ( pg , NULL ) ;
 }
 pb = purple_buddy_new ( pd -> account , who , NULL ) ;
 purple_blist_add_buddy ( pb , NULL , pg , NULL ) ;
 purple_account_add_buddy ( pd -> account , pb ) ;
 purple_gg_buddylist_export ( pd -> account -> gc ) ;
 }


static void cmd_dcc_chat(const char *data, IRC_SERVER_REC *server)
{
	void *free_arg;
	CHAT_DCC_REC *dcc;
	IPADDR own_ip;
	GIOChannel *handle;
	GHashTable *optlist;
	int p_id;
	char *nick, host[MAX_IP_LEN];
	int port;

	g_return_if_fail(data != NULL);

	if (!cmd_get_params(data, &free_arg, 1 | PARAM_FLAG_OPTIONS,
			    "dcc chat", &optlist, &nick))
		return;

	if (*nick == '\0') {
		dcc = DCC_CHAT(dcc_find_request_latest(DCC_CHAT_TYPE));
		if (dcc != NULL) {
			if (!dcc_is_passive(dcc))
				dcc_chat_connect(dcc);
			else
				dcc_chat_passive(dcc);
		}
		cmd_params_free(free_arg);
		return;
	}

	dcc = dcc_chat_find_id(nick);
	if (dcc != NULL && dcc_is_waiting_user(dcc)) {
		if (!dcc_is_passive(dcc)) {
			/* found from dcc chat requests,
			   we're the connecting side */
			dcc_chat_connect(dcc);
		} else {
			/* We are accepting a passive DCC CHAT. */
			dcc_chat_passive(dcc);
		}
		return;
	}

	if (dcc != NULL && dcc_is_listening(dcc) &&
	    dcc->server == server) {
		/* sending request again even while old request is
		   still waiting, remove it. */
		dcc_destroy(DCC(dcc));
	}

	if (!IS_IRC_SERVER(server) || !server->connected)
		cmd_param_error(CMDERR_NOT_CONNECTED);

	dcc = dcc_chat_create(server, NULL, nick, "chat");

	if (g_hash_table_lookup(optlist, "passive") == NULL) {
		/* Standard DCC CHAT... let's listen for incoming connections */
		handle = dcc_listen(net_sendbuffer_handle(server->handle),
				    &own_ip, &port);
		if (handle == NULL)
			cmd_param_error(CMDERR_ERRNO);

		dcc->handle = handle;
		dcc->tagconn =
			g_input_add(dcc->handle, G_INPUT_READ,
				    (GInputFunction) dcc_chat_listen, dcc);

		/* send the chat request */
		signal_emit("dcc request send", 1, dcc);

		dcc_ip2str(&own_ip, host);
		irc_send_cmdv(server, "PRIVMSG %s :\001DCC CHAT CHAT %s %d\001",
			      nick, host, port);
	} else {
		/* Passive protocol... we want the other side to listen */
		/* send the chat request */
		dcc->port = 0;
		signal_emit("dcc request send", 1, dcc);

		/* generate a random id */
		p_id = rand() % 64;
		dcc->pasv_id = p_id;

		/* 16843009 is the long format of 1.1.1.1, we use a fake IP
		   since the other side shouldn't care of it: they will send
		   the address for us to connect to in the reply */
		irc_send_cmdv(server,
			      "PRIVMSG %s :\001DCC CHAT CHAT 16843009 0 %d\001",
			      nick, p_id);
	}
	cmd_params_free(free_arg);
}


static char *theme_format_compress_colors(THEME_REC *theme, const char *format)
{
	GString *str;
	char *ret;
	char last_fg, last_bg;

	str = g_string_new(NULL);

	last_fg = last_bg = '\0';
	while (*format != '\0') {
		if (*format == '$') {
                        /* $variable, skrip it entirely */
			theme_format_append_variable(str, &format);
                        last_fg = last_bg = '\0';
		} else if (*format != '%') {
			/* a normal character */
			g_string_append_c(str, *format);
			format++;
		} else {
			/* %format */
			format++;
			if (IS_OLD_FORMAT(*format, last_fg, last_bg)) {
				/* active color set again */
			} else if (IS_FGCOLOR_FORMAT(*format) &&
				   format[1] == '%' &&
				   IS_FGCOLOR_FORMAT(format[2]) &&
				   (*format != 'n' || format[2] == 'n')) {
				/* two fg colors in a row. bg colors are
				   so rare that we don't bother checking
				   them */
			} else {
				/* some format, add it */
				g_string_append_c(str, '%');
				g_string_append_c(str, *format);

				if (IS_FGCOLOR_FORMAT(*format))
					last_fg = *format;
				else if (*format == 'Z' || *format == 'X')
					last_fg = '\0';
				if (IS_BGCOLOR_FORMAT(*format))
					last_bg = *format;
				else if (*format == 'z' || *format == 'x')
					last_bg = '\0';
			}
			format++;
		}
	}

	ret = str->str;
        g_string_free(str, FALSE);
        return ret;
}


static void free_sconv_object ( struct archive_string_conv * sc ) {
 free ( sc -> from_charset ) ;
 free ( sc -> to_charset ) ;
 archive_string_free ( & sc -> utftmp ) ;
 # if HAVE_ICONV if ( sc -> cd != ( iconv_t ) - 1 ) iconv_close ( sc -> cd ) ;
 if ( sc -> cd_w != ( iconv_t ) - 1 ) iconv_close ( sc -> cd_w ) ;
 # endif free ( sc ) ;
 }


static void ctcp_msg_dcc_chat(IRC_SERVER_REC *server, const char *data,
			      const char *nick, const char *addr,
			      const char *target, CHAT_DCC_REC *chat)
{
        CHAT_DCC_REC *dcc;
	char **params;
	int paramcount;
        int passive, autoallow = FALSE;

        /* CHAT <unused> <address> <port> */
	/* CHAT <unused> <address> 0 <id> (DCC CHAT passive protocol) */
	params = g_strsplit(data, " ", -1);
	paramcount = g_strv_length(params);

	if (paramcount < 3) {
		g_strfreev(params);
		return;
	}
	passive = paramcount == 4 && g_strcmp0(params[2], "0") == 0;

	dcc = DCC_CHAT(dcc_find_request(DCC_CHAT_TYPE, nick, NULL));
	if (dcc != NULL) {
		if (dcc_is_listening(dcc)) {
			/* we requested dcc chat, they requested
			   dcc chat from us .. allow it. */
			dcc_destroy(DCC(dcc));
			autoallow = TRUE;
		} else if (!dcc_is_passive(dcc)) {
			/* we already have one dcc chat request
			   from this nick, remove it. */
			dcc_destroy(DCC(dcc));
		} else if (passive) {
			if (dcc->pasv_id != atoi(params[3])) {
				/* IDs don't match! */
				dcc_destroy(DCC(dcc));
			} else {
				/* IDs are ok! Update address and port and
				   connect! */
				dcc->target = g_strdup(target);
				dcc->port = atoi(params[2]);
				dcc_str2ip(params[1], &dcc->addr);
				net_ip2host(&dcc->addr, dcc->addrstr);

				dcc_chat_connect(dcc);
				g_strfreev(params);
				return;
			}
		}
	}

	dcc = dcc_chat_create(server, chat, nick, params[0]);
	dcc->target = g_strdup(target);
	dcc->port = atoi(params[2]);

	if (passive)
		dcc->pasv_id = atoi(params[3]);

	dcc_str2ip(params[1], &dcc->addr);
	net_ip2host(&dcc->addr, dcc->addrstr);

	signal_emit("dcc request", 2, dcc, addr);

	if (autoallow || DCC_CHAT_AUTOACCEPT(dcc, server, nick, addr)) {
		if (passive) {
			/* Passive DCC... let's set up a listening socket
			   and send reply back */
			dcc_chat_passive(dcc);
		} else {
			dcc_chat_connect(dcc);
		}
	}
	g_strfreev(params);
}


ikev1_hash_print(netdissect_options *ndo, u_char tpay _U_,
		 const struct isakmp_gen *ext, u_int item_len _U_,
		 const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_,
		 uint32_t proto _U_, int depth _U_)
{
	struct isakmp_gen e;

	ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_HASH)));

	ND_TCHECK(*ext);
	UNALIGNED_MEMCPY(&e, ext, sizeof(e));
	ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
	if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
		/* Print the entire payload in hex */
		ND_PRINT((ndo," "));
		if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
			goto trunc;
	}
	return (const u_char *)ext + ntohs(e.len);
trunc:
	ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_HASH)));
	return NULL;
}


static void * Type_ProfileSequenceId_Dup ( struct _cms_typehandler_struct * self , const void * Ptr , cmsUInt32Number n ) {
 return ( void * ) cmsDupProfileSequenceDescription ( ( cmsSEQ * ) Ptr ) ;
 cmsUNUSED_PARAMETER ( n ) ;
 cmsUNUSED_PARAMETER ( self ) ;
 }


ogg_read_header (AVFormatContext * s, AVFormatParameters * ap) { struct ogg *ogg = s->priv_data; ogg->curidx = -1; //linear headers seek from start if (ogg_get_headers (s) < 0){ return -1; } //linear granulepos seek from end ogg_get_length (s); //fill the extradata in the per codec callbacks return 0; }


CHAT_DCC_REC *dcc_chat_create(IRC_SERVER_REC *server,
				     CHAT_DCC_REC *chat,
				     const char *nick, const char *arg)
{
	CHAT_DCC_REC *dcc;

	dcc = g_new0(CHAT_DCC_REC, 1);
	dcc->orig_type = dcc->type = DCC_CHAT_TYPE;
	dcc->mirc_ctcp = settings_get_bool("dcc_mirc_ctcp");
        dcc->id = dcc_chat_get_new_id(nick);

	dcc_init_rec(DCC(dcc), server, chat, nick, arg);
        return dcc;
}


ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_,
		const struct isakmp_gen *ext,
		u_int item_len _U_, const u_char *ep _U_,
		uint32_t phase _U_, uint32_t doi _U_,
		uint32_t proto _U_, int depth _U_)
{
	struct isakmp_gen e;

	ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_VID)));

	ND_TCHECK(*ext);
	UNALIGNED_MEMCPY(&e, ext, sizeof(e));
	ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
	if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
		/* Print the entire payload in hex */
		ND_PRINT((ndo," "));
		if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
			goto trunc;
	}
	return (const u_char *)ext + ntohs(e.len);
trunc:
	ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_VID)));
	return NULL;
}


GET_DCC_REC *dcc_get_create(IRC_SERVER_REC *server, CHAT_DCC_REC *chat,
				   const char *nick, const char *arg)
{
	GET_DCC_REC *dcc;

	dcc = g_new0(GET_DCC_REC, 1);
	dcc->orig_type = module_get_uniq_id_str("DCC", "SEND");
	dcc->type = module_get_uniq_id_str("DCC", "GET");
	dcc->fhandle = -1;

	dcc_init_rec(DCC(dcc), server, chat, nick, arg);
        return dcc;
}


TEST_F ( FullscreenControllerStateUnitTest , DISABLED_ToggleTabWhenPendingBrowser ) {
 if ( FullscreenControllerStateTest : : IsWindowFullscreenStateChangedReentrant ( ) ) return ;
 AddTab ( browser ( ) , GURL ( url : : kAboutBlankURL ) ) ;
 ASSERT_NO_FATAL_FAILURE ( TransitionToState ( STATE_TO_BROWSER_FULLSCREEN_NO_CHROME ) ) << GetAndClearDebugLog ( ) ;
 ASSERT_TRUE ( InvokeEvent ( TAB_FULLSCREEN_TRUE ) ) << GetAndClearDebugLog ( ) ;
 ASSERT_TRUE ( InvokeEvent ( TAB_FULLSCREEN_FALSE ) ) << GetAndClearDebugLog ( ) ;
 ASSERT_TRUE ( InvokeEvent ( WINDOW_CHANGE ) ) << GetAndClearDebugLog ( ) ;
 }


ldns_str2rdf_str(ldns_rdf **rd, const char *str)
{
	uint8_t *data;
	size_t i, str_i, esc_i;

	if (strlen(str) > 255) {
		return LDNS_STATUS_INVALID_STR;
	}

	data = LDNS_XMALLOC(uint8_t, strlen(str) + 1);
        if(!data) return LDNS_STATUS_MEM_ERR;
	i = 1;

	for (str_i = 0; str_i < strlen(str); str_i++) {
		if (str[str_i] == '\\') {
			/* octet value or literal char */
			esc_i = (size_t) parse_escape((uint8_t*) &str[str_i], (uint8_t*) &data[i]);
			if (esc_i == 0) {
				LDNS_FREE(data);
				return LDNS_STATUS_SYNTAX_BAD_ESCAPE;
			}
			str_i += esc_i;
		} else {
			data[i] = (uint8_t) str[str_i];
		}
		i++;
	}
	data[0] = i - 1;
	*rd = ldns_rdf_new_frm_data(LDNS_RDF_TYPE_STR, i, data);

	LDNS_FREE(data);
	return *rd?LDNS_STATUS_OK:LDNS_STATUS_MEM_ERR;
}


static int slirp_smb(SlirpState* s, const char *exported_dir, struct in_addr vserver_addr) { static int instance; char smb_conf[128]; char smb_cmdline[128]; FILE *f; snprintf(s->smb_dir, sizeof(s->smb_dir), "/tmp/qemu-smb.%ld-%d", (long)getpid(), instance++); if (mkdir(s->smb_dir, 0700) < 0) { error_report("could not create samba server dir '%s'", s->smb_dir); return -1; } snprintf(smb_conf, sizeof(smb_conf), "%s/%s", s->smb_dir, "smb.conf"); f = fopen(smb_conf, "w"); if (!f) { slirp_smb_cleanup(s); error_report("could not create samba server configuration file '%s'", smb_conf); return -1; } fprintf(f, "[global]\n" "private dir=%s\n" "socket address=127.0.0.1\n" "pid directory=%s\n" "lock directory=%s\n" "state directory=%s\n" "log file=%s/log.smbd\n" "smb passwd file=%s/smbpasswd\n" "security = share\n" "[qemu]\n" "path=%s\n" "read only=no\n" "guest ok=yes\n", exported_dir ); fclose(f); snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s", CONFIG_SMBD_COMMAND, smb_conf); if (slirp_add_exec(s->slirp, 0, smb_cmdline, &vserver_addr, 139) < 0) { slirp_smb_cleanup(s); error_report("conflicting/invalid smbserver address"); return -1; } return 0; }


ikev2_ke_print(netdissect_options *ndo, u_char tpay,
		const struct isakmp_gen *ext,
		u_int item_len _U_, const u_char *ep _U_,
		uint32_t phase _U_, uint32_t doi _U_,
		uint32_t proto _U_, int depth _U_)
{
	struct ikev2_ke ke;
	const struct ikev2_ke *k;

	k = (const struct ikev2_ke *)ext;
	ND_TCHECK(*k);
	UNALIGNED_MEMCPY(&ke, ext, sizeof(ke));
	ikev2_pay_print(ndo, NPSTR(tpay), ke.h.critical);

	ND_PRINT((ndo," len=%u group=%s", ntohs(ke.h.len) - 8,
		  STR_OR_ID(ntohs(ke.ke_group), dh_p_map)));

	if (2 < ndo->ndo_vflag && 8 < ntohs(ke.h.len)) {
		ND_PRINT((ndo," "));
		if (!rawprint(ndo, (const uint8_t *)(k + 1), ntohs(ke.h.len) - 8))
			goto trunc;
	}
	return (const u_char *)ext + ntohs(ke.h.len);
trunc:
	ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
	return NULL;
}


TEST_P ( GLES2DecoderTestWithBlendEquationAdvanced , BlendBarrierKHRValidArgs ) {
 EXPECT_CALL ( * gl_ , BlendBarrierKHR ( ) ) ;
 SpecializedSetup < cmds : : BlendBarrierKHR , 0 > ( true ) ;
 cmds : : BlendBarrierKHR cmd ;
 cmd . Init ( ) ;
 EXPECT_EQ ( error : : kNoError , ExecuteCmd ( cmd ) ) ;
 EXPECT_EQ ( GL_NO_ERROR , GetGLError ( ) ) ;
 }


ldns_wire2rdf(ldns_rr *rr, const uint8_t *wire, size_t max, size_t *pos)
{
	size_t end;
	size_t cur_rdf_length;
	uint8_t rdf_index;
	uint8_t *data;
	uint16_t rd_length;
	ldns_rdf *cur_rdf = NULL;
	ldns_rdf_type cur_rdf_type;
	const ldns_rr_descriptor *descriptor = ldns_rr_descript(ldns_rr_get_type(rr));
	ldns_status status;

	if (*pos + 2 > max) {
		return LDNS_STATUS_PACKET_OVERFLOW;
	}

	rd_length = ldns_read_uint16(&wire[*pos]);
	*pos = *pos + 2;

	if (*pos + rd_length > max) {
		return LDNS_STATUS_PACKET_OVERFLOW;
	}

	end = *pos + (size_t) rd_length;

	for (rdf_index = 0;
	     rdf_index < ldns_rr_descriptor_maximum(descriptor); rdf_index++) {
		if (*pos >= end) {
			break;
		}
		cur_rdf_length = 0;

		cur_rdf_type = ldns_rr_descriptor_field_type(descriptor, rdf_index);
		/* handle special cases immediately, set length
		   for fixed length rdata and do them below */
		switch (cur_rdf_type) {
		case LDNS_RDF_TYPE_DNAME:
			status = ldns_wire2dname(&cur_rdf, wire, max, pos);
			LDNS_STATUS_CHECK_RETURN(status);
			break;
		case LDNS_RDF_TYPE_CLASS:
		case LDNS_RDF_TYPE_ALG:
		case LDNS_RDF_TYPE_INT8:
			cur_rdf_length = LDNS_RDF_SIZE_BYTE;
			break;
		case LDNS_RDF_TYPE_TYPE:
		case LDNS_RDF_TYPE_INT16:
		case LDNS_RDF_TYPE_CERT_ALG:
			cur_rdf_length = LDNS_RDF_SIZE_WORD;
			break;
		case LDNS_RDF_TYPE_TIME:
		case LDNS_RDF_TYPE_INT32:
		case LDNS_RDF_TYPE_A:
		case LDNS_RDF_TYPE_PERIOD:
			cur_rdf_length = LDNS_RDF_SIZE_DOUBLEWORD;
			break;
		case LDNS_RDF_TYPE_TSIGTIME:
		case LDNS_RDF_TYPE_EUI48:
			cur_rdf_length = LDNS_RDF_SIZE_6BYTES;
			break;
		case LDNS_RDF_TYPE_ILNP64:
		case LDNS_RDF_TYPE_EUI64:
			cur_rdf_length = LDNS_RDF_SIZE_8BYTES;
			break;
		case LDNS_RDF_TYPE_AAAA:
			cur_rdf_length = LDNS_RDF_SIZE_16BYTES;
			break;
		case LDNS_RDF_TYPE_STR:
		case LDNS_RDF_TYPE_NSEC3_SALT:
			/* len is stored in first byte
			 * it should be in the rdf too, so just
			 * copy len+1 from this position
			 */
			cur_rdf_length = ((size_t) wire[*pos]) + 1;
			break;
		case LDNS_RDF_TYPE_INT16_DATA:
			cur_rdf_length = (size_t) ldns_read_uint16(&wire[*pos]) + 2;
			break;
		case LDNS_RDF_TYPE_B32_EXT:
		case LDNS_RDF_TYPE_NSEC3_NEXT_OWNER:
			/* length is stored in first byte */
			cur_rdf_length = ((size_t) wire[*pos]) + 1;
			break;
		case LDNS_RDF_TYPE_APL:
		case LDNS_RDF_TYPE_B64:
		case LDNS_RDF_TYPE_HEX:
		case LDNS_RDF_TYPE_NSEC:
		case LDNS_RDF_TYPE_UNKNOWN:
		case LDNS_RDF_TYPE_SERVICE:
		case LDNS_RDF_TYPE_LOC:
		case LDNS_RDF_TYPE_WKS:
		case LDNS_RDF_TYPE_NSAP:
		case LDNS_RDF_TYPE_ATMA:
		case LDNS_RDF_TYPE_IPSECKEY:
		case LDNS_RDF_TYPE_TSIG:
		case LDNS_RDF_TYPE_NONE:
			/*
			 * Read to end of rr rdata
			 */
			cur_rdf_length = end - *pos;
			break;
		}

		/* fixed length rdata */
		if (cur_rdf_length > 0) {
			if (cur_rdf_length + *pos > end) {
				return LDNS_STATUS_PACKET_OVERFLOW;
			}
			data = LDNS_XMALLOC(uint8_t, rd_length);
			if (!data) {
				return LDNS_STATUS_MEM_ERR;
			}
			memcpy(data, &wire[*pos], cur_rdf_length);

			cur_rdf = ldns_rdf_new(cur_rdf_type, cur_rdf_length, data);
			*pos = *pos + cur_rdf_length;
		}

		if (cur_rdf) {
			ldns_rr_push_rdf(rr, cur_rdf);
			cur_rdf = NULL;
		}
	}

	return LDNS_STATUS_OK;
}


static inline int ipv6_addr_type ( const struct in6_addr * addr ) {
 return __ipv6_addr_type ( addr ) & 0xffff ;
 }


int seccomp_memory_deny_write_execute(void) {

        uint32_t arch;
        int r;

        SECCOMP_FOREACH_LOCAL_ARCH(arch) {
                _cleanup_(seccomp_releasep) scmp_filter_ctx seccomp = NULL;
                int filter_syscall = 0, block_syscall = 0, shmat_syscall = 0;

                log_debug("Operating on architecture: %s", seccomp_arch_to_string(arch));

                switch (arch) {

                case SCMP_ARCH_X86:
                        filter_syscall = SCMP_SYS(mmap2);
                        block_syscall = SCMP_SYS(mmap);
                        break;

                case SCMP_ARCH_PPC64:
                case SCMP_ARCH_PPC64LE:
                        filter_syscall = SCMP_SYS(mmap);

                        /* Note that shmat() isn't available, and the call is multiplexed through ipc().
                         * We ignore that here, which means there's still a way to get writable/executable
                         * memory, if an IPC key is mapped like this. That's a pity, but no total loss. */

                        break;

                case SCMP_ARCH_ARM:
                        filter_syscall = SCMP_SYS(mmap2); /* arm has only mmap2 */
                        shmat_syscall = SCMP_SYS(shmat);
                        break;

                case SCMP_ARCH_X86_64:
                case SCMP_ARCH_X32:
                case SCMP_ARCH_AARCH64:
                        filter_syscall = SCMP_SYS(mmap); /* amd64, x32, and arm64 have only mmap */
                        shmat_syscall = SCMP_SYS(shmat);
                        break;

                /* Please add more definitions here, if you port systemd to other architectures! */

#if !defined(__i386__) && !defined(__x86_64__) && !defined(__powerpc64__) && !defined(__arm__) && !defined(__aarch64__)
#warning "Consider adding the right mmap() syscall definitions here!"
#endif
                }

                /* Can't filter mmap() on this arch, then skip it */
                if (filter_syscall == 0)
                        continue;

                r = seccomp_init_for_arch(&seccomp, arch, SCMP_ACT_ALLOW);
                if (r < 0)
                        return r;

                r = add_seccomp_syscall_filter(seccomp, arch, filter_syscall,
                                               1,
                                               SCMP_A2(SCMP_CMP_MASKED_EQ, PROT_EXEC|PROT_WRITE, PROT_EXEC|PROT_WRITE));
                if (r < 0)
                        continue;

                if (block_syscall != 0) {
                        r = add_seccomp_syscall_filter(seccomp, arch, block_syscall, 0, (const struct scmp_arg_cmp){} );
                        if (r < 0)
                                continue;
                }

                r = add_seccomp_syscall_filter(seccomp, arch, SCMP_SYS(mprotect),
                                               1,
                                               SCMP_A2(SCMP_CMP_MASKED_EQ, PROT_EXEC, PROT_EXEC));
                if (r < 0)
                        continue;

                if (shmat_syscall != 0) {
                        r = add_seccomp_syscall_filter(seccomp, arch, SCMP_SYS(shmat),
                                                       1,
                                                       SCMP_A2(SCMP_CMP_MASKED_EQ, SHM_EXEC, SHM_EXEC));
                        if (r < 0)
                                continue;
                }

                r = seccomp_load(seccomp);
                if (IN_SET(r, -EPERM, -EACCES))
                        return r;
                if (r < 0)
                        log_debug_errno(r, "Failed to install MemoryDenyWriteExecute= rule for architecture %s, skipping: %m", seccomp_arch_to_string(arch));
        }

        return 0;
}


static av_cold int aacPlus_encode_init(AVCodecContext *avctx) { aacPlusAudioContext *s = avctx->priv_data; aacplusEncConfiguration *aacplus_cfg; /* number of channels */ if (avctx->channels < 1 || avctx->channels > 2) { av_log(avctx, AV_LOG_ERROR, "encoding %d channel(s) is not allowed\n", avctx->channels); return AVERROR(EINVAL); if (avctx->profile != FF_PROFILE_AAC_LOW && avctx->profile != FF_PROFILE_UNKNOWN) { av_log(avctx, AV_LOG_ERROR, "invalid AAC profile: %d, only LC supported\n", avctx->profile); return AVERROR(EINVAL); s->aacplus_handle = aacplusEncOpen(avctx->sample_rate, avctx->channels, &s->samples_input, &s->max_output_bytes); if (!s->aacplus_handle) { av_log(avctx, AV_LOG_ERROR, "can't open encoder\n"); return AVERROR(EINVAL); /* check aacplus version */ aacplus_cfg = aacplusEncGetCurrentConfiguration(s->aacplus_handle); aacplus_cfg->bitRate = avctx->bit_rate; aacplus_cfg->bandWidth = avctx->cutoff; aacplus_cfg->outputFormat = !(avctx->flags & CODEC_FLAG_GLOBAL_HEADER); aacplus_cfg->inputFormat = avctx->sample_fmt == AV_SAMPLE_FMT_FLT ? AACPLUS_INPUT_FLOAT : AACPLUS_INPUT_16BIT; if (!aacplusEncSetConfiguration(s->aacplus_handle, aacplus_cfg)) { av_log(avctx, AV_LOG_ERROR, "libaacplus doesn't support this output format!\n"); return AVERROR(EINVAL); avctx->frame_size = s->samples_input / avctx->channels; /* Set decoder specific info */ avctx->extradata_size = 0; if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) { unsigned char *buffer = NULL; unsigned long decoder_specific_info_size; if (aacplusEncGetDecoderSpecificInfo(s->aacplus_handle, &buffer, &decoder_specific_info_size) == 1) { avctx->extradata = av_malloc(decoder_specific_info_size + FF_INPUT_BUFFER_PADDING_SIZE); avctx->extradata_size = decoder_specific_info_size; memcpy(avctx->extradata, buffer, avctx->extradata_size); return 0;


static int get_fixed_point_scale_factor ( int other_size , int this_size ) {
 return ( other_size << REF_SCALE_SHIFT ) / this_size ;
 }


static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb, AVStream *st, MOVStreamContext *sc) { uint8_t codec_name[32]; int64_t stsd_start; unsigned int len; /* The first 16 bytes of the video sample description are already * read in ff_mov_read_stsd_entries() */ stsd_start = avio_tell(pb) - 16; avio_rb16(pb); /* version */ avio_rb16(pb); /* revision level */ avio_rb32(pb); /* vendor */ avio_rb32(pb); /* temporal quality */ avio_rb32(pb); /* spatial quality */ st->codecpar->width = avio_rb16(pb); /* width */ st->codecpar->height = avio_rb16(pb); /* height */ avio_rb32(pb); /* horiz resolution */ avio_rb32(pb); /* vert resolution */ avio_rb32(pb); /* data size, always 0 */ avio_rb16(pb); /* frames per samples */ len = avio_r8(pb); /* codec name, pascal string */ if (len > 31) len = 31; mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name)); if (len < 31) avio_skip(pb, 31 - len); if (codec_name[0]) av_dict_set(&st->metadata, "encoder", codec_name, 0); /* codec_tag YV12 triggers an UV swap in rawdec.c */ if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) { st->codecpar->codec_tag = MKTAG('I', '4', '2', '0'); st->codecpar->width &= ~1; st->codecpar->height &= ~1; } /* Flash Media Server uses tag H.263 with Sorenson Spark */ if (st->codecpar->codec_tag == MKTAG('H','2','6','3') && !memcmp(codec_name, "Sorenson H263", 13)) st->codecpar->codec_id = AV_CODEC_ID_FLV1; st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* depth */ avio_seek(pb, stsd_start, SEEK_SET); if (ff_get_qtpalette(st->codecpar->codec_id, pb, sc->palette)) { st->codecpar->bits_per_coded_sample &= 0x1F; sc->has_palette = 1; } }


static int read_entry(
	git_index_entry **out,
	size_t *out_size,
	git_index *index,
	const void *buffer,
	size_t buffer_size,
	const char *last)
{
	size_t path_length, entry_size;
	const char *path_ptr;
	struct entry_short source;
	git_index_entry entry = {{0}};
	bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP;
	char *tmp_path = NULL;

	if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size)
		return -1;

	/* buffer is not guaranteed to be aligned */
	memcpy(&source, buffer, sizeof(struct entry_short));

	entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds);
	entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds);
	entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds);
	entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds);
	entry.dev = ntohl(source.dev);
	entry.ino = ntohl(source.ino);
	entry.mode = ntohl(source.mode);
	entry.uid = ntohl(source.uid);
	entry.gid = ntohl(source.gid);
	entry.file_size = ntohl(source.file_size);
	git_oid_cpy(&entry.id, &source.oid);
	entry.flags = ntohs(source.flags);

	if (entry.flags & GIT_IDXENTRY_EXTENDED) {
		uint16_t flags_raw;
		size_t flags_offset;

		flags_offset = offsetof(struct entry_long, flags_extended);
		memcpy(&flags_raw, (const char *) buffer + flags_offset,
			sizeof(flags_raw));
		flags_raw = ntohs(flags_raw);

		memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw));
		path_ptr = (const char *) buffer + offsetof(struct entry_long, path);
	} else
		path_ptr = (const char *) buffer + offsetof(struct entry_short, path);

	if (!compressed) {
		path_length = entry.flags & GIT_IDXENTRY_NAMEMASK;

		/* if this is a very long string, we must find its
		 * real length without overflowing */
		if (path_length == 0xFFF) {
			const char *path_end;

			path_end = memchr(path_ptr, '\0', buffer_size);
			if (path_end == NULL)
				return -1;

			path_length = path_end - path_ptr;
		}

		entry_size = index_entry_size(path_length, 0, entry.flags);
		entry.path = (char *)path_ptr;
	} else {
		size_t varint_len;
		size_t strip_len = git_decode_varint((const unsigned char *)path_ptr,
						     &varint_len);
		size_t last_len = strlen(last);
		size_t prefix_len = last_len - strip_len;
		size_t suffix_len = strlen(path_ptr + varint_len);
		size_t path_len;

		if (varint_len == 0)
			return index_error_invalid("incorrect prefix length");

		GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len);
		GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1);
		tmp_path = git__malloc(path_len);
		GITERR_CHECK_ALLOC(tmp_path);

		memcpy(tmp_path, last, prefix_len);
		memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1);
		entry_size = index_entry_size(suffix_len, varint_len, entry.flags);
		entry.path = tmp_path;
	}

	if (entry_size == 0)
		return -1;

	if (INDEX_FOOTER_SIZE + entry_size > buffer_size)
		return -1;

	if (index_entry_dup(out, index, &entry) < 0) {
		git__free(tmp_path);
		return -1;
	}

	git__free(tmp_path);
	*out_size = entry_size;
	return 0;
}


int csum_len_for_type(int cst)
{
	switch (cst) {
	  case CSUM_NONE:
		return 1;
	  case CSUM_ARCHAIC:
		return 2;
	  case CSUM_MD4:
	  case CSUM_MD4_OLD:
	  case CSUM_MD4_BUSTED:
		return MD4_DIGEST_LEN;
	  case CSUM_MD5:
		return MD5_DIGEST_LEN;
	}
	return 0;
}


static void update_remote_info_refs ( struct remote_lock * lock ) {
 struct buffer buffer = {
 STRBUF_INIT , 0 }
 ;
 struct active_request_slot * slot ;
 struct slot_results results ;
 struct curl_slist * dav_headers ;
 remote_ls ( "refs/" , ( PROCESS_FILES | RECURSIVE ) , add_remote_info_ref , & buffer . buf ) ;
 if ( ! aborted ) {
 dav_headers = get_dav_token_headers ( lock , DAV_HEADER_IF ) ;
 slot = get_active_slot ( ) ;
 slot -> results = & results ;
 curl_setup_http ( slot -> curl , lock -> url , DAV_PUT , & buffer , fwrite_null ) ;
 curl_easy_setopt ( slot -> curl , CURLOPT_HTTPHEADER , dav_headers ) ;
 if ( start_active_slot ( slot ) ) {
 run_active_slot ( slot ) ;
 if ( results . curl_result != CURLE_OK ) {
 fprintf ( stderr , "PUT error: curl result=%d, HTTP code=%ld\n" , results . curl_result , results . http_code ) ;
 }
 }
 }
 strbuf_release ( & buffer . buf ) ;
 }


const char *avcodec_get_pix_fmt_name(enum PixelFormat pix_fmt) { if (pix_fmt < 0 || pix_fmt >= PIX_FMT_NB) return NULL; else return av_pix_fmt_descriptors[pix_fmt].name; }


void sum_init(int csum_type, int seed)
{
	char s[4];

	if (csum_type < 0)
		csum_type = parse_csum_name(NULL, 0);
	cursum_type = csum_type;

	switch (csum_type) {
	  case CSUM_MD5:
		md5_begin(&md);
		break;
	  case CSUM_MD4:
		mdfour_begin(&md);
		sumresidue = 0;
		break;
	  case CSUM_MD4_OLD:
	  case CSUM_MD4_BUSTED:
		mdfour_begin(&md);
		sumresidue = 0;
		SIVAL(s, 0, seed);
		sum_update(s, 4);
		break;
	  case CSUM_NONE:
		break;
	}
}


static void free_duplicate_context(MpegEncContext *s){ if(s==NULL) return; av_freep(&s->allocated_edge_emu_buffer); s->edge_emu_buffer= NULL; av_freep(&s->me.scratchpad); s->me.temp= s->rd_scratchpad= s->b_scratchpad= s->obmc_scratchpad= NULL; av_freep(&s->dct_error_sum); av_freep(&s->me.map); av_freep(&s->me.score_map); av_freep(&s->blocks); av_freep(&s->ac_val_base); s->block= NULL; }


void test_checkout_nasty__dotgit_alternate_data_stream(void)
{
	test_checkout_fails("refs/heads/dotgit_alternate_data_stream", ".git/dummy-file");
	test_checkout_fails("refs/heads/dotgit_alternate_data_stream", ".git::$INDEX_ALLOCATION/dummy-file");
}


GIT_INLINE(bool) only_spaces_and_dots(const char *path)
{
	const char *c = path;

	for (;; c++) {
		if (*c == '\0' || *c == ':')
			return true;
		if (*c != ' ' && *c != '.')
			return false;
	}

	return true;
}


static int milkymist_minimac2_init(SysBusDevice *sbd) { DeviceState *dev = DEVICE(sbd); MilkymistMinimac2State *s = MILKYMIST_MINIMAC2(dev); size_t buffers_size = TARGET_PAGE_ALIGN(3 * MINIMAC2_BUFFER_SIZE); sysbus_init_irq(sbd, &s->rx_irq); sysbus_init_irq(sbd, &s->tx_irq); memory_region_init_io(&s->regs_region, OBJECT(dev), &minimac2_ops, s, "milkymist-minimac2", R_MAX * 4); sysbus_init_mmio(sbd, &s->regs_region); /* register buffers memory */ memory_region_init_ram(&s->buffers, OBJECT(dev), "milkymist-minimac2.buffers", buffers_size, &error_abort); vmstate_register_ram_global(&s->buffers); s->rx0_buf = memory_region_get_ram_ptr(&s->buffers); s->rx1_buf = s->rx0_buf + MINIMAC2_BUFFER_SIZE; s->tx_buf = s->rx1_buf + MINIMAC2_BUFFER_SIZE; sysbus_init_mmio(sbd, &s->buffers); qemu_macaddr_default_if_unset(&s->conf.macaddr); s->nic = qemu_new_nic(&net_milkymist_minimac2_info, &s->conf, object_get_typename(OBJECT(dev)), dev->id, s); qemu_format_nic_info_str(qemu_get_queue(s->nic), s->conf.macaddr.a); return 0; }


void show_error_msg ( int m6resp , associd_t associd ) {
 if ( numhosts > 1 ) fprintf ( stderr , "server=%s " , currenthost ) ;
 switch ( m6resp ) {
 case CERR_BADFMT : fprintf ( stderr , "***Server reports a bad format request packet\n" ) ;
 break ;
 case CERR_PERMISSION : fprintf ( stderr , "***Server disallowed request (authentication?)\n" ) ;
 break ;
 case CERR_BADOP : fprintf ( stderr , "***Server reports a bad opcode in request\n" ) ;
 break ;
 case CERR_BADASSOC : fprintf ( stderr , "***Association ID %d unknown to server\n" , associd ) ;
 break ;
 case CERR_UNKNOWNVAR : fprintf ( stderr , "***A request variable unknown to the server\n" ) ;
 break ;
 case CERR_BADVALUE : fprintf ( stderr , "***Server indicates a request variable was bad\n" ) ;
 break ;
 case ERR_UNSPEC : fprintf ( stderr , "***Server returned an unspecified error\n" ) ;
 break ;
 case ERR_TIMEOUT : fprintf ( stderr , "***Request timed out\n" ) ;
 break ;
 case ERR_INCOMPLETE : fprintf ( stderr , "***Response from server was incomplete\n" ) ;
 break ;
 case ERR_TOOMUCH : fprintf ( stderr , "***Buffer size exceeded for returned data\n" ) ;
 break ;
 default : fprintf ( stderr , "***Server returns unknown error code %d\n" , m6resp ) ;
 }
 }


static int url_connect(struct variant *var, AVDictionary *opts) { AVDictionary *tmp = NULL; int ret; av_dict_copy(&tmp, opts, 0); av_opt_set_dict(var->input, &tmp); if ((ret = ffurl_connect(var->input, NULL)) < 0) { ffurl_close(var->input); var->input = NULL; } av_dict_free(&tmp); return ret; }


parse_user_name(char *user_input, char **ret_username)
{
	register char *ptr;
	register int index = 0;
	char username[PAM_MAX_RESP_SIZE];

	/* Set the default value for *ret_username */
	*ret_username = NULL;

	/*
	 * Set the initial value for username - this is a buffer holds
	 * the user name.
	 */
	bzero((void *)username, PAM_MAX_RESP_SIZE);

	/*
	 * The user_input is guaranteed to be terminated by a null character.
	 */
	ptr = user_input;

	/* Skip all the leading whitespaces if there are any. */
	while ((*ptr == ' ') || (*ptr == '\t'))
		ptr++;

	if (*ptr == '\0') {
		/*
		 * We should never get here since the user_input we got
		 * in pam_get_user() is not all whitespaces nor just "\0".
		 */
		return (PAM_BUF_ERR);
	}

	/*
	 * username will be the first string we get from user_input
	 * - we skip leading whitespaces and ignore trailing whitespaces
	 */
	while (*ptr != '\0') {
		if ((*ptr == ' ') || (*ptr == '\t') ||
		    (index >= PAM_MAX_RESP_SIZE)) {
			break;
		} else {
			username[index] = *ptr;
			index++;
			ptr++;
		}
	}

	/* ret_username will be freed in pam_get_user(). */
	if (index >= PAM_MAX_RESP_SIZE ||
	    (*ret_username = strdup(username)) == NULL)
		return (PAM_BUF_ERR);
	return (PAM_SUCCESS);
}


flac_buffer_copy (SF_PRIVATE *psf)
{	FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
	const FLAC__Frame *frame = pflac->frame ;
	const int32_t* const *buffer = pflac->wbuffer ;
	unsigned i = 0, j, offset, channels, len ;

	/*
	**	frame->header.blocksize is variable and we're using a constant blocksize
	**	of FLAC__MAX_BLOCK_SIZE.
	**	Check our assumptions here.
	*/
	if (frame->header.blocksize > FLAC__MAX_BLOCK_SIZE)
	{	psf_log_printf (psf, "Ooops : frame->header.blocksize (%d) > FLAC__MAX_BLOCK_SIZE (%d)\n", __func__, __LINE__, frame->header.blocksize, FLAC__MAX_BLOCK_SIZE) ;
		psf->error = SFE_INTERNAL ;
		return 0 ;
		} ;

	if (frame->header.channels > FLAC__MAX_CHANNELS)
		psf_log_printf (psf, "Ooops : frame->header.channels (%d) > FLAC__MAX_BLOCK_SIZE (%d)\n", __func__, __LINE__, frame->header.channels, FLAC__MAX_CHANNELS) ;

	channels = SF_MIN (frame->header.channels, FLAC__MAX_CHANNELS) ;

	if (pflac->ptr == NULL)
	{	/*
		**	Not sure why this code is here and not elsewhere.
		**	Removing it causes valgrind errors.
		*/
		pflac->bufferbackup = SF_TRUE ;
		for (i = 0 ; i < channels ; i++)
		{
			if (pflac->rbuffer [i] == NULL)
				pflac->rbuffer [i] = calloc (FLAC__MAX_BLOCK_SIZE, sizeof (int32_t)) ;

			memcpy (pflac->rbuffer [i], buffer [i], frame->header.blocksize * sizeof (int32_t)) ;
			} ;
		pflac->wbuffer = (const int32_t* const*) pflac->rbuffer ;

		return 0 ;
		} ;

	len = SF_MIN (pflac->len, frame->header.blocksize) ;

	switch (pflac->pcmtype)
	{	case PFLAC_PCM_SHORT :
			{	short *retpcm = (short*) pflac->ptr ;
				int shift = 16 - frame->header.bits_per_sample ;
				if (shift < 0)
				{	shift = abs (shift) ;
					for (i = 0 ; i < len && pflac->remain > 0 ; i++)
					{	offset = pflac->pos + i * channels ;

						if (pflac->bufferpos >= frame->header.blocksize)
							break ;

						if (offset + channels > pflac->len)
							break ;

						for (j = 0 ; j < channels ; j++)
							retpcm [offset + j] = buffer [j][pflac->bufferpos] >> shift ;
						pflac->remain -= channels ;
						pflac->bufferpos++ ;
						}
					}
				else
				{	for (i = 0 ; i < len && pflac->remain > 0 ; i++)
					{	offset = pflac->pos + i * channels ;

						if (pflac->bufferpos >= frame->header.blocksize)
							break ;

						if (offset + channels > pflac->len)
							break ;

						for (j = 0 ; j < channels ; j++)
							retpcm [offset + j] = ((uint16_t) buffer [j][pflac->bufferpos]) << shift ;

						pflac->remain -= channels ;
						pflac->bufferpos++ ;
						} ;
					} ;
				} ;
			break ;

		case PFLAC_PCM_INT :
			{	int *retpcm = (int*) pflac->ptr ;
				int shift = 32 - frame->header.bits_per_sample ;
				for (i = 0 ; i < len && pflac->remain > 0 ; i++)
				{	offset = pflac->pos + i * channels ;

					if (pflac->bufferpos >= frame->header.blocksize)
						break ;

					if (offset + channels > pflac->len)
						break ;

					for (j = 0 ; j < channels ; j++)
						retpcm [offset + j] = ((uint32_t) buffer [j][pflac->bufferpos]) << shift ;
					pflac->remain -= channels ;
					pflac->bufferpos++ ;
					} ;
				} ;
			break ;

		case PFLAC_PCM_FLOAT :
			{	float *retpcm = (float*) pflac->ptr ;
				float norm = (psf->norm_float == SF_TRUE) ? 1.0 / (1 << (frame->header.bits_per_sample - 1)) : 1.0 ;

				for (i = 0 ; i < len && pflac->remain > 0 ; i++)
				{	offset = pflac->pos + i * channels ;

					if (pflac->bufferpos >= frame->header.blocksize)
						break ;

					if (offset + channels > pflac->len)
						break ;

					for (j = 0 ; j < channels ; j++)
						retpcm [offset + j] = buffer [j][pflac->bufferpos] * norm ;
					pflac->remain -= channels ;
					pflac->bufferpos++ ;
					} ;
				} ;
			break ;

		case PFLAC_PCM_DOUBLE :
			{	double *retpcm = (double*) pflac->ptr ;
				double norm = (psf->norm_double == SF_TRUE) ? 1.0 / (1 << (frame->header.bits_per_sample - 1)) : 1.0 ;

				for (i = 0 ; i < len && pflac->remain > 0 ; i++)
				{	offset = pflac->pos + i * channels ;

					if (pflac->bufferpos >= frame->header.blocksize)
						break ;

					if (offset + channels > pflac->len)
						break ;

					for (j = 0 ; j < channels ; j++)
						retpcm [offset + j] = buffer [j][pflac->bufferpos] * norm ;
					pflac->remain -= channels ;
					pflac->bufferpos++ ;
					} ;
				} ;
			break ;

		default :
			return 0 ;
		} ;

	offset = i * channels ;
	pflac->pos += i * channels ;

	return offset ;
} /* flac_buffer_copy */


static void print_long_term ( H264Context * h ) {
 uint32_t i ;
 if ( h -> avctx -> debug & FF_DEBUG_MMCO ) {
 av_log ( h -> avctx , AV_LOG_DEBUG , "long term list:\n" ) ;
 for ( i = 0 ;
 i < 16 ;
 i ++ ) {
 Picture * pic = h -> long_ref [ i ] ;
 if ( pic ) {
 av_log ( h -> avctx , AV_LOG_DEBUG , "%d fn:%d poc:%d %p\n" , i , pic -> frame_num , pic -> poc , pic -> f . data [ 0 ] ) ;
 }
 }
 }
 }


id3_skip (SF_PRIVATE * psf)
{	unsigned char	buf [10] ;

	memset (buf, 0, sizeof (buf)) ;
	psf_binheader_readf (psf, "pb", 0, buf, 10) ;

	if (buf [0] == 'I' && buf [1] == 'D' && buf [2] == '3')
	{	int	offset = buf [6] & 0x7f ;
		offset = (offset << 7) | (buf [7] & 0x7f) ;
		offset = (offset << 7) | (buf [8] & 0x7f) ;
		offset = (offset << 7) | (buf [9] & 0x7f) ;

		psf_log_printf (psf, "ID3 length : %d\n--------------------\n", offset) ;

		/* Never want to jump backwards in a file. */
		if (offset < 0)
			return 0 ;

		/* Calculate new file offset and position ourselves there. */
		psf->fileoffset += offset + 10 ;
		psf_binheader_readf (psf, "p", psf->fileoffset) ;

		return 1 ;
		} ;

	return 0 ;
} /* id3_skip */


static void fz_drop_link_key ( fz_context * ctx , void * key_ ) {
 fz_link_key * key = ( fz_link_key * ) key_ ;
 if ( fz_drop_imp ( ctx , key , & key -> refs ) ) fz_free ( ctx , key ) ;
 }


aiff_read_chanmap (SF_PRIVATE * psf, unsigned dword)
{	const AIFF_CAF_CHANNEL_MAP * map_info ;
	unsigned channel_bitmap, channel_decriptions, bytesread ;
	int layout_tag ;

	bytesread = psf_binheader_readf (psf, "444", &layout_tag, &channel_bitmap, &channel_decriptions) ;

	if ((map_info = aiff_caf_of_channel_layout_tag (layout_tag)) == NULL)
		return 0 ;

	psf_log_printf (psf, "  Tag    : %x\n", layout_tag) ;
	if (map_info)
		psf_log_printf (psf, "  Layout : %s\n", map_info->name) ;

	if (bytesread < dword)
		psf_binheader_readf (psf, "j", dword - bytesread) ;

	if (map_info->channel_map != NULL)
	{	size_t chanmap_size = psf->sf.channels * sizeof (psf->channel_map [0]) ;

		free (psf->channel_map) ;

		if ((psf->channel_map = malloc (chanmap_size)) == NULL)
			return SFE_MALLOC_FAILED ;

		memcpy (psf->channel_map, map_info->channel_map, chanmap_size) ;
		} ;

	return 0 ;
} /* aiff_read_chanmap */


static int load_bitmap_entries_v1 ( struct bitmap_index * index ) {
 uint32_t i ;
 struct stored_bitmap * recent_bitmaps [ MAX_XOR_OFFSET ] = {
 NULL }
 ;
 for ( i = 0 ;
 i < index -> entry_count ;
 ++ i ) {
 int xor_offset , flags ;
 struct ewah_bitmap * bitmap = NULL ;
 struct stored_bitmap * xor_bitmap = NULL ;
 uint32_t commit_idx_pos ;
 const unsigned char * sha1 ;
 commit_idx_pos = read_be32 ( index -> map , & index -> map_pos ) ;
 xor_offset = read_u8 ( index -> map , & index -> map_pos ) ;
 flags = read_u8 ( index -> map , & index -> map_pos ) ;
 sha1 = nth_packed_object_sha1 ( index -> pack , commit_idx_pos ) ;
 bitmap = read_bitmap_1 ( index ) ;
 if ( ! bitmap ) return - 1 ;
 if ( xor_offset > MAX_XOR_OFFSET || xor_offset > i ) return error ( "Corrupted bitmap pack index" ) ;
 if ( xor_offset > 0 ) {
 xor_bitmap = recent_bitmaps [ ( i - xor_offset ) % MAX_XOR_OFFSET ] ;
 if ( xor_bitmap == NULL ) return error ( "Invalid XOR offset in bitmap pack index" ) ;
 }
 recent_bitmaps [ i % MAX_XOR_OFFSET ] = store_bitmap ( index , bitmap , sha1 , xor_bitmap , flags ) ;
 }
 return 0 ;
 }


header_gets (SF_PRIVATE *psf, char *ptr, int bufsize)
{	int		k ;

	for (k = 0 ; k < bufsize - 1 ; k++)
	{	if (psf->headindex < psf->headend)
		{	ptr [k] = psf->header [psf->headindex] ;
			psf->headindex ++ ;
			}
		else
		{	psf->headend += psf_fread (psf->header + psf->headend, 1, 1, psf) ;
			ptr [k] = psf->header [psf->headindex] ;
			psf->headindex = psf->headend ;
			} ;

		if (ptr [k] == '\n')
			break ;
		} ;

	ptr [k] = 0 ;

	return k ;
} /* header_gets */


static coroutine_fn int nbd_negotiate(NBDClient *client, Error **errp)
{
    char buf[8 + 8 + 8 + 128];
    int ret;
    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;

    /* 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, ending in NBD_OPT_EXPORT_NAME....
     */

    qio_channel_set_blocking(client->ioc, false, NULL);

    trace_nbd_negotiate_begin();
    memset(buf, 0, sizeof(buf));
    memcpy(buf, "NBDMAGIC", 8);

    oldStyle = client->exp != NULL && !client->tlscreds;
    if (oldStyle) {
        trace_nbd_negotiate_old_style(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);

        if (nbd_write(client->ioc, buf, sizeof(buf), errp) < 0) {
            error_prepend(errp, "write failed: ");
            return -EINVAL;
        }
    } else {
        stq_be_p(buf + 8, NBD_OPTS_MAGIC);
        stw_be_p(buf + 16, NBD_FLAG_FIXED_NEWSTYLE | NBD_FLAG_NO_ZEROES);

        if (nbd_write(client->ioc, buf, 18, errp) < 0) {
            error_prepend(errp, "write failed: ");
            return -EINVAL;
        }
        ret = nbd_negotiate_options(client, myflags, errp);
        if (ret != 0) {
            if (ret < 0) {
                error_prepend(errp, "option negotiation failed: ");
            }
            return ret;
        }
    }

    trace_nbd_negotiate_success();

    return 0;
}


xmlPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr input) {
    int ret;
    if (input == NULL) return(-1);

    if (xmlParserDebugEntities) {
	if ((ctxt->input != NULL) && (ctxt->input->filename))
	    xmlGenericError(xmlGenericErrorContext,
		    "%s(%d): ", ctxt->input->filename,
		    ctxt->input->line);
	xmlGenericError(xmlGenericErrorContext,
		"Pushing input %d : %.30s\n", ctxt->inputNr+1, input->cur);
    }
    ret = inputPush(ctxt, input);
    if (ctxt->instate == XML_PARSER_EOF)
        return(-1);
    GROW;
    return(ret);
}


bool memory_region_present(MemoryRegion *parent, hwaddr addr) { MemoryRegion *mr = memory_region_find(parent, addr, 1).mr; if (!mr) { return false; } memory_region_unref(mr); return true; }


static void term_eol(void) { term_cmd_buf_index = term_cmd_buf_size; }


dvi_document_file_exporter_end (EvFileExporter *exporter)
{
	gchar *command_line;
	gint exit_stat;
	GError *err = NULL;
	gboolean success;

	DviDocument *dvi_document = DVI_DOCUMENT(exporter);

	command_line = g_strdup_printf ("dvipdfm %s -o %s \"%s\"", /* dvipdfm -s 1,2,.., -o exporter_filename dvi_filename */
					dvi_document->exporter_opts->str,
					dvi_document->exporter_filename,
					dvi_document->context->filename);

	success = g_spawn_command_line_sync (command_line,
					     NULL,
					     NULL,
					     &exit_stat,
					     &err);

	g_free (command_line);

	if (success == FALSE) {
		g_warning ("Error: %s", err->message);
	} else if (!WIFEXITED(exit_stat) || WEXITSTATUS(exit_stat) != EXIT_SUCCESS){
		g_warning ("Error: dvipdfm does not end normally or exit with a failure status.");
	}

	if (err)
		g_error_free (err);
}


header_put_marker (SF_PRIVATE *psf, int x)
{	psf->header.ptr [psf->header.indx++] = (x >> 24) ;
	psf->header.ptr [psf->header.indx++] = (x >> 16) ;
	psf->header.ptr [psf->header.indx++] = (x >> 8) ;
	psf->header.ptr [psf->header.indx++] = x ;
} /* header_put_marker */


static void selinux_inode_free_security ( struct inode * inode ) {
 inode_free_security ( inode ) ;
 }