ChamaraVishwajithRajapaksha/Code-Vulnerability-FineTune huggingface dataset:
mpi_print (estream_t fp, gcry_mpi_t a, int mode)
{
  int n=0;

  if (!a)
    return es_fprintf (fp, "[MPI_NULL]");
  if (!mode)
    {
      unsigned int n1;
      n1 = gcry_mpi_get_nbits(a);
      n += es_fprintf (fp, "[%u bits]", n1);
    }
  else if (gcry_mpi_get_flag (a, GCRYMPI_FLAG_OPAQUE))
    {
      unsigned int nbits;
      unsigned char *p = gcry_mpi_get_opaque (a, &nbits);
      if (!p)
        n += es_fprintf (fp, "[invalid opaque value]");
      else
        {
          nbits = (nbits + 7)/8;
          for (; nbits; nbits--, p++)
            n += es_fprintf (fp, "%02X", *p);
        }
    }
  else
    {
      unsigned char *buffer;

      if (gcry_mpi_aprint (GCRYMPI_FMT_HEX, &buffer, NULL, a))
        BUG ();
      es_fputs (buffer, fp);
      n += strlen (buffer);
      gcry_free (buffer);
    }
  return n;
}
static void AuthPAMUserPwdRspFunc(rfbClientPtr cl)
{
  CARD32 userLen;
  CARD32 pwdLen;
  char userBuf[MAX_USER_LEN + 1];
  char pwdBuf[MAX_PWD_LEN + 1];
  int n;
  const char *emsg;

  n = ReadExact(cl, (char *)&userLen, sizeof(userLen));
  if (n <= 0) {
    if (n != 0)
      rfbLogPerror("AuthPAMUserPwdRspFunc: read error");
    rfbCloseClient(cl);
    return;
  }

  userLen = Swap32IfLE(userLen);
  n = ReadExact(cl, (char *)&pwdLen, sizeof(pwdLen));
  if (n <= 0) {
    if (n != 0)
      rfbLogPerror("AuthPAMUserPwdRspFunc: read error");
    rfbCloseClient(cl);
    return;
  }

  pwdLen = Swap32IfLE(pwdLen);
  if ((userLen > MAX_USER_LEN) || (pwdLen > MAX_PWD_LEN)) {
    rfbLogPerror("AuthPAMUserPwdRspFunc: excessively large user name or password in response");
    rfbCloseClient(cl);
    return;
  }

  n = ReadExact(cl, userBuf, userLen);
  if (n <= 0) {
    if (n != 0)
      rfbLogPerror("AuthPAMUserPwdRspFunc: error reading user name");
    rfbCloseClient(cl);
    return;
  }

  userBuf[userLen] = '\0';
  n = ReadExact(cl, pwdBuf, pwdLen);
  if (n <= 0) {
    if (n != 0)
      rfbLogPerror("AuthPAMUserPwdRspFunc: error reading password");
    rfbCloseClient(cl);
    return;
  }

  pwdBuf[pwdLen] = '\0';
  if (rfbAuthUserACL) {
    UserList *p = userACL;

    if (p == NULL)
      rfbLog("WARNING: User ACL is empty.  No users will be allowed to log in with Unix Login authentication.\n");

    while (p != NULL) {
      if (!strcmp(p->name, userBuf))
        break;
      p = p->next;
    }

    if (p == NULL) {
      rfbLog("User '%s' is not in the ACL and has been denied access\n",
             userBuf);
      rfbClientAuthFailed(cl, "User denied access");
      return;
    }

    cl->viewOnly = p->viewOnly;
  } else {
    struct passwd pbuf;
    struct passwd *pw;
    char buf[256];

    if (getpwuid_r(getuid(), &pbuf, buf, sizeof(buf), &pw) != 0)
      FatalError("AuthPAMUserPwdRspFunc: getpwuid_r failed: %s",
                 strerror(errno));

    if (strcmp(pbuf.pw_name, userBuf)) {
      rfbLog("User '%s' denied access (not the session owner)\n", userBuf);
      rfbLog("  Enable user ACL to grant access to other users.\n");
      rfbClientAuthFailed(cl, "User denied access");
      return;
    }
  }

  if (rfbPAMAuthenticate(cl, pamServiceName, userBuf, pwdBuf, &emsg))
    rfbClientAuthSucceeded(cl, rfbAuthUnixLogin);
  else
    rfbClientAuthFailed(cl, (char *)emsg);
}
str_to_key(unsigned char *str, unsigned char *key)
{
	int i;

	key[0] = str[0] >> 1;
	key[1] = ((str[0] & 0x01) << 6) | (str[1] >> 2);
	key[2] = ((str[1] & 0x03) << 5) | (str[2] >> 3);
	key[3] = ((str[2] & 0x07) << 4) | (str[3] >> 4);
	key[4] = ((str[3] & 0x0F) << 3) | (str[4] >> 5);
	key[5] = ((str[4] & 0x1F) << 2) | (str[5] >> 6);
	key[6] = ((str[5] & 0x3F) << 1) | (str[6] >> 7);
	key[7] = str[6] & 0x7F;
	for (i = 0; i < 8; i++)
		key[i] = (key[i] << 1);
}
void sqlite3Fts3SegReaderFinish(
  Fts3MultiSegReader *pCsr       /* Cursor object */
){
  if( pCsr ){
    int i;
    for(i=0; i<pCsr->nSegment; i++){
      sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
    }
    sqlite3_free(pCsr->apSegment);
    sqlite3_free(pCsr->aBuffer);

    pCsr->nSegment = 0;
    pCsr->apSegment = 0;
    pCsr->aBuffer = 0;
  }
}
void setDetails(absl::string_view details) {
      // It is probably a mistake to call setDetails() twice, so
      // assert that details_ is empty.
      ASSERT(details_.empty());

      details_ = details;
    }
int __ext4_journal_stop(const char *where, handle_t *handle)
{
	struct super_block *sb;
	int err;
	int rc;

	if (!ext4_handle_valid(handle)) {
		/*
		 * Do this here since we don't call jbd2_journal_stop() in
		 * no-journal mode.
		 */
		current->journal_info = NULL;
		return 0;
	}
	sb = handle->h_transaction->t_journal->j_private;
	err = handle->h_err;
	rc = jbd2_journal_stop(handle);

	if (!err)
		err = rc;
	if (err)
		__ext4_std_error(sb, where, err);
	return err;
}
GF_Err flxs_box_dump(GF_Box *a, FILE * trace)
{
	if (!a) return GF_BAD_PARAM;
	gf_isom_box_dump_start(a, "AdobeFlashAccessParamsBox", trace);
	gf_fprintf(trace, ">\n");
	gf_isom_box_dump_done("AdobeFlashAccessParamsBox", a, trace);
	return GF_OK;
}
static void tg3_rss_init_dflt_indir_tbl(struct tg3 *tp, u32 qcnt)
{
	int i;

	for (i = 0; i < TG3_RSS_INDIR_TBL_SIZE; i++)
		tp->rss_ind_tbl[i] = ethtool_rxfh_indir_default(i, qcnt);
}
void rtrs_clt_set_max_reconnect_attempts(struct rtrs_clt_sess *clt, int value)
{
	clt->max_reconnect_attempts = (unsigned int)value;
}
redisContext *redisConnectUnixWithTimeout(const char *path, const struct timeval tv) {
    redisOptions options = {0};
    REDIS_OPTIONS_SET_UNIX(&options, path);
    options.connect_timeout = &tv;
    return redisConnectWithOptions(&options);
}
static char *ParseXPMColor(char *color,MagickBooleanType search_start)
{
#define NumberTargets  6

  char
    *p,
    *r;

  const char
    *q;

  ssize_t
    i;

  static const char
    *const targets[NumberTargets] = { "c ", "g ", "g4 ", "m ", "b ", "s " };

  if (*color == '\0')
    return((char *) NULL);
  if (search_start != MagickFalse)
    {
      for (i=0; i < NumberTargets; i++)
      {
        p=color;
        for (q=targets[i]; *p != '\0'; p++)
        {
          if (*p == '\n')
            break;
          if (*p != *q)
            continue;
          if (isspace((int) ((unsigned char) (*(p-1)))) == 0)
            continue;
          r=p;
          for ( ; ; )
          {
            if (*q == '\0')
              return(p);
            if (*r++ != *q++)
              break;
          }
          q=targets[i];
        }
      }
      return((char *) NULL);
    }
  for (p=color+1; *p != '\0'; p++)
  {
    if (*p == '\n')
      break;
    if (isspace((int) ((unsigned char) (*(p-1)))) == 0)
      continue;
    if (isspace((int) ((unsigned char) (*p))) != 0)
      continue;
    for (i=0; i < NumberTargets; i++)
    {
      if ((*p == *targets[i]) && (*(p+1) == *(targets[i]+1)))
        return(p);
    }
  }
  return(p);
}
static char* cJSON_strdup( const char* str )
{
	size_t len;
	char* copy;

	len = strlen( str ) + 1;
	if ( ! ( copy = (char*) cJSON_malloc( len ) ) )
		return 0;
	memcpy( copy, str, len );
	return copy;
}
ComparisonOpModel(const TensorData& input1, const TensorData& input2,
                    TensorType input_type, BuiltinOperator op) {
    input1_ = AddInput(input1);
    input2_ = AddInput(input2);
    output_ = AddOutput(TensorType_BOOL);
    ConfigureBuiltinOp(op);
    BuildInterpreter({GetShape(input1_), GetShape(input2_)});
  }
void gf_isom_set_progress_callback(GF_ISOFile *file, void (*progress_cbk)(void *udta, u64 nb_done, u64 nb_total), void *progress_cbk_udta)
{
	if (file) {
		file->progress_cbk = progress_cbk;
		file->progress_cbk_udta = progress_cbk_udta;

	}
}
__fastcall TExternalConsole::TExternalConsole(
  const UnicodeString Instance, bool NoInteractiveInput)
{
  UnicodeString Name;
  Name = FORMAT(L"%s%s", (CONSOLE_EVENT_REQUEST, (Instance)));
  CheckHandle(FRequestEvent = OpenEvent(EVENT_ALL_ACCESS, false, Name.c_str()), L"Request event");
  Name = FORMAT(L"%s%s", (CONSOLE_EVENT_RESPONSE, (Instance)));
  CheckHandle(FResponseEvent = OpenEvent(EVENT_ALL_ACCESS, false, Name.c_str()), L"Response event");
  Name = FORMAT(L"%s%s", (CONSOLE_EVENT_CANCEL, (Instance)));
  CheckHandle(FCancelEvent = OpenEvent(EVENT_ALL_ACCESS, false, Name.c_str()), L"Cancel event");
  Name = FORMAT(L"%s%s", (CONSOLE_MAPPING, (Instance)));
  CheckHandle(FFileMapping = OpenFileMapping(FILE_MAP_ALL_ACCESS, false, Name.c_str()), L"File mapping");

  HANDLE Job = OpenJobObject(JOB_OBJECT_ASSIGN_PROCESS, FALSE,
    FORMAT(L"%s%s", (CONSOLE_JOB, Instance)).c_str());
  if (DebugAlwaysTrue(Job != NULL))
  {
    AssignProcessToJobObject(Job, GetCurrentProcess());
    // winscp.com/winscp.dll keeps the only reference to the job.
    // once it gets closed (because winscp.com if forcefully terminated),
    // we get terminated as well
    CloseHandle(Job);
  }

  TConsoleCommStruct * CommStruct = GetCommStruct();
  try
  {
    if (CommStruct->Version != TConsoleCommStruct::CurrentVersion)
    {
      throw Exception(FMTLOAD(EXTERNAL_CONSOLE_INCOMPATIBLE, (CommStruct->Version)));
    }

    CommStruct->Version = TConsoleCommStruct::CurrentVersionConfirmed;
  }
  __finally
  {
    FreeCommStruct(CommStruct);
  }

  // to break application event loop regularly during "watching for changes"
  // to allow user to abort it
  SetTimer(Application->Handle, 1, 500, NULL);

  FNoInteractiveInput = NoInteractiveInput;
  FMaxSend = 0;

  Init();
}
DEFUN (clear_ip_bgp_instance_all_ipv4_soft,
       clear_ip_bgp_instance_all_ipv4_soft_cmd,
       "clear ip bgp view WORD * ipv4 (unicast|multicast) soft",
       CLEAR_STR
       IP_STR
       BGP_STR
       "BGP view\n"
       "view name\n"
       "Clear all peers\n"
       "Address family\n"
       "Address Family Modifier\n"
       "Address Family Modifier\n"
       "Soft reconfig\n")
{
  if (strncmp (argv[1], "m", 1) == 0)
    return bgp_clear_vty (vty, NULL, AFI_IP, SAFI_MULTICAST, clear_all,
                          BGP_CLEAR_SOFT_BOTH, NULL);

  return bgp_clear_vty (vty, NULL, AFI_IP, SAFI_UNICAST, clear_all,
                        BGP_CLEAR_SOFT_BOTH, NULL);
}
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;
}
void CLASS sony_arw_load_raw()
{
  ushort huff[32770];
  static const ushort tab[18] = {0xf11, 0xf10, 0xe0f, 0xd0e, 0xc0d, 0xb0c, 0xa0b, 0x90a, 0x809,
                                 0x708, 0x607, 0x506, 0x405, 0x304, 0x303, 0x300, 0x202, 0x201};
  int i, c, n, col, row, sum = 0;

  huff[0] = 15;
  for (n = i = 0; i < 18; i++)
    FORC(32768 >> (tab[i] >> 8)) huff[++n] = tab[i];
  getbits(-1);
  for (col = raw_width; col--;)
  {
#ifdef LIBRAW_LIBRARY_BUILD
    checkCancel();
#endif
    for (row = 0; row < raw_height + 1; row += 2)
    {
      if (row == raw_height)
        row = 1;
      if ((sum += ljpeg_diff(huff)) >> 12)
        derror();
      if (row < height)
        RAW(row, col) = sum;
    }
  }
}
spell_enc(void)
{

    if (STRLEN(p_enc) < 60 && STRCMP(p_enc, "iso-8859-15") != 0)
	return p_enc;
    return (char_u *)"latin1";
}
SNC_io_parser<EW>::SNC_io_parser(std::istream& is, SNC_structure& W) :
  Base(W), in(is), out(std::cout) {
  W.clear();
  CGAL_assertion(W.is_empty());
  verbose = false;
}
HRESULT Http::HrFlushHeaders()
{
	HRESULT hr = hrSuccess;
	std::string strOutput, strConnection;
	char lpszChar[128];

	HrGetHeaderValue("Connection", &strConnection);
	// Add misc. headers
	HrResponseHeader("Server","Kopano");
	struct tm dummy;
	strftime(lpszChar, 127, "%a, %d %b %Y %H:%M:%S GMT", gmtime_safe(time(nullptr), &dummy));
	HrResponseHeader("Date", lpszChar);
	if (m_ulKeepAlive != 0 && strcasecmp(strConnection.c_str(), "keep-alive") == 0) {
		HrResponseHeader("Connection", "Keep-Alive");
		HrResponseHeader("Keep-Alive", stringify(m_ulKeepAlive));
	}
	else
	{
		HrResponseHeader("Connection", "close");
		hr = MAPI_E_END_OF_SESSION;
	}

	// create headers packet
	assert(m_ulRetCode != 0);
	if (m_ulRetCode == 0)
		HrResponseHeader(500, "Request handled incorrectly");
	ec_log_debug("> " + m_strRespHeader);
	strOutput += m_strRespHeader + "\r\n";
	m_strRespHeader.clear();
	for (const auto &h : m_lstHeaders) {
		ec_log_debug("> " + h);
		strOutput += h + "\r\n";
	}
	m_lstHeaders.clear();
	//as last line has a CRLF. The HrWriteLine adds one more CRLF.
	//this means the End of headder.
	m_lpChannel->HrWriteLine(strOutput);
	return hr;
}
static bool cpu_common_crash_occurred_needed(void *opaque)
{
    CPUState *cpu = opaque;

    return cpu->crash_occurred;
}
GF_Err href_box_read(GF_Box *s, GF_BitStream *bs)
{
	u32 len;
	GF_TextHyperTextBox*ptr = (GF_TextHyperTextBox*)s;
	ISOM_DECREASE_SIZE(ptr, 6) //including 2 length fields
	ptr->startcharoffset = gf_bs_read_u16(bs);
	ptr->endcharoffset = gf_bs_read_u16(bs);
	len = gf_bs_read_u8(bs);
	if (len) {
		ISOM_DECREASE_SIZE(ptr, len)
		ptr->URL = (char *) gf_malloc(sizeof(char) * (len+1));
		if (!ptr->URL) return GF_OUT_OF_MEM;
		gf_bs_read_data(bs, ptr->URL, len);
		ptr->URL[len] = 0;
	}
	len = gf_bs_read_u8(bs);
	if (len) {
		ISOM_DECREASE_SIZE(ptr, len)
		ptr->URL_hint = (char *) gf_malloc(sizeof(char) * (len+1));
		if (!ptr->URL_hint) return GF_OUT_OF_MEM;
		gf_bs_read_data(bs, ptr->URL_hint, len);
		ptr->URL_hint[len]= 0;
	}
	return GF_OK;
}
static struct page *pmd_to_page(pmd_t *pmd)
{
	unsigned long mask = ~(PTRS_PER_PMD * sizeof(pmd_t) - 1);
	return virt_to_page((void *)((unsigned long) pmd & mask));
}
ippGetResolution(
    ipp_attribute_t *attr,		/* I - IPP attribute */
    int             element,		/* I - Value number (0-based) */
    int             *yres,		/* O - Vertical/feed resolution */
    ipp_res_t       *units)		/* O - Units for resolution */
{
 /*
  * Range check input...
  */

  if (!attr || attr->value_tag != IPP_TAG_RESOLUTION ||
      element < 0 || element >= attr->num_values)
  {
    if (yres)
      *yres = 0;

    if (units)
      *units = (ipp_res_t)0;

    return (0);
  }

 /*
  * Return the value...
  */

  if (yres)
    *yres = attr->values[element].resolution.yres;

  if (units)
    *units = attr->values[element].resolution.units;

  return (attr->values[element].resolution.xres);
}
hostkey_method_ssh_ecdsa_initPEMFromMemory(LIBSSH2_SESSION * session,
                                         const char *privkeyfiledata,
                                         size_t privkeyfiledata_len,
                                         unsigned const char *passphrase,
                                         void **abstract)
{
    libssh2_ecdsa_ctx *ec_ctx = NULL;
    int ret;

    if(abstract != NULL && *abstract) {
        hostkey_method_ssh_ecdsa_dtor(session, abstract);
        *abstract = NULL;
    }

    ret = _libssh2_ecdsa_new_private_frommemory(&ec_ctx, session,
                                                privkeyfiledata,
                                                privkeyfiledata_len, passphrase);
    if(ret) {
        return -1;
    }

    if(abstract != NULL)
        *abstract = ec_ctx;

    return 0;
}
static inline unsigned int io_put_kbuf_comp(struct io_kiocb *req)
{
	lockdep_assert_held(&req->ctx->completion_lock);

	if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
		return 0;
	return __io_put_kbuf(req, &req->ctx->io_buffers_comp);
}
int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
{
    f->owner[0] = f->owner[1] = avctx;
    return ff_get_buffer(avctx, f->f, flags);
}
theme_adium_remove_mark_from_message (EmpathyThemeAdium *self,
				      guint32 id)
{
	WebKitDOMDocument *dom;
	WebKitDOMNodeList *nodes;
	gchar *class;
	GError *error = NULL;

	dom = webkit_web_view_get_dom_document (WEBKIT_WEB_VIEW (self));
	if (dom == NULL) {
		return;
	}

	class = g_strdup_printf (".x-empathy-message-id-%u", id);

	/* Get all nodes with focus class */
	nodes = webkit_dom_document_query_selector_all (dom, class, &error);
	g_free (class);

	if (nodes == NULL) {
		DEBUG ("Error getting focus nodes: %s",
			error ? error->message : "No error");
		g_clear_error (&error);
		return;
	}

	theme_adium_remove_focus_marks (self, nodes);
}
move_reading_point(struct archive_read *a, uint64_t offset)
{
	struct xar *xar;

	xar = (struct xar *)(a->format->data);
	if (xar->offset - xar->h_base != offset) {
		/* Seek forward to the start of file contents. */
		int64_t step;

		step = offset - (xar->offset - xar->h_base);
		if (step > 0) {
			step = __archive_read_consume(a, step);
			if (step < 0)
				return ((int)step);
			xar->offset += step;
		} else {
			int64_t pos = __archive_read_seek(a, offset, SEEK_SET);
			if (pos == ARCHIVE_FAILED) {
				archive_set_error(&(a->archive),
				    ARCHIVE_ERRNO_MISC,
				    "Cannot seek.");
				return (ARCHIVE_FAILED);
			}
			xar->offset = pos;
		}
	}
	return (ARCHIVE_OK);
}
void trex_box_del(GF_Box *s)
{
	GF_TrackExtendsBox *ptr = (GF_TrackExtendsBox *)s;
	if (ptr == NULL) return;
	gf_free(ptr);
static void mysql_prune_stmt_list(MYSQL *mysql)
{
  LIST *element= mysql->stmts;
  LIST *pruned_list= 0;

  for (; element; element= element->next)
  {
    MYSQL_STMT *stmt= (MYSQL_STMT *) element->data;
    if (stmt->state != MYSQL_STMT_INIT_DONE)
    {
      stmt->mysql= 0;
      stmt->last_errno= CR_SERVER_LOST;
      strmov(stmt->last_error, ER(CR_SERVER_LOST));
      strmov(stmt->sqlstate, unknown_sqlstate);
    }
    else
    {
      pruned_list= list_add(pruned_list, element);
    }
  }

  mysql->stmts= pruned_list;
}
config_trap(
	config_tree *ptree
	)
{
	addr_opts_node *curr_trap;
	attr_val *curr_opt;
	sockaddr_u addr_sock;
	sockaddr_u peeraddr;
	struct interface *localaddr;
	struct addrinfo hints;
	char port_text[8];
	settrap_parms *pstp;
	u_short port;
	int err_flag;
	int rc;

	/* silence warning about addr_sock potentially uninitialized */
	AF(&addr_sock) = AF_UNSPEC;

	curr_trap = HEAD_PFIFO(ptree->trap);
	for (; curr_trap != NULL; curr_trap = curr_trap->link) {
		err_flag = 0;
		port = 0;
		localaddr = NULL;

		curr_opt = HEAD_PFIFO(curr_trap->options);
		for (; curr_opt != NULL; curr_opt = curr_opt->link) {
			if (T_Port == curr_opt->attr) {
				if (curr_opt->value.i < 1 
				    || curr_opt->value.i > USHRT_MAX) {
					msyslog(LOG_ERR,
						"invalid port number "
						"%d, trap ignored", 
						curr_opt->value.i);
					err_flag = 1;
				}
				port = (u_short)curr_opt->value.i;
			}
			else if (T_Interface == curr_opt->attr) {
				/* Resolve the interface address */
				ZERO_SOCK(&addr_sock);
				if (getnetnum(curr_opt->value.s,
					      &addr_sock, 1, t_UNK) != 1) {
					err_flag = 1;
					break;
				}

				localaddr = findinterface(&addr_sock);

				if (NULL == localaddr) {
					msyslog(LOG_ERR,
						"can't find interface with address %s",
						stoa(&addr_sock));
					err_flag = 1;
				}
			}
		}

		/* Now process the trap for the specified interface
		 * and port number
		 */
		if (!err_flag) {
			if (!port)
				port = TRAPPORT;
			ZERO_SOCK(&peeraddr);
			rc = getnetnum(curr_trap->addr->address,
				       &peeraddr, 1, t_UNK);
			if (1 != rc) {
#ifndef WORKER
				msyslog(LOG_ERR,
					"trap: unable to use IP address %s.",
					curr_trap->addr->address);
#else	/* WORKER follows */
				/*
				 * save context and hand it off
				 * for name resolution.
				 */
				memset(&hints, 0, sizeof(hints));
				hints.ai_protocol = IPPROTO_UDP;
				hints.ai_socktype = SOCK_DGRAM;
				snprintf(port_text, sizeof(port_text),
					 "%u", port);
				hints.ai_flags = Z_AI_NUMERICSERV;
				pstp = emalloc_zero(sizeof(*pstp));
				if (localaddr != NULL) {
					hints.ai_family = localaddr->family;
					pstp->ifaddr_nonnull = 1;
					memcpy(&pstp->ifaddr,
					       &localaddr->sin,
					       sizeof(pstp->ifaddr));
				}
				rc = getaddrinfo_sometime(
					curr_trap->addr->address,
					port_text, &hints,
					INITIAL_DNS_RETRY,
					&trap_name_resolved,
					pstp);
				if (!rc)
					msyslog(LOG_ERR,
						"config_trap: getaddrinfo_sometime(%s,%s): %m",
						curr_trap->addr->address,
						port_text);
#endif	/* WORKER */
				continue;
			}
			/* port is at same location for v4 and v6 */
			SET_PORT(&peeraddr, port);

			if (NULL == localaddr)
				localaddr = ANY_INTERFACE_CHOOSE(&peeraddr);
			else
				AF(&peeraddr) = AF(&addr_sock);

			if (!ctlsettrap(&peeraddr, localaddr, 0,
					NTP_VERSION))
				msyslog(LOG_ERR,
					"set trap %s -> %s failed.",
					latoa(localaddr),
					stoa(&peeraddr));
		}
	}
}
static loff_t ext2_max_size(int bits)
{
	loff_t res = EXT2_NDIR_BLOCKS;
	int meta_blocks;
	loff_t upper_limit;

	/* This is calculated to be the largest file size for a
	 * dense, file such that the total number of
	 * sectors in the file, including data and all indirect blocks,
	 * does not exceed 2^32 -1
	 * __u32 i_blocks representing the total number of
	 * 512 bytes blocks of the file
	 */
	upper_limit = (1LL << 32) - 1;

	/* total blocks in file system block size */
	upper_limit >>= (bits - 9);


	/* indirect blocks */
	meta_blocks = 1;
	/* double indirect blocks */
	meta_blocks += 1 + (1LL << (bits-2));
	/* tripple indirect blocks */
	meta_blocks += 1 + (1LL << (bits-2)) + (1LL << (2*(bits-2)));

	upper_limit -= meta_blocks;
	upper_limit <<= bits;

	res += 1LL << (bits-2);
	res += 1LL << (2*(bits-2));
	res += 1LL << (3*(bits-2));
	res <<= bits;
	if (res > upper_limit)
		res = upper_limit;

	if (res > MAX_LFS_FILESIZE)
		res = MAX_LFS_FILESIZE;

	return res;
}
static void mptsas_process_port_facts(MPTSASState *s,
                                     MPIMsgPortFacts *req)
{
    MPIMsgPortFactsReply reply;

    mptsas_fix_port_facts_endianness(req);

    QEMU_BUILD_BUG_ON(MPTSAS_MAX_REQUEST_SIZE < sizeof(*req));
    QEMU_BUILD_BUG_ON(sizeof(s->doorbell_msg) < sizeof(*req));
    QEMU_BUILD_BUG_ON(sizeof(s->doorbell_reply) < sizeof(reply));

    memset(&reply, 0, sizeof(reply));
    reply.MsgLength  = sizeof(reply) / 4;
    reply.Function   = req->Function;
    reply.PortNumber = req->PortNumber;
    reply.MsgContext = req->MsgContext;

    if (req->PortNumber < MPTSAS_NUM_PORTS) {
        reply.PortType      = MPI_PORTFACTS_PORTTYPE_SAS;
        reply.MaxDevices    = MPTSAS_NUM_PORTS;
        reply.PortSCSIID    = MPTSAS_NUM_PORTS;
        reply.ProtocolFlags = MPI_PORTFACTS_PROTOCOL_LOGBUSADDR | MPI_PORTFACTS_PROTOCOL_INITIATOR;
    }

    mptsas_fix_port_facts_reply_endianness(&reply);
    mptsas_reply(s, (MPIDefaultReply *)&reply);
}
ADDRESS *rfc822_cpy_adr_real (ADDRESS *addr)
{
  ADDRESS *p = rfc822_new_address ();

#ifdef EXACT_ADDRESS
  p->val = safe_strdup (addr->val);
#endif
  p->personal = safe_strdup (addr->personal);
  p->mailbox = safe_strdup (addr->mailbox);
  p->group = addr->group;
  p->is_intl = addr->is_intl;
  p->intl_checked = addr->intl_checked;
  return p;
}
__tcf_get_next_proto(struct tcf_chain *chain, struct tcf_proto *tp)
{
	u32 prio = 0;

	ASSERT_RTNL();
	mutex_lock(&chain->filter_chain_lock);

	if (!tp) {
		tp = tcf_chain_dereference(chain->filter_chain, chain);
	} else if (tcf_proto_is_deleting(tp)) {
		/* 'deleting' flag is set and chain->filter_chain_lock was
		 * unlocked, which means next pointer could be invalid. Restart
		 * search.
		 */
		prio = tp->prio + 1;
		tp = tcf_chain_dereference(chain->filter_chain, chain);

		for (; tp; tp = tcf_chain_dereference(tp->next, chain))
			if (!tp->deleting && tp->prio >= prio)
				break;
	} else {
		tp = tcf_chain_dereference(tp->next, chain);
	}

	if (tp)
		tcf_proto_get(tp);

	mutex_unlock(&chain->filter_chain_lock);

	return tp;
}