示例#1
0
CERTSignedCrl* PK11_ImportCRL(PK11SlotInfo * slot, SECItem *derCRL, char *url,
    int type, void *wincx, PRInt32 importOptions, PRArenaPool* arena,
    PRInt32 decodeoptions)
{
    CERTSignedCrl *newCrl, *crl;
    SECStatus rv;
    CERTCertificate *caCert = NULL;

    newCrl = crl = NULL;

    do {
        newCrl = CERT_DecodeDERCrlWithFlags(arena, derCRL, type,
                                            decodeoptions);
        if (newCrl == NULL) {
            if (type == SEC_CRL_TYPE) {
                /* only promote error when the error code is too generic */
                if (PORT_GetError () == SEC_ERROR_BAD_DER)
                    PORT_SetError(SEC_ERROR_CRL_INVALID);
	        } else {
                PORT_SetError(SEC_ERROR_KRL_INVALID);
            }
            break;		
        }

        if (0 == (importOptions & CRL_IMPORT_BYPASS_CHECKS)){
            CERTCertDBHandle* handle = CERT_GetDefaultCertDB();
            PR_ASSERT(handle != NULL);
            caCert = CERT_FindCertByName (handle,
                                          &newCrl->crl.derName);
            if (caCert == NULL) {
                PORT_SetError(SEC_ERROR_UNKNOWN_ISSUER);	    
                break;
            }

            /* If caCert is a v3 certificate, make sure that it can be used for
               crl signing purpose */
            rv = CERT_CheckCertUsage (caCert, KU_CRL_SIGN);
            if (rv != SECSuccess) {
                break;
            }

            rv = CERT_VerifySignedData(&newCrl->signatureWrap, caCert,
                                       PR_Now(), wincx);
            if (rv != SECSuccess) {
                if (type == SEC_CRL_TYPE) {
                    PORT_SetError(SEC_ERROR_CRL_BAD_SIGNATURE);
                } else {
                    PORT_SetError(SEC_ERROR_KRL_BAD_SIGNATURE);
                }
                break;
            }
        }

	crl = crl_storeCRL(slot, url, newCrl, derCRL, type);

    } while (0);

    if (crl == NULL) {
	SEC_DestroyCrl (newCrl);
    }
    if (caCert) {
        CERT_DestroyCertificate(caCert);
    }
    return (crl);
}
示例#2
0
文件: hmac.c 项目: JasonCC/Openswan
void
hmac_init(struct hmac_ctx *ctx,
    const struct hash_desc *h,
    const u_char *key, size_t key_len)
{
#ifndef HAVE_LIBNSS
    int k;
#endif
    ctx->h = h;
    ctx->hmac_digest_len = h->hash_digest_len;

#ifdef HAVE_LIBNSS
    /* DBG(DBG_CRYPT, DBG_log("NSS: hmac init")); */
    SECStatus status;
    PK11SymKey *symkey=NULL, *tkey1=NULL;
    /* PK11SymKey *tkey1=NULL; */
    unsigned int klen;
    chunk_t hmac_opad, hmac_ipad, hmac_pad;

    memcpy(&symkey, key, key_len);
    klen =  PK11_GetKeyLength(symkey);

    hmac_opad = hmac_pads(HMAC_OPAD,HMAC_BUFSIZE);
    hmac_ipad = hmac_pads(HMAC_IPAD,HMAC_BUFSIZE);
    hmac_pad  = hmac_pads(0x00,HMAC_BUFSIZE-klen);

    if(klen > HMAC_BUFSIZE)
    {
	tkey1 = PK11_Derive_osw(symkey, nss_key_derivation_mech(h)
				, NULL, CKM_CONCATENATE_BASE_AND_DATA, CKA_DERIVE, 0);
    }
    else
    {
	tkey1 = symkey;
    }

    PK11SymKey *tkey2 = pk11_derive_wrapper_osw(tkey1, CKM_CONCATENATE_BASE_AND_DATA
				, hmac_pad,CKM_XOR_BASE_AND_DATA, CKA_DERIVE, HMAC_BUFSIZE);

    PR_ASSERT(tkey2!=NULL);
    ctx->ikey = pk11_derive_wrapper_osw(tkey2, CKM_XOR_BASE_AND_DATA
					, hmac_ipad,nss_hash_mech(h), CKA_DIGEST, 0);

    PR_ASSERT(ctx->ikey !=NULL);
    ctx->okey = pk11_derive_wrapper_osw(tkey2, CKM_XOR_BASE_AND_DATA
					, hmac_opad,nss_hash_mech(h), CKA_DIGEST, 0);

    PR_ASSERT(ctx->okey !=NULL);

    if(tkey1!=symkey) {
	PK11_FreeSymKey(tkey1);
    }
    PK11_FreeSymKey(tkey2);

    freeanychunk(hmac_opad);
    freeanychunk(hmac_ipad);
    freeanychunk(hmac_pad);
    ctx->ctx_nss = PK11_CreateDigestContext(nss_hash_oid(h));
    PR_ASSERT(ctx->ctx_nss!=NULL);

    status=PK11_DigestBegin(ctx->ctx_nss);
    PR_ASSERT(status==SECSuccess);

    status=PK11_DigestKey(ctx->ctx_nss, ctx->ikey);
    PR_ASSERT(status==SECSuccess);

#else

    /* Prepare the two pads for the HMAC */

    memset(ctx->buf1, '\0', HMAC_BUFSIZE);

    if (key_len <= HMAC_BUFSIZE)
    {
	memcpy(ctx->buf1, key, key_len);
    }
    else
    {
	h->hash_init(&ctx->hash_ctx);
	h->hash_update(&ctx->hash_ctx, key, key_len);
	h->hash_final(ctx->buf1, &ctx->hash_ctx);
    }

    memcpy(ctx->buf2, ctx->buf1, HMAC_BUFSIZE);

    for (k = 0; k < HMAC_BUFSIZE; k++)
    {
	ctx->buf1[k] ^= HMAC_IPAD;
	ctx->buf2[k] ^= HMAC_OPAD;
    }

    hmac_reinit(ctx);
#endif
}
/*
 * ar_send_res_msg
 *
 * When sending queries to nameservers listed in the resolv.conf file,
 * don't send a query to every one, but increase the number sent linearly
 * to match the number of resends. This increase only occurs if there are
 * multiple nameserver entries in the resolv.conf file.
 * The return value is the number of messages successfully sent to 
 * nameservers or -1 if no successful sends.
 */
int Resolver :: ar_send_res_msg(char *msg, int len, int rcount)
{
    int    i;
    int    sent = 0;

#ifdef HPUX
    /* VB: _res on HP is thread specific and needs to be initialized 
       on every thread */
    if (!(_res.options & RES_INIT)) {
        res_init();
    }
#endif
#ifdef Linux
    res_init_tls();
#endif

    if (!msg)
        return -1;

    if (_res.options & RES_PRIMARY)
        rcount = 1;
    rcount = (_res.nscount > rcount) ? rcount : _res.nscount;

    if (ar_vc)
    {
        ar_reinfo.re_sent++;
        sent++;
        if (PR_Send(afd, msg, len, 0, PR_INTERVAL_NO_TIMEOUT) == -1)
        {
            int errtmp = errno;
            PR_ASSERT(0);
            (void)PR_Close(afd);
            errno = errtmp;
            afd = NULL;
        }
    }
    else
        for (i = 0; i < rcount; i++)
        {
            struct sockaddr_in sin = _res.nsaddr_list[i];
            // XXX jpierre is this legal ???
            PRNetAddr *paddr = (PRNetAddr *)&sin;
#ifdef AIX
            PRNetAddr addr;
            /* For AIX struct sockaddr_in { uchar_t sin_len; 
             *                      sa_family_t sin_family;
             *                      in_port_t sin_port;
             * struct in_addr sin_addr; uchar_t sin_zero[8]; };
             * struct in_addr { in_addr_t s_addr; };
             * typedef uint32_t in_addr_t;
             *
             * In NSPR PRNetAddr is :
             *  union PRNetAddr { struct { PRUint16 family; 
             *                             char data[14]; } raw;
             *   struct { PRUint16 family; PRUint16 port; 
             *           PRUint32 ip; char pad[8]; } inet; ... }
             */
            PR_ASSERT(sin.sin_family == AF_INET);
            /* xxx strange when request is sent to IPV6 address 
             * then also address family is AF_INET 
             */
            memset(&addr, 0, sizeof(addr));
            addr.raw.family = sin.sin_family;
            addr.inet.family = sin.sin_family;
            addr.inet.port  = sin.sin_port;
            addr.inet.ip = sin.sin_addr.s_addr;
            memcpy(addr.inet.pad, sin.sin_zero, 8);
            paddr = &addr;
#endif
            if (PR_SendTo(afd, msg, len, 0,
                paddr,
                PR_INTERVAL_NO_TIMEOUT) == len) {
                ar_reinfo.re_sent++;
                sent++;
            }
            else
            {
                PR_ASSERT(0);
            }
        }
    return (sent) ? sent : -1;
}
示例#4
0
PRInt32 nsInstallPatch::Prepare()
{
    PRInt32 err;
    PRBool deleteOldSrc, flagExists, flagIsFile;
    
    if (mTargetFile == nsnull)
        return  nsInstall::INVALID_ARGUMENTS;

    mTargetFile->Exists(&flagExists);
    if (flagExists)
    {
        mTargetFile->IsFile(&flagIsFile);
        if (flagIsFile)
        {
            err = nsInstall::SUCCESS;
        }
        else
        {
            err = nsInstall::IS_DIRECTORY;
        }
    }
    else
    {
        err = nsInstall::DOES_NOT_EXIST;
    }

    if (err != nsInstall::SUCCESS)
    {   
        return err;
    }

    err =  mInstall->ExtractFileFromJar(*mJarLocation, mTargetFile, getter_AddRefs(mPatchFile));
   
    
    nsCOMPtr<nsIFile> fileName = nsnull;
    //nsVoidKey ikey( HashFilePath( nsFilePath(*mTargetFile) ) );//nsIFileXXX: nsFilePath?
    nsVoidKey ikey( HashFilePath( mTargetFile ));

    mInstall->GetPatch(&ikey, getter_AddRefs(fileName));

    if (fileName != nsnull) 
    {
        deleteOldSrc = PR_TRUE;
    } 
    else 
    {
        fileName     = mTargetFile;
        deleteOldSrc = PR_FALSE;
    }

    err = NativePatch(  fileName,           // the file to patch
                        mPatchFile,         // the patch that was extracted from the jarfile
                        getter_AddRefs(mPatchedFile));     // the new patched file
    
    // clean up extracted diff data file
    mPatchFile->Exists(&flagExists);
    if ( (mPatchFile != nsnull) && (flagExists) )
    {
        mPatchFile->Remove(PR_FALSE);
    }


    if (err != nsInstall::SUCCESS)
    {   
        // clean up tmp patched file since patching failed
      mPatchFile->Exists(&flagExists);
 		  if ((mPatchedFile != nsnull) && (flagExists))
      {
			    mPatchedFile->Remove(PR_FALSE);
      }
		return err;
    }

    PR_ASSERT(mPatchedFile != nsnull);
    mInstall->AddPatch(&ikey, mPatchedFile );

    if ( deleteOldSrc ) 
    {
    DeleteFileNowOrSchedule(fileName );
    }
  
    return err;
}
示例#5
0
static struct NumArg* BuildArgArray( const char *fmt, va_list ap, int* rv, struct NumArg* nasArray )
{
    int number = 0, cn = 0, i;
    const char* p;
    char  c;
    struct NumArg* nas;
    

    /*
    **	first pass:
    **	detemine how many legal % I have got, then allocate space
    */

    p = fmt;
    *rv = 0;
    i = 0;
    while( ( c = *p++ ) != 0 ){
	if( c != '%' )
	    continue;
	if( ( c = *p++ ) == '%' )	/* skip %% case */
	    continue;

	while( c != 0 ){
	    if( c > '9' || c < '0' ){
		if( c == '$' ){		/* numbered argument case */
		    if( i > 0 ){
			*rv = -1;
			return NULL;
		    }
		    number++;
		} else{			/* non-numbered argument case */
		    if( number > 0 ){
			*rv = -1;
			return NULL;
		    }
		    i = 1;
		}
		break;
	    }

	    c = *p++;
	}
    }

    if( number == 0 ){
	return NULL;
    }

    
    if( number > NAS_DEFAULT_NUM ){
	nas = (struct NumArg*)PR_MALLOC( number * sizeof( struct NumArg ) );
	if( !nas ){
	    *rv = -1;
	    return NULL;
	}
    } else {
	nas = nasArray;
    }

    for( i = 0; i < number; i++ ){
	nas[i].type = TYPE_UNKNOWN;
    }


    /*
    ** second pass:
    ** set nas[].type
    */

    p = fmt;
    while( ( c = *p++ ) != 0 ){
    	if( c != '%' )	continue;
	    c = *p++;
	if( c == '%' )	continue;

	cn = 0;
	while( c && c != '$' ){	    /* should imporve error check later */
	    cn = cn*10 + c - '0';
	    c = *p++;
	}

	if( !c || cn < 1 || cn > number ){
	    *rv = -1;
	    break;
        }

	/* nas[cn] starts from 0, and make sure nas[cn].type is not assigned */
        cn--;
	if( nas[cn].type != TYPE_UNKNOWN )
	    continue;

        c = *p++;

        /* width */
        if (c == '*') {
	    /* not supported feature, for the argument is not numbered */
	    *rv = -1;
	    break;
	}

	while ((c >= '0') && (c <= '9')) {
	    c = *p++;
	}

	/* precision */
	if (c == '.') {
	    c = *p++;
	    if (c == '*') {
	        /* not supported feature, for the argument is not numbered */
	        *rv = -1;
	        break;
	    }

	    while ((c >= '0') && (c <= '9')) {
		c = *p++;
	    }
	}

	/* size */
	nas[cn].type = TYPE_INTN;
	if (c == 'h') {
	    nas[cn].type = TYPE_INT16;
	    c = *p++;
	} else if (c == 'L') {
	    /* XXX not quite sure here */
	    nas[cn].type = TYPE_INT64;
	    c = *p++;
	} else if (c == 'l') {
	    nas[cn].type = TYPE_INT32;
	    c = *p++;
	    if (c == 'l') {
	        nas[cn].type = TYPE_INT64;
	        c = *p++;
	    }
	}

	/* format */
	switch (c) {
	case 'd':
	case 'c':
	case 'i':
	case 'o':
	case 'u':
	case 'x':
	case 'X':
	    break;

	case 'e':
	case 'f':
	case 'g':
	    nas[ cn ].type = TYPE_DOUBLE;
	    break;

	case 'p':
	    /* XXX should use cpp */
	    if (sizeof(void *) == sizeof(PRInt32)) {
		nas[ cn ].type = TYPE_UINT32;
	    } else if (sizeof(void *) == sizeof(PRInt64)) {
	        nas[ cn ].type = TYPE_UINT64;
	    } else if (sizeof(void *) == sizeof(PRIntn)) {
	        nas[ cn ].type = TYPE_UINTN;
	    } else {
	        nas[ cn ].type = TYPE_UNKNOWN;
	    }
	    break;

	case 'C':
	case 'S':
	case 'E':
	case 'G':
	    /* XXX not supported I suppose */
	    PR_ASSERT(0);
	    nas[ cn ].type = TYPE_UNKNOWN;
	    break;

	case 's':
	    nas[ cn ].type = TYPE_STRING;
	    break;

	case 'n':
	    nas[ cn ].type = TYPE_INTSTR;
	    break;

	default:
	    PR_ASSERT(0);
	    nas[ cn ].type = TYPE_UNKNOWN;
	    break;
	}

	/* get a legal para. */
	if( nas[ cn ].type == TYPE_UNKNOWN ){
	    *rv = -1;
	    break;
	}
    }


    /*
    ** third pass
    ** fill the nas[cn].ap
    */

    if( *rv < 0 ){
	if( nas != nasArray )
	    PR_DELETE( nas );
	return NULL;
    }

    cn = 0;
    while( cn < number ){
	if( nas[cn].type == TYPE_UNKNOWN ){
	    cn++;
	    continue;
	}

	switch( nas[cn].type ){
	case TYPE_INT16:
	case TYPE_UINT16:
	case TYPE_INTN:
	    nas[cn].u.i = va_arg( ap, int );
	    break;

	case TYPE_UINTN:
	    nas[cn].u.ui = va_arg( ap, unsigned int );
	    break;

	case TYPE_INT32:
	    nas[cn].u.i32 = va_arg( ap, PRInt32 );
	    break;

	case TYPE_UINT32:
	    nas[cn].u.ui32 = va_arg( ap, PRUint32 );
	    break;

	case TYPE_INT64:
	    nas[cn].u.ll = va_arg( ap, PRInt64 );
	    break;

	case TYPE_UINT64:
	    nas[cn].u.ull = va_arg( ap, PRUint64 );
	    break;

	case TYPE_STRING:
	    nas[cn].u.s = va_arg( ap, char* );
	    break;

	case TYPE_INTSTR:
	    nas[cn].u.ip = va_arg( ap, int* );
	    break;

	case TYPE_DOUBLE:
	    nas[cn].u.d = va_arg( ap, double );
	    break;

	default:
	    if( nas != nasArray )
		PR_DELETE( nas );
	    *rv = -1;
	    return NULL;
	}

	cn++;
    }


    return nas;
}
示例#6
0
static void pt_PostNotifies(PRLock *lock, PRBool unlock)
{
    PRIntn index, rv;
    _PT_Notified post;
    _PT_Notified *notified, *prev = NULL;
    /*
     * Time to actually notify any conditions that were affected
     * while the lock was held. Get a copy of the list that's in
     * the lock structure and then zero the original. If it's
     * linked to other such structures, we own that storage.
     */
    post = lock->notified;  /* a safe copy; we own the lock */

#if defined(DEBUG)
    memset(&lock->notified, 0, sizeof(_PT_Notified));  /* reset */
#else
    lock->notified.length = 0;  /* these are really sufficient */
    lock->notified.link = NULL;
#endif

    /* should (may) we release lock before notifying? */
    if (unlock)
    {
        rv = pthread_mutex_unlock(&lock->mutex);
        PR_ASSERT(0 == rv);
    }

    notified = &post;  /* this is where we start */
    do
    {
        for (index = 0; index < notified->length; ++index)
        {
            PRCondVar *cv = notified->cv[index].cv;
            PR_ASSERT(NULL != cv);
            PR_ASSERT(0 != notified->cv[index].times);
            if (-1 == notified->cv[index].times)
            {
                rv = pthread_cond_broadcast(&cv->cv);
                PR_ASSERT(0 == rv);
            }
            else
            {
                while (notified->cv[index].times-- > 0)
                {
                    rv = pthread_cond_signal(&cv->cv);
                    PR_ASSERT(0 == rv);
                }
            }
#if defined(DEBUG)
            pt_debug.cvars_notified += 1;
            if (0 > PR_AtomicDecrement(&cv->notify_pending))
            {
                pt_debug.delayed_cv_deletes += 1;
                PR_DestroyCondVar(cv);
            }
#else  /* defined(DEBUG) */
            if (0 > PR_AtomicDecrement(&cv->notify_pending))
                PR_DestroyCondVar(cv);
#endif  /* defined(DEBUG) */
        }
        prev = notified;
        notified = notified->link;
        if (&post != prev) PR_DELETE(prev);
    } while (NULL != notified);
}  /* pt_PostNotifies */
示例#7
0
/* Print the data for chosen primer pairs to stdout in "boulderio" format. */
void
print_boulder(int io_version,
              const p3_global_settings *pa,
              const seq_args *sa,
              const p3retval *retval,
              int   explain_flag) {
  /* The pointers to warning tag */
  char *warning;

  /* A place to put a string containing all error messages */
  pr_append_str *combined_retval_err = NULL;

  /* A small spacer; WARNING this is a fixed size
     buffer, but plenty bigger than
     log(2^64, 10), the longest character
     string that is needed for a 64 bit integer. */
  char suffix [100];

  /* Pointers for the primer set just printing */
  primer_rec *fwd, *rev, *intl;
 
  /* Variables only used for Primer Lists */
  int num_fwd, num_rev, num_int, num_pair, num_print;
  int print_fwd = 0;
  int print_rev = 0;
  int print_int = 0;
    
  /* Switches for printing this primer */
  int go_fwd = 0;
  int go_rev = 0;
  int go_int = 0;
    
  /* The number of loop cycles */
  int loop_max;
    
  /* That links to the included region */
  int i, incl_s = sa->incl_s;
    
  /* This deals with the renaming of the internal oligo */
  const char *new_oligo_name = "INTERNAL";
  const char *old_oligo_name = "INTERNAL_OLIGO";
  char *int_oligo = (char*) new_oligo_name;

  /* Check: are all pointers linked to something*/
  PR_ASSERT(NULL != pa);
  PR_ASSERT(NULL != sa);
    
  if (io_version == 3) {
    int_oligo = (char*) old_oligo_name;
  }
        
  /* Check if there are warnings and print them */
  if ((warning = p3_get_rv_and_gs_warnings(retval, pa)) != NULL) { 
    printf("PRIMER_WARNING=%s\n", warning);
    free(warning);
  }

  /* Check if a settings file was read an print its id 
   * Not needed anymore, we do this when we read the setting file. */
  /*
  if (pa->settings_file_id != NULL) { 
    printf("P3_FILE_ID=%s\n", pa->settings_file_id);
    free(warning);
  }
  */

  combined_retval_err = create_pr_append_str();
  if (NULL == combined_retval_err) exit(-2); /* Out of memory */

  if (pr_append_new_chunk_external(combined_retval_err, 
                                   retval->glob_err.data))
    exit(-2);

  if (pr_append_new_chunk_external(combined_retval_err, 
                                   retval->per_sequence_err.data)) 
    exit(-2);

  /* Check if there are errors, print and return */
  if (!pr_is_empty(combined_retval_err)) {
    print_boulder_error(pr_append_str_chars(combined_retval_err));
    destroy_pr_append_str(combined_retval_err);
    return;
  }
  destroy_pr_append_str(combined_retval_err);

  /* Get how many primers are in the array */
  num_fwd = retval->fwd.num_elem;
  num_rev = retval->rev.num_elem;
  num_int = retval->intl.num_elem;
  num_pair = retval->best_pairs.num_pairs;

  /* Prints out statistics about the primers */
  if (explain_flag) print_all_explain(pa, sa, retval, io_version);
    
  /* Print out the stop codon if a reading frame was specified */
  if (!PR_START_CODON_POS_IS_NULL(sa))
    printf("PRIMER_STOP_CODON_POSITION=%d\n", retval->stop_codon_pos);
    
  /* How often has the loop to be done? */
  if (retval->output_type == primer_list) {
    /* For Primer Lists: Figure out how many primers are in
     * the array that can be printed. If more than needed,
     * set it to the number requested. */

    /* Get how may primers should be printed */
    num_print = pa->num_return;
    /* Set how many primers will be printed */
    print_fwd = (num_print < num_fwd) ? num_print : num_fwd;
    print_rev = (num_print < num_rev) ? num_print : num_rev;
    print_int = (num_print < num_int) ? num_print : num_int;
    /* Get which list has to print most primers */
    loop_max = 0;
    if (loop_max < print_fwd) {
      loop_max = print_fwd;
    }
    if (loop_max < print_rev) {
      loop_max = print_rev;
    }
    if (loop_max < print_int) {
      loop_max = print_int;
    }
    /* Now the vars are there how often we have to go
     * through the loop and how many of each primer can
     * be printed. */
    num_pair = 0;
  } else {
    loop_max = num_pair;
    /* Set how many primers will be printed */
    print_fwd = num_pair;
    print_rev = num_pair;
    if (num_int != 0) {
      print_int = num_pair;
    }
  }

  if (io_version == 4) {
    printf("PRIMER_LEFT_NUM_RETURNED=%d\n", print_fwd);
    printf("PRIMER_RIGHT_NUM_RETURNED=%d\n",  print_rev);
    printf("PRIMER_%s_NUM_RETURNED=%d\n", int_oligo, print_int);
    printf("PRIMER_PAIR_NUM_RETURNED=%d\n", num_pair);
  }
  
  /* --------------------------------------- */
  /* Start of the loop printing all pairs or primers or oligos */
  for(i=0; i<loop_max; i++) {
    /* What needs to be printed */
    /* The conditions for primer lists */

    if (retval->output_type == primer_list) {
      /* Attach the selected primers to the pointers */
      fwd = &retval->fwd.oligo[i];
      rev = &retval->rev.oligo[i];
      intl = &retval->intl.oligo[i];
      /* Do fwd oligos have to be printed? */
      if ((pa->pick_left_primer) && (i < print_fwd)) {
        go_fwd = 1;
      } else {
        go_fwd = 0;
      }
      /* Do rev oligos have to be printed? */
      if ((pa->pick_right_primer) && (i < print_rev)) {
        go_rev = 1;
      } else {
        go_rev = 0;
      }
      /* Do int oligos have to be printed? */
      if ((pa->pick_internal_oligo) && (i < print_int)) {
        go_int = 1;
      } else {
        go_int = 0;
      }
    }  else {
      /* We will print primer pairs or pairs plus internal oligos */
      /* Get pointers to the primer_rec's that we will print */
      fwd  = retval->best_pairs.pairs[i].left;
      rev  = retval->best_pairs.pairs[i].right;
      intl = retval->best_pairs.pairs[i].intl;
      /* Pairs must have fwd and rev primers */
      go_fwd = 1;
      go_rev = 1;
      /* Do hyb oligos have to be printed? */
      if (pa->pick_internal_oligo == 1) {
        go_int = 1;
      } else {
        go_int = 0;
      }
    }
      
    /* Get the number for pimer counting in suffix[0] */
    if ((i == 0) && (io_version == 3) ){
      suffix[0] = '\0';
    } else { 
      sprintf(suffix, "_%d", i);
    }

    /* Print out the Pair Penalties */
    if (retval->output_type == primer_pairs) {
      if (io_version == 3) {
        printf("PRIMER_PAIR_PENALTY%s=%.4f\n", suffix,
               retval->best_pairs.pairs[i].pair_quality);
      } else {
        printf("PRIMER_PAIR%s_PENALTY=%f\n", suffix,
               retval->best_pairs.pairs[i].pair_quality);
      }
    }

    /* Print single primer penalty */
    if (go_fwd == 1)
      printf("PRIMER_LEFT%s_PENALTY=%f\n", suffix, fwd->quality);
    if (go_rev == 1)
      printf("PRIMER_RIGHT%s_PENALTY=%f\n", suffix, rev->quality);
    if (go_int == 1)
      printf("PRIMER_%s%s_PENALTY=%f\n", int_oligo, suffix, intl->quality);

    /* Print the oligo_problems */
    if (io_version == 4) {
      if (go_fwd == 1 && p3_ol_has_any_problem(fwd))
        printf("PRIMER_LEFT%s_PROBLEMS=%s\n", suffix, p3_get_ol_problem_string(fwd));
      if (go_rev == 1 && p3_ol_has_any_problem(rev))
        printf("PRIMER_RIGHT%s_PROBLEMS=%s\n", suffix, p3_get_ol_problem_string(rev));
      if (go_int == 1 && p3_ol_has_any_problem(intl))
        printf("PRIMER_%s%s_PROBLEMS=%s\n", int_oligo, suffix, p3_get_ol_problem_string(intl));
    }

    /* Print primer sequences. */
    if (go_fwd == 1)
      printf("PRIMER_LEFT%s_SEQUENCE=%s\n", suffix,
             pr_oligo_sequence(sa, fwd));
    if (go_rev == 1)
      printf("PRIMER_RIGHT%s_SEQUENCE=%s\n", suffix,
             pr_oligo_rev_c_sequence(sa, rev));
    if(go_int == 1)
      printf("PRIMER_%s%s_SEQUENCE=%s\n", int_oligo, suffix,
             pr_oligo_sequence(sa,intl));
        
    /* Print primer start and length */
    if (go_fwd == 1)
      printf("PRIMER_LEFT%s=%d,%d\n", suffix,
             fwd->start + incl_s + pa->first_base_index,
             fwd->length);
    if (go_rev == 1)
      printf("PRIMER_RIGHT%s=%d,%d\n", suffix,
             rev->start + incl_s + pa->first_base_index,
             rev->length);
    if (go_int == 1)
      printf("PRIMER_%s%s=%d,%d\n", int_oligo, suffix,
             intl->start + incl_s + pa->first_base_index,
             intl->length);

    /* Print primer Tm */
    if (go_fwd == 1)
      printf("PRIMER_LEFT%s_TM=%.3f\n", suffix, fwd->temp);
    if (go_rev == 1)
      printf("PRIMER_RIGHT%s_TM=%.3f\n", suffix, rev->temp);
    if (go_int == 1)
      printf("PRIMER_%s%s_TM=%.3f\n", int_oligo, suffix, intl->temp);

    /* Print primer GC content */
    if (go_fwd == 1)
      printf("PRIMER_LEFT%s_GC_PERCENT=%.3f\n", suffix, fwd->gc_content);
    if (go_rev == 1)
      printf("PRIMER_RIGHT%s_GC_PERCENT=%.3f\n", suffix, rev->gc_content);
    if (go_int == 1)
      printf("PRIMER_%s%s_GC_PERCENT=%.3f\n", int_oligo, suffix,
             intl->gc_content);

    /* Print primer self_any */
    if (go_fwd == 1 && pa->thermodynamic_alignment==0)
      printf("PRIMER_LEFT%s_SELF_ANY=%.2f\n", suffix,
             fwd->self_any);
    if (go_rev == 1 && pa->thermodynamic_alignment==0)
      printf("PRIMER_RIGHT%s_SELF_ANY=%.2f\n", suffix,
             rev->self_any);
    if (go_int == 1 && pa->thermodynamic_alignment==0)
      printf("PRIMER_%s%s_SELF_ANY=%.2f\n", int_oligo, suffix,
             intl->self_any);
     if (go_int == 1 && pa->thermodynamic_alignment==1)
       printf("PRIMER_%s%s_SELF_ANY_TH=%.2f\n", int_oligo, suffix,
	      intl->self_any);
    /* Print primer self_any thermodynamical approach */
     if (go_fwd == 1 && pa->thermodynamic_alignment==1)
       printf("PRIMER_LEFT%s_SELF_ANY_TH=%.2f\n", suffix,
	      fwd->self_any);
     if (go_rev == 1 && pa->thermodynamic_alignment==1)
       printf("PRIMER_RIGHT%s_SELF_ANY_TH=%.2f\n", suffix,
	      rev->self_any);
    /* Print primer self_end*/
    if (go_fwd == 1 && pa->thermodynamic_alignment==0)
      printf("PRIMER_LEFT%s_SELF_END=%.2f\n", suffix,
             fwd->self_end);
    if (go_rev == 1 && pa->thermodynamic_alignment==0)
      printf("PRIMER_RIGHT%s_SELF_END=%.2f\n", suffix,
             rev->self_end);
    if (go_int == 1 && pa->thermodynamic_alignment==0)
      printf("PRIMER_%s%s_SELF_END=%.2f\n", int_oligo, suffix,
             intl->self_end);
     if (go_int == 1 && pa->thermodynamic_alignment==1)
       printf("PRIMER_%s%s_SELF_END_TH=%.2f\n", int_oligo, suffix,
	      intl->self_end);
     /* Print primer self_end thermodynamical approach */
     if (go_fwd == 1 && pa->thermodynamic_alignment==1)
       printf("PRIMER_LEFT%s_SELF_END_TH=%.2f\n", suffix,
	      fwd->self_end);
     if (go_rev == 1 && pa->thermodynamic_alignment==1)
       printf("PRIMER_RIGHT%s_SELF_END_TH=%.2f\n", suffix,
	      rev->self_end);
     /* Print primer hairpin */
     if (go_fwd == 1 && pa->thermodynamic_alignment==1)
       printf("PRIMER_LEFT%s_HAIRPIN_TH=%.2f\n", suffix,
	      fwd->hairpin_th);
     if (go_rev == 1 && pa->thermodynamic_alignment==1)
       printf("PRIMER_RIGHT%s_HAIRPIN_TH=%.2f\n", suffix,
	      rev->hairpin_th);
     if (go_int == 1 && pa->thermodynamic_alignment==1)
       printf("PRIMER_%s%s_HAIRPIN_TH=%.2f\n", int_oligo, suffix,
	      intl->hairpin_th);
     /*Print out primer mispriming scores */
    if (io_version == 3) {
		if (seq_lib_num_seq(pa->p_args.repeat_lib) > 0) {
		  if (go_fwd == 1)
		    printf("PRIMER_LEFT%s_MISPRIMING_SCORE=%.2f, %s\n", suffix,
		           fwd->repeat_sim.score[fwd->repeat_sim.max],
		           fwd->repeat_sim.name);
		  if (go_rev == 1)
		    printf("PRIMER_RIGHT%s_MISPRIMING_SCORE=%.2f, %s\n", suffix,
		           rev->repeat_sim.score[rev->repeat_sim.max],
		           rev->repeat_sim.name);
		  if (retval->output_type == primer_pairs)
		    printf("PRIMER_PAIR%s_MISPRIMING_SCORE=%.2f, %s\n", suffix,
		           retval->best_pairs.pairs[i].repeat_sim,
		           retval->best_pairs.pairs[i].rep_name);
		}
    
		/* Print out internal oligo mispriming scores */
		if (go_int == 1 && seq_lib_num_seq(pa->o_args.repeat_lib) > 0)
		  printf("PRIMER_%s%s_MISHYB_SCORE=%.2f, %s\n", int_oligo, suffix,
		         intl->repeat_sim.score[intl->repeat_sim.max],
		         intl->repeat_sim.name);
    } else {
		if (seq_lib_num_seq(pa->p_args.repeat_lib) > 0) {
		  if (go_fwd == 1)
		    printf("PRIMER_LEFT%s_LIBRARY_MISPRIMING=%.2f, %s\n", suffix,
		           fwd->repeat_sim.score[fwd->repeat_sim.max],
		           fwd->repeat_sim.name);
		  if (go_rev == 1)
		    printf("PRIMER_RIGHT%s_LIBRARY_MISPRIMING=%.2f, %s\n", suffix,
		           rev->repeat_sim.score[rev->repeat_sim.max],
		           rev->repeat_sim.name);
		  if (retval->output_type == primer_pairs)
		    printf("PRIMER_PAIR%s_LIBRARY_MISPRIMING=%.2f, %s\n", suffix,
		           retval->best_pairs.pairs[i].repeat_sim,
		           retval->best_pairs.pairs[i].rep_name);
		}
		
		/* Print out internal oligo mispriming scores */
		if (go_int == 1 && seq_lib_num_seq(pa->o_args.repeat_lib) > 0)
		  printf("PRIMER_%s%s_LIBRARY_MISHYB=%.2f, %s\n", int_oligo, suffix,
		         intl->repeat_sim.score[intl->repeat_sim.max],
		         intl->repeat_sim.name);
    }

    /* If a sequence quality was provided, print it*/
    if (NULL != sa->quality){
      if (go_fwd == 1)
        printf("PRIMER_LEFT%s_MIN_SEQ_QUALITY=%d\n", suffix,
               fwd->seq_quality);
      if (go_rev == 1) 
        printf("PRIMER_RIGHT%s_MIN_SEQ_QUALITY=%d\n", suffix,
               rev->seq_quality);
      if (go_int == 1 && (retval->output_type == primer_list)) 
        printf("PRIMER_%s%s_MIN_SEQ_QUALITY=%d\n", int_oligo, suffix,
               intl->seq_quality);
      /* Has to be here and in primer pairs for backward compatibility */
    }
        
    /* Print position penalty, this is for backward compatibility */
    if (!_PR_DEFAULT_POSITION_PENALTIES(pa)
        || !PR_START_CODON_POS_IS_NULL(sa)){
      printf("PRIMER_LEFT%s_POSITION_PENALTY=%f\n", suffix,
             fwd->position_penalty);
      printf("PRIMER_RIGHT%s_POSITION_PENALTY=%f\n", suffix,
             rev->position_penalty);
    }
        
    /* Print primer end stability */
    if (go_fwd == 1)
      printf("PRIMER_LEFT%s_END_STABILITY=%.4f\n",
             suffix, fwd->end_stability);
    if (go_rev == 1)
      printf("PRIMER_RIGHT%s_END_STABILITY=%.4f\n",
             suffix, rev->end_stability);

    /* Print primer template mispriming */
    if ( (pa->thermodynamic_alignment == 0) && (go_fwd == 1) && 
         (oligo_max_template_mispriming(fwd) != ALIGN_SCORE_UNDEF))
      printf("PRIMER_LEFT%s_TEMPLATE_MISPRIMING=%.4f\n", suffix,
             oligo_max_template_mispriming(fwd));
    if ( (pa->thermodynamic_alignment == 0) && (go_rev == 1) && 
         (oligo_max_template_mispriming(rev) != ALIGN_SCORE_UNDEF))
      printf("PRIMER_RIGHT%s_TEMPLATE_MISPRIMING=%.4f\n", suffix,
             oligo_max_template_mispriming(rev));
     /* Print primer template mispriming thermodynamical approach*/
     if ( (pa->thermodynamic_alignment == 1) && (go_fwd == 1) &&
	  (oligo_max_template_mispriming_thermod(fwd) != ALIGN_SCORE_UNDEF))
       printf("PRIMER_LEFT%s_TEMPLATE_MISPRIMING_TH=%.4f\n", suffix,
	      oligo_max_template_mispriming_thermod(fwd));
     if ( (pa->thermodynamic_alignment == 1) && (go_rev == 1) &&
	  (oligo_max_template_mispriming_thermod(rev) != ALIGN_SCORE_UNDEF))
       printf("PRIMER_RIGHT%s_TEMPLATE_MISPRIMING_TH=%.4f\n", suffix,
	      oligo_max_template_mispriming_thermod(rev));
     /************************************************************************************/
     /* Print the pair parameters*/
    if (retval->output_type == primer_pairs) {
      if (go_int == 1 && NULL != sa->quality) /* FIX ME - Uptate the tests */
        printf("PRIMER_%s%s_MIN_SEQ_QUALITY=%d\n", int_oligo,
               suffix, intl->seq_quality);
      /* Print pair comp_any */
       if(pa->thermodynamic_alignment==0)
	 printf("PRIMER_PAIR%s_COMPL_ANY=%.2f\n", suffix,
		retval->best_pairs.pairs[i].compl_any);
       if(pa->thermodynamic_alignment==1)
	 printf("PRIMER_PAIR%s_COMPL_ANY_TH=%.2f\n", suffix,
		retval->best_pairs.pairs[i].compl_any);
       /* Print pair comp_end */
       if(pa->thermodynamic_alignment==0)
	 printf("PRIMER_PAIR%s_COMPL_END=%.2f\n", suffix,
		retval->best_pairs.pairs[i].compl_end);
       if(pa->thermodynamic_alignment==1)
	 printf("PRIMER_PAIR%s_COMPL_END_TH=%.2f\n", suffix,
		retval->best_pairs.pairs[i].compl_end);
       if (io_version == 3) {
	  /* Print product size */
	  printf("PRIMER_PRODUCT_SIZE%s=%d\n", suffix,
		 retval->best_pairs.pairs[i].product_size);
        /* Print the product Tm if a Tm range is defined */
        if (pa->product_max_tm != PR_DEFAULT_PRODUCT_MAX_TM ||
            pa->product_min_tm != PR_DEFAULT_PRODUCT_MIN_TM) {
          printf("PRIMER_PRODUCT_TM%s=%.4f\n", suffix,
                 retval->best_pairs.pairs[i].product_tm);
                    
          printf("PRIMER_PRODUCT_TM_OLIGO_TM_DIFF%s=%.4f\n", suffix,
                 retval->best_pairs.pairs[i].product_tm_oligo_tm_diff);
                
          printf("PRIMER_PAIR%s_T_OPT_A=%.4f\n", suffix,
                 retval->best_pairs.pairs[i].t_opt_a);
        }
      } else {
        /* Print product size */
        printf("PRIMER_PAIR%s_PRODUCT_SIZE=%d\n", suffix,
               retval->best_pairs.pairs[i].product_size);
        /* Print the product Tm if a Tm range is defined */
        if (pa->product_max_tm != PR_DEFAULT_PRODUCT_MAX_TM ||
            pa->product_min_tm != PR_DEFAULT_PRODUCT_MIN_TM) {
          printf("PRIMER_PAIR%s_PRODUCT_TM=%.4f\n", suffix,
                 retval->best_pairs.pairs[i].product_tm);
                    
          printf("PRIMER_PAIR%s_PRODUCT_TM_OLIGO_TM_DIFF=%.4f\n", suffix,
                 retval->best_pairs.pairs[i].product_tm_oligo_tm_diff);
                
          printf("PRIMER_PAIR%s_T_OPT_A=%.4f\n", suffix,
                 retval->best_pairs.pairs[i].t_opt_a);
        }
      }
      
      /* Print the primer pair temlate mispriming */
      if ((pa->thermodynamic_alignment == 0) && (retval->best_pairs.pairs[i].template_mispriming != ALIGN_SCORE_UNDEF))
        printf("PRIMER_PAIR%s_TEMPLATE_MISPRIMING=%.2f\n", suffix,
               retval->best_pairs.pairs[i].template_mispriming);
       /* Print the primer pair temlate mispriming. Thermodynamic approach.  */
       if ((pa->thermodynamic_alignment == 1) && (retval->best_pairs.pairs[i].template_mispriming != ALIGN_SCORE_UNDEF))
	 printf("PRIMER_PAIR%s_TEMPLATE_MISPRIMING_TH=%.2f\n", suffix,
		retval->best_pairs.pairs[i].template_mispriming);

    } /* End of print parameters of primer pairs */
        
  } /* End of the big loop printing all data */
    
    /* End the print with newline and flush all buffers */
  printf("=\n");
  if (fflush(stdout) == EOF) {
    perror("fflush(stdout) failed");
    exit(-1);
  }
}
示例#8
0
/*
** Unblock the first runnable waiting thread. Skip over
** threads that are trying to be suspended
** Note: Caller must hold _PR_LOCK_LOCK()
*/
void _PR_UnblockLockWaiter(PRLock *lock)
{
    PRThread *t = NULL;
    PRThread *me;
    PRCList *q;

    q = lock->waitQ.next;
    PR_ASSERT(q != &lock->waitQ);
    while (q != &lock->waitQ) {
        /* Unblock first waiter */
        t = _PR_THREAD_CONDQ_PTR(q);

        /*
        ** We are about to change the thread's state to runnable and for local
        ** threads, we are going to assign a cpu to it.  So, protect thread's
        ** data structure.
        */
        _PR_THREAD_LOCK(t);

        if (t->flags & _PR_SUSPENDING) {
            q = q->next;
            _PR_THREAD_UNLOCK(t);
            continue;
        }

        /* Found a runnable thread */
        PR_ASSERT(t->state == _PR_LOCK_WAIT);
        PR_ASSERT(t->wait.lock == lock);
        t->wait.lock = 0;
        PR_REMOVE_LINK(&t->waitQLinks);         /* take it off lock's waitQ */

        /*
        ** If this is a native thread, nothing else to do except to wake it
        ** up by calling the machine dependent wakeup routine.
        **
        ** If this is a local thread, we need to assign it a cpu and
        ** put the thread on that cpu's run queue.  There are two cases to
        ** take care of.  If the currently running thread is also a local
        ** thread, we just assign our own cpu to that thread and put it on
        ** the cpu's run queue.  If the the currently running thread is a
        ** native thread, we assign the primordial cpu to it (on NT,
        ** MD_WAKEUP handles the cpu assignment).
        */

        if ( !_PR_IS_NATIVE_THREAD(t) ) {

            t->state = _PR_RUNNABLE;

            me = _PR_MD_CURRENT_THREAD();

            _PR_AddThreadToRunQ(me, t);
            _PR_THREAD_UNLOCK(t);
        } else {
            t->state = _PR_RUNNING;
            _PR_THREAD_UNLOCK(t);
        }
        _PR_MD_WAKEUP_WAITER(t);
        break;
    }
    return;
}
示例#9
0
文件: ntioto.c 项目: bringhurst/vbox
PRIntn main(PRIntn argc, char *argv[])
{
    PRThread *tJitter;
    PRThread *tAccept;
    PRThread *tConnect;
    PRStatus rv;
    /* This test if valid for WinNT only! */

#if !defined(WINNT)
    return 0;
#endif

    {
        /*
        ** Get command line options
        */
        PLOptStatus os;
        PLOptState *opt = PL_CreateOptState(argc, argv, "hdrvj:");

	    while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
        {
		    if (PL_OPT_BAD == os) continue;
            switch (opt->option)
            {
            case 'd':  /* debug */
                debug = 1;
			    msgLevel = PR_LOG_ERROR;
                break;
            case 'v':  /* verbose mode */
                verbose = 1;
			    msgLevel = PR_LOG_DEBUG;
                break;
            case 'j':
                jitter = atoi(opt->value);
                if ( jitter == 0)
                    jitter = JITTER_DEFAULT;
                break;
            case 'r':
                resume = PR_TRUE;
                break;
            case 'h':  /* help message */
			    Help();
                break;
             default:
                break;
            }
        }
	    PL_DestroyOptState(opt);
    }

    lm = PR_NewLogModule("Test");       /* Initialize logging */

    /* set concurrency */
    PR_SetConcurrency( 4 );

    /* setup thread synchronization mechanics */
    ml = PR_NewLock();
    cv = PR_NewCondVar( ml );

    /* setup a tcp socket */
    memset(&listenAddr, 0, sizeof(listenAddr));
    rv = PR_InitializeNetAddr(PR_IpAddrAny, BASE_PORT, &listenAddr);
    PR_ASSERT( PR_SUCCESS == rv );

    listenSock = PR_NewTCPSocket();
    PR_ASSERT( listenSock );

    rv = PR_Bind( listenSock, &listenAddr);
    PR_ASSERT( PR_SUCCESS == rv );

    rv = PR_Listen( listenSock, 5 );
    PR_ASSERT( PR_SUCCESS == rv );

    /* open a file for writing, provoke bug */
    file1 = PR_Open("xxxTestFile", PR_CREATE_FILE | PR_RDWR, 666);

    /* create Connect thread */
    tConnect = PR_CreateThread(
        PR_USER_THREAD, ConnectThread, NULL,
        PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD,
        PR_JOINABLE_THREAD, 0 );
    PR_ASSERT( tConnect );

    /* create jitter off thread */
    tJitter = PR_CreateThread(
        PR_USER_THREAD, JitterThread, NULL,
        PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD,
        PR_JOINABLE_THREAD, 0 );
    PR_ASSERT( tJitter );

    /* create acceptread thread */
    tAccept = PR_CreateThread(
        PR_USER_THREAD, AcceptThread, NULL,
        PR_PRIORITY_NORMAL, PR_LOCAL_THREAD,
        PR_JOINABLE_THREAD, 0 );
    PR_ASSERT( tAccept );

    /* wait for all threads to quit, then terminate gracefully */
    PR_JoinThread( tConnect );
    PR_JoinThread( tAccept );
    PR_JoinThread( tJitter );
    PR_Close( listenSock );
    PR_DestroyCondVar(cv);
    PR_DestroyLock(ml);
    PR_Close( file1 );
    PR_Delete( "xxxTestFile");

    /* test return and exit */
    if (debug) printf("%s\n", (failed_already)? "FAIL" : "PASS");
    return( (failed_already == PR_TRUE )? 1 : 0 );
}  /* main() */
示例#10
0
/*
** Unlock the lock.
*/
PR_IMPLEMENT(PRStatus) PR_Unlock(PRLock *lock)
{
    PRCList *q;
    PRThreadPriority pri, boost;
    PRIntn is;
    PRThread *me = _PR_MD_CURRENT_THREAD();

    PR_ASSERT(lock != NULL);
    PR_ASSERT(lock->owner == me);
    PR_ASSERT(me != suspendAllThread);
    PR_ASSERT(!(me->flags & _PR_IDLE_THREAD));
    if (lock->owner != me) {
        return PR_FAILURE;
    }

#ifdef _PR_GLOBAL_THREADS_ONLY
    lock->owner = 0;
    _PR_MD_UNLOCK(&lock->ilock);
    return PR_SUCCESS;
#else  /* _PR_GLOBAL_THREADS_ONLY */

    if (_native_threads_only) {
        lock->owner = 0;
        _PR_MD_UNLOCK(&lock->ilock);
        return PR_SUCCESS;
    }

    if (!_PR_IS_NATIVE_THREAD(me))
        _PR_INTSOFF(is);
    _PR_LOCK_LOCK(lock);

    /* Remove the lock from the owning thread's lock list */
    PR_REMOVE_LINK(&lock->links);
    pri = lock->priority;
    boost = lock->boostPriority;
    if (boost > pri) {
        /*
        ** We received a priority boost during the time we held the lock.
        ** We need to figure out what priority to move to by scanning
        ** down our list of lock's that we are still holding and using
        ** the highest boosted priority found.
        */
        q = me->lockList.next;
        while (q != &me->lockList) {
            PRLock *ll = _PR_LOCK_PTR(q);
            if (ll->boostPriority > pri) {
                pri = ll->boostPriority;
            }
            q = q->next;
        }
        if (pri != me->priority) {
            _PR_SetThreadPriority(me, pri);
        }
    }

    /* Unblock the first waiting thread */
    q = lock->waitQ.next;
    if (q != &lock->waitQ)
        _PR_UnblockLockWaiter(lock);
    lock->boostPriority = PR_PRIORITY_LOW;
    lock->owner = 0;
    _PR_LOCK_UNLOCK(lock);
    if (!_PR_IS_NATIVE_THREAD(me))
        _PR_INTSON(is);
    return PR_SUCCESS;
#endif  /* _PR_GLOBAL_THREADS_ONLY */
}
示例#11
0
/*
**  If the current thread owns |lock|, this assertion is guaranteed to
**  succeed.  Otherwise, the behavior of this function is undefined.
*/
PR_IMPLEMENT(void) PR_AssertCurrentThreadOwnsLock(PRLock *lock)
{
    PRThread *me = _PR_MD_CURRENT_THREAD();
    PR_ASSERT(lock->owner == me);
}
示例#12
0
/*
** Lock the lock.
*/
PR_IMPLEMENT(void) PR_Lock(PRLock *lock)
{
    PRThread *me = _PR_MD_CURRENT_THREAD();
    PRIntn is;
    PRThread *t;
    PRCList *q;

    PR_ASSERT(me != suspendAllThread);
    PR_ASSERT(!(me->flags & _PR_IDLE_THREAD));
    PR_ASSERT(lock != NULL);
#ifdef _PR_GLOBAL_THREADS_ONLY
    _PR_MD_LOCK(&lock->ilock);
    PR_ASSERT(lock->owner == 0);
    lock->owner = me;
    return;
#else  /* _PR_GLOBAL_THREADS_ONLY */

    if (_native_threads_only) {
        _PR_MD_LOCK(&lock->ilock);
        PR_ASSERT(lock->owner == 0);
        lock->owner = me;
        return;
    }

    if (!_PR_IS_NATIVE_THREAD(me))
        _PR_INTSOFF(is);

    PR_ASSERT(_PR_IS_NATIVE_THREAD(me) || _PR_MD_GET_INTSOFF() != 0);

retry:
    _PR_LOCK_LOCK(lock);
    if (lock->owner == 0) {
        /* Just got the lock */
        lock->owner = me;
        lock->priority = me->priority;
        /* Add the granted lock to this owning thread's lock list */
        PR_APPEND_LINK(&lock->links, &me->lockList);
        _PR_LOCK_UNLOCK(lock);
        if (!_PR_IS_NATIVE_THREAD(me))
            _PR_FAST_INTSON(is);
        return;
    }

    /* If this thread already owns this lock, then it is a deadlock */
    PR_ASSERT(lock->owner != me);

    PR_ASSERT(_PR_IS_NATIVE_THREAD(me) || _PR_MD_GET_INTSOFF() != 0);

#if 0
    if (me->priority > lock->owner->priority) {
        /*
        ** Give the lock owner a priority boost until we get the
        ** lock. Record the priority we boosted it to.
        */
        lock->boostPriority = me->priority;
        _PR_SetThreadPriority(lock->owner, me->priority);
    }
#endif

    /*
    Add this thread to the asked for lock's list of waiting threads.  We
    add this thread thread in the right priority order so when the unlock
    occurs, the thread with the higher priority will get the lock.
    */
    q = lock->waitQ.next;
    if (q == &lock->waitQ || _PR_THREAD_CONDQ_PTR(q)->priority ==
            _PR_THREAD_CONDQ_PTR(lock->waitQ.prev)->priority) {
        /*
         * If all the threads in the lock waitQ have the same priority,
         * then avoid scanning the list:  insert the element at the end.
         */
        q = &lock->waitQ;
    } else {
        /* Sort thread into lock's waitQ at appropriate point */
        /* Now scan the list for where to insert this entry */
        while (q != &lock->waitQ) {
            t = _PR_THREAD_CONDQ_PTR(lock->waitQ.next);
            if (me->priority > t->priority) {
                /* Found a lower priority thread to insert in front of */
                break;
            }
            q = q->next;
        }
    }
    PR_INSERT_BEFORE(&me->waitQLinks, q);

    /*
    Now grab the threadLock since we are about to change the state.  We have
    to do this since a PR_Suspend or PR_SetThreadPriority type call that takes
    a PRThread* as an argument could be changing the state of this thread from
    a thread running on a different cpu.
    */

    _PR_THREAD_LOCK(me);
    me->state = _PR_LOCK_WAIT;
    me->wait.lock = lock;
    _PR_THREAD_UNLOCK(me);

    _PR_LOCK_UNLOCK(lock);

    _PR_MD_WAIT(me, PR_INTERVAL_NO_TIMEOUT);
    goto retry;

#endif  /* _PR_GLOBAL_THREADS_ONLY */
}
示例#13
0
void _PR_FreeLock(PRLock *lock)
{
    PR_ASSERT(lock->owner == 0);
    _PR_MD_FREE_LOCK(&lock->ilock);
}
示例#14
0
PR_IMPLEMENT(void *) PL_ArenaAllocate(PLArenaPool *pool, PRUint32 nb)
{
    PLArena *a;   
    char *rp;     /* returned pointer */

    PR_ASSERT((nb & pool->mask) == 0);
    
    nb = (PRUword)PL_ARENA_ALIGN(pool, nb); /* force alignment */

    /* attempt to allocate from arenas at pool->current */
    {
        a = pool->current;
        do {
            if ( a->avail +nb <= a->limit )  {
                pool->current = a;
                rp = (char *)a->avail;
                a->avail += nb;
                return rp;
            }
        } while( NULL != (a = a->next) );
    }

    /* attempt to allocate from arena_freelist */
    {
        PLArena *p; /* previous pointer, for unlinking from freelist */

        /* lock the arena_freelist. Make access to the freelist MT-Safe */
        if ( PR_FAILURE == LockArena())
            return(0);

        for ( a = arena_freelist, p = NULL; a != NULL ; p = a, a = a->next ) {
            if ( a->base +nb <= a->limit )  {
                if ( p == NULL )
                    arena_freelist = a->next;
                else
                    p->next = a->next;
                UnlockArena();
                a->avail = a->base;
                rp = (char *)a->avail;
                a->avail += nb;
                /* the newly allocated arena is linked after pool->current 
                *  and becomes pool->current */
                a->next = pool->current->next;
                pool->current->next = a;
                pool->current = a;
                if ( NULL == pool->first.next )
                    pool->first.next = a;
                return(rp);
            }
        }
        UnlockArena();
    }

    /* attempt to allocate from the heap */ 
    {  
        PRUint32 sz = PR_MAX(pool->arenasize, nb);
        sz += sizeof *a + pool->mask;  /* header and alignment slop */
        a = (PLArena*)PR_MALLOC(sz);
        if ( NULL != a )  {
            a->limit = (PRUword)a + sz;
            a->base = a->avail = (PRUword)PL_ARENA_ALIGN(pool, a + 1);
            rp = (char *)a->avail;
            a->avail += nb;
            /* the newly allocated arena is linked after pool->current 
            *  and becomes pool->current */
            a->next = pool->current->next;
            pool->current->next = a;
            pool->current = a;
            if ( NULL == pool->first.next )
                pool->first.next = a;
            PL_COUNT_ARENA(pool,++);
            COUNT(pool, nmallocs);
            return(rp);
        }
    }
// We let the caller close the file in case he's updating a lot of flags
// and we don't want to open and close the file every time through.
// As an experiment, try caching the fid in the db as m_folderFile.
// If this is set, use it but don't return *pFid.
void nsMailDatabase::UpdateFolderFlag(nsIMsgDBHdr *mailHdr, PRBool bSet, 
							  MsgFlags flag, nsIOutputStream **ppFileStream)
{
  static char buf[50];
  PRInt64 folderStreamPos = 0; //saves the folderStream pos in case we are sharing the stream with other code
  nsIOutputStream *fileStream = (m_folderStream) ? m_folderStream.get() : *ppFileStream;
  PRUint32 offset;
  (void)mailHdr->GetStatusOffset(&offset);
  nsCOMPtr <nsISeekableStream> seekableStream;
  
  nsresult rv;
  
  if (offset > 0) 
  {
    
    if (fileStream == NULL) 
    {
      rv = MsgGetFileStream(m_folderFile, &fileStream);
      if (NS_FAILED(rv))
        return;
      seekableStream = do_QueryInterface(fileStream);
    }
    else if (!m_ownFolderStream)
    {
      m_folderStream->Flush();
      seekableStream = do_QueryInterface(fileStream);
      seekableStream->Tell(&folderStreamPos);
    }
    else
      seekableStream = do_QueryInterface(m_folderStream);
      
    if (fileStream) 
    {
      PRUint32 msgOffset;
      (void)mailHdr->GetMessageOffset(&msgOffset);
      PRUint32 statusPos = offset + msgOffset;
      PR_ASSERT(offset < 10000);
      seekableStream->Seek(nsISeekableStream::NS_SEEK_SET, statusPos);
      buf[0] = '\0';
      nsCOMPtr <nsIInputStream> inputStream = do_QueryInterface(fileStream);
      PRUint32 bytesRead;
      if (NS_SUCCEEDED(inputStream->Read(buf, X_MOZILLA_STATUS_LEN + 6, &bytesRead)))
      {
        buf[bytesRead] = '\0';
        if (strncmp(buf, X_MOZILLA_STATUS, X_MOZILLA_STATUS_LEN) == 0 &&
          strncmp(buf + X_MOZILLA_STATUS_LEN, ": ", 2) == 0 &&
          strlen(buf) >= X_MOZILLA_STATUS_LEN + 6) 
        {
          PRUint32 flags;
          PRUint32 bytesWritten;
          (void)mailHdr->GetFlags(&flags);
          if (!(flags & MSG_FLAG_EXPUNGED))
          {
            int i;
            char *p = buf + X_MOZILLA_STATUS_LEN + 2;
            
            for (i=0, flags = 0; i<4; i++, p++)
            {
              flags = (flags << 4) | msg_UnHex(*p);
            }
            
            PRUint32 curFlags;
            (void)mailHdr->GetFlags(&curFlags);
            flags = (flags & MSG_FLAG_QUEUED) |
              (curFlags & ~MSG_FLAG_RUNTIME_ONLY);
          }
          else
          {
            flags &= ~MSG_FLAG_RUNTIME_ONLY;
          }
          seekableStream->Seek(nsISeekableStream::NS_SEEK_SET, statusPos);
          // We are filing out x-mozilla-status flags here
          PR_snprintf(buf, sizeof(buf), X_MOZILLA_STATUS_FORMAT,
            flags & 0x0000FFFF);
          PRInt32 lineLen = PL_strlen(buf);
          PRUint32 status2Pos = statusPos + lineLen + MSG_LINEBREAK_LEN;
          fileStream->Write(buf, lineLen, &bytesWritten);
          
          // time to upate x-mozilla-status2
          seekableStream->Seek(nsISeekableStream::NS_SEEK_SET, status2Pos);
          if (NS_SUCCEEDED(inputStream->Read(buf, X_MOZILLA_STATUS2_LEN + 10, &bytesRead)))
          {
            if (strncmp(buf, X_MOZILLA_STATUS2, X_MOZILLA_STATUS2_LEN) == 0 &&
              strncmp(buf + X_MOZILLA_STATUS2_LEN, ": ", 2) == 0 &&
              strlen(buf) >= X_MOZILLA_STATUS2_LEN + 10) 
            {
              PRUint32 dbFlags;
              (void)mailHdr->GetFlags(&dbFlags);
              dbFlags &= 0xFFFF0000;
              seekableStream->Seek(nsISeekableStream::NS_SEEK_SET, status2Pos);
              PR_snprintf(buf, sizeof(buf), X_MOZILLA_STATUS2_FORMAT, dbFlags);
              fileStream->Write(buf, PL_strlen(buf), &bytesWritten);
            }
          }
        } else 
        {
#ifdef DEBUG
          printf("Didn't find %s where expected at position %ld\n"
            "instead, found %s.\n",
            X_MOZILLA_STATUS, (long) statusPos, buf);
#endif
          SetReparse(PR_TRUE);
        }			
      } 
      else 
      {
#ifdef DEBUG
        printf("Couldn't read old status line at all at position %ld\n",
          (long) statusPos);
#endif
        SetReparse(PR_TRUE);
      }
    }
    else
    {
#ifdef DEBUG
      nsCString folderPath;
      m_folderFile->GetNativePath(folderPath);
      printf("Couldn't open mail folder for update%s!\n",
        folderPath.get());
#endif
      PR_ASSERT(PR_FALSE);
    }
  }
  if (!m_folderStream)
    *ppFileStream = fileStream; // This tells the caller that we opened the file, and please to close it.
  else if (!m_ownFolderStream)
    seekableStream->Seek(nsISeekableStream::NS_SEEK_SET, folderStreamPos);
}
示例#16
0
PRInt32 _PR_EmulateTransmitFile(PRFileDesc *sd, PRFileDesc *fd, 
const void *headers, PRInt32 hlen, PRTransmitFileFlags flags,
PRIntervalTime timeout)
{
	PRInt32 rv, count = 0;
	PRInt32 rlen;
	PRThread *me = _PR_MD_CURRENT_THREAD();
	char *buf = NULL;
#define _TRANSMITFILE_BUFSIZE	(16 * 1024)

	if (_PR_PENDING_INTERRUPT(me)) {
		me->flags &= ~_PR_INTERRUPT;
		PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
		return -1;
	}

	buf = PR_MALLOC(_TRANSMITFILE_BUFSIZE);
	if (buf == NULL) {
		PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
		return -1;
	}

	/*
	 * send headers, first
	 */
	while (hlen) {
		rv =  PR_Send(sd, headers, hlen, 0, timeout);
		if (rv < 0) {
			/* PR_Send() has invoked PR_SetError(). */
			rv = -1;
			goto done;
		} else {
			count += rv;
			headers = (const void*) ((const char*)headers + rv);
			hlen -= rv;
		}
	}
	/*
	 * send file, next
	 */
	while ((rlen = PR_Read(fd, buf, _TRANSMITFILE_BUFSIZE)) > 0) {
		while (rlen) {
			char *bufptr = buf;

			rv =  PR_Send(sd, bufptr, rlen,0,PR_INTERVAL_NO_TIMEOUT);
			if (rv < 0) {
				/* PR_Send() has invoked PR_SetError(). */
				rv = -1;
				goto done;
			} else {
				count += rv;
				bufptr = ((char*)bufptr + rv);
				rlen -= rv;
			}
		}
	}
	if (rlen == 0) {
		/*
		 * end-of-file
		 */
		if (flags & PR_TRANSMITFILE_CLOSE_SOCKET)
			PR_Close(sd);
		rv = count;
	} else {
		PR_ASSERT(rlen < 0);
		/* PR_Read() has invoked PR_SetError(). */
		rv = -1;
	}

done:
	if (buf)
		PR_DELETE(buf);
	return rv;
}
示例#17
0
文件: uxproces.c 项目: edrikL/gears
static PRProcess *
ForkAndExec(
    const char *path,
    char *const *argv,
    char *const *envp,
    const PRProcessAttr *attr)
{
    PRProcess *process;
    int nEnv, idx;
    char *const *childEnvp;
    char **newEnvp = NULL;
    int flags;
#ifdef VMS
    char VMScurdir[FILENAME_MAX+1] = { '\0' } ;
#endif	

    process = PR_NEW(PRProcess);
    if (!process) {
        PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
        return NULL;
    }

    childEnvp = envp;
    if (attr && attr->fdInheritBuffer) {
        PRBool found = PR_FALSE;

        if (NULL == childEnvp) {
#ifdef DARWIN
            childEnvp = *(_NSGetEnviron());
#else
            childEnvp = environ;
#endif
        }
        for (nEnv = 0; childEnvp[nEnv]; nEnv++) {
        }
        newEnvp = (char **) PR_MALLOC((nEnv + 2) * sizeof(char *));
        if (NULL == newEnvp) {
            PR_DELETE(process);
            PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
            return NULL;
        }
        for (idx = 0; idx < nEnv; idx++) {
            newEnvp[idx] = childEnvp[idx];
            if (!found && !strncmp(newEnvp[idx], "NSPR_INHERIT_FDS=", 17)) {
                newEnvp[idx] = attr->fdInheritBuffer;
                found = PR_TRUE;
            }
        }
        if (!found) {
            newEnvp[idx++] = attr->fdInheritBuffer;
        }
        newEnvp[idx] = NULL;
        childEnvp = newEnvp;
    }

#ifdef VMS
/*
** Since vfork/exec is implemented VERY differently on OpenVMS, we have to
** handle the setting up of the standard streams very differently. And since
** none of this code can ever execute in the context of the child, we have
** to perform the chdir in the parent so the child is born into the correct
** directory (and then switch the parent back again).
*/
{
    int decc$set_child_standard_streams(int,int,int);
    int n, fd_stdin=0, fd_stdout=1, fd_stderr=2;

    /* Set up any standard streams we are given, assuming defaults */
    if (attr) {
       if (attr->stdinFd)
           fd_stdin = attr->stdinFd->secret->md.osfd;
       if (attr->stdoutFd)
           fd_stdout = attr->stdoutFd->secret->md.osfd;
       if (attr->stderrFd)
           fd_stderr = attr->stderrFd->secret->md.osfd;
    }

    /*
    ** Put a lock around anything that isn't going to be thread-safe.
    */
    PR_Lock(_pr_vms_fork_lock);

    /*
    ** Prepare the child's streams. We always do this in case a previous fork
    ** has left the stream assignments in some non-standard way.
    */
    n = decc$set_child_standard_streams(fd_stdin,fd_stdout,fd_stderr);
    if (n == -1) {
       PR_SetError(PR_BAD_DESCRIPTOR_ERROR, errno);
       PR_DELETE(process);
       if (newEnvp) {
           PR_DELETE(newEnvp);
       }
       PR_Unlock(_pr_vms_fork_lock);
       return NULL;
    }

    /* Switch directory if we have to */
    if (attr) {
       if (attr->currentDirectory) {
           if ( (getcwd(VMScurdir,sizeof(VMScurdir)) == NULL) ||
                (chdir(attr->currentDirectory) < 0) ) {
               PR_SetError(PR_DIRECTORY_OPEN_ERROR, errno);
               PR_DELETE(process);
               if (newEnvp) {
                   PR_DELETE(newEnvp);
               }
               PR_Unlock(_pr_vms_fork_lock);
               return NULL;
           }
       }
    }
}
#endif /* VMS */

#ifdef AIX
    process->md.pid = (*pr_wp.forkptr)();
#elif defined(NTO) || defined(SYMBIAN)
    /*
     * fork() & exec() does not work in a multithreaded process.
     * Use spawn() instead.
     */
    {
        int fd_map[3] = { 0, 1, 2 };

        if (attr) {
            if (attr->stdinFd && attr->stdinFd->secret->md.osfd != 0) {
                fd_map[0] = dup(attr->stdinFd->secret->md.osfd);
                flags = fcntl(fd_map[0], F_GETFL, 0);
                if (flags & O_NONBLOCK)
                    fcntl(fd_map[0], F_SETFL, flags & ~O_NONBLOCK);
            }
            if (attr->stdoutFd && attr->stdoutFd->secret->md.osfd != 1) {
                fd_map[1] = dup(attr->stdoutFd->secret->md.osfd);
                flags = fcntl(fd_map[1], F_GETFL, 0);
                if (flags & O_NONBLOCK)
                    fcntl(fd_map[1], F_SETFL, flags & ~O_NONBLOCK);
            }
            if (attr->stderrFd && attr->stderrFd->secret->md.osfd != 2) {
                fd_map[2] = dup(attr->stderrFd->secret->md.osfd);
                flags = fcntl(fd_map[2], F_GETFL, 0);
                if (flags & O_NONBLOCK)
                    fcntl(fd_map[2], F_SETFL, flags & ~O_NONBLOCK);
            }

            PR_ASSERT(attr->currentDirectory == NULL);  /* not implemented */
        }

#ifdef SYMBIAN
        /* In Symbian OS, we use posix_spawn instead of fork() and exec() */
        posix_spawn(&(process->md.pid), path, NULL, NULL, argv, childEnvp);
#else
        process->md.pid = spawn(path, 3, fd_map, NULL, argv, childEnvp);
#endif

        if (fd_map[0] != 0)
            close(fd_map[0]);
        if (fd_map[1] != 1)
            close(fd_map[1]);
        if (fd_map[2] != 2)
            close(fd_map[2]);
    }
#else
    process->md.pid = fork();
#endif
    if ((pid_t) -1 == process->md.pid) {
        PR_SetError(PR_INSUFFICIENT_RESOURCES_ERROR, errno);
        PR_DELETE(process);
        if (newEnvp) {
            PR_DELETE(newEnvp);
        }
        return NULL;
    } else if (0 == process->md.pid) {  /* the child process */
        /*
         * If the child process needs to exit, it must call _exit().
         * Do not call exit(), because exit() will flush and close
         * the standard I/O file descriptors, and hence corrupt
         * the parent process's standard I/O data structures.
         */

#if !defined(NTO) && !defined(SYMBIAN)
#ifdef VMS
       /* OpenVMS has already handled all this above */
#else
        if (attr) {
            /* the osfd's to redirect stdin, stdout, and stderr to */
            int in_osfd = -1, out_osfd = -1, err_osfd = -1;

            if (attr->stdinFd
                    && attr->stdinFd->secret->md.osfd != 0) {
                in_osfd = attr->stdinFd->secret->md.osfd;
                if (dup2(in_osfd, 0) != 0) {
                    _exit(1);  /* failed */
                }
                flags = fcntl(0, F_GETFL, 0);
                if (flags & O_NONBLOCK) {
                    fcntl(0, F_SETFL, flags & ~O_NONBLOCK);
                }
            }
            if (attr->stdoutFd
                    && attr->stdoutFd->secret->md.osfd != 1) {
                out_osfd = attr->stdoutFd->secret->md.osfd;
                if (dup2(out_osfd, 1) != 1) {
                    _exit(1);  /* failed */
                }
                flags = fcntl(1, F_GETFL, 0);
                if (flags & O_NONBLOCK) {
                    fcntl(1, F_SETFL, flags & ~O_NONBLOCK);
                }
            }
            if (attr->stderrFd
                    && attr->stderrFd->secret->md.osfd != 2) {
                err_osfd = attr->stderrFd->secret->md.osfd;
                if (dup2(err_osfd, 2) != 2) {
                    _exit(1);  /* failed */
                }
                flags = fcntl(2, F_GETFL, 0);
                if (flags & O_NONBLOCK) {
                    fcntl(2, F_SETFL, flags & ~O_NONBLOCK);
                }
            }
            if (in_osfd != -1) {
                close(in_osfd);
            }
            if (out_osfd != -1 && out_osfd != in_osfd) {
                close(out_osfd);
            }
            if (err_osfd != -1 && err_osfd != in_osfd
                    && err_osfd != out_osfd) {
                close(err_osfd);
            }
            if (attr->currentDirectory) {
                if (chdir(attr->currentDirectory) < 0) {
                    _exit(1);  /* failed */
                }
            }
        }
#endif /* !VMS */

        if (childEnvp) {
            (void)execve(path, argv, childEnvp);
        } else {
            /* Inherit the environment of the parent. */
            (void)execv(path, argv);
        }
        /* Whoops! It returned. That's a bad sign. */
#ifdef VMS
       /*
       ** On OpenVMS we are still in the context of the parent, and so we
       ** can (and should!) perform normal error handling.
       */
       PR_SetError(PR_UNKNOWN_ERROR, errno);
       PR_DELETE(process);
       if (newEnvp) {
           PR_DELETE(newEnvp);
       }
       if (VMScurdir[0] != '\0')
           chdir(VMScurdir);
       PR_Unlock(_pr_vms_fork_lock);
       return NULL;
#else
        _exit(1);
#endif /* VMS */
#endif /* !NTO */
    }

    if (newEnvp) {
        PR_DELETE(newEnvp);
    }
#ifdef VMS
    /* If we switched directories, then remember to switch back */
    if (VMScurdir[0] != '\0') {
       chdir(VMScurdir); /* can't do much if it fails */
    }
    PR_Unlock(_pr_vms_fork_lock);
#endif /* VMS */

#if defined(_PR_NATIVE_THREADS)
    PR_Lock(pr_wp.ml);
    if (0 == pr_wp.numProcs++) {
        PR_NotifyCondVar(pr_wp.cv);
    }
    PR_Unlock(pr_wp.ml);
#endif
    return process;
}
示例#18
0
PR_IMPLEMENT(void) PR_FD_SET(PRFileDesc *fh, PR_fd_set *set)
{
	PR_ASSERT( set->hsize < PR_MAX_SELECT_DESC );

	set->harray[set->hsize++] = fh;
}
示例#19
0
PR_IMPLEMENT(PRStatus) PR_NotifyAllCondVar(PRCondVar *cvar)
{
    PR_ASSERT(cvar != NULL);
    pt_PostNotifyToCvar(cvar, PR_TRUE);
    return PR_SUCCESS;
}  /* PR_NotifyAllCondVar */
示例#20
0
PR_IMPLEMENT(void) PR_FD_NSET(PRInt32 fd, PR_fd_set *set)
{
	PR_ASSERT( set->nsize < PR_MAX_SELECT_DESC );

	set->narray[set->nsize++] = fd;
}
示例#21
0
static PRStatus
IdentityInfoInit()
{
  for (size_t iEV = 0; iEV < PR_ARRAY_SIZE(myTrustedEVInfos); ++iEV) {
    nsMyTrustedEVInfo& entry = myTrustedEVInfos[iEV];

    SECStatus rv;
    CERTIssuerAndSN ias;

    rv = ATOB_ConvertAsciiToItem(&ias.derIssuer, const_cast<char*>(entry.issuer_base64));
    PR_ASSERT(rv == SECSuccess);
    if (rv != SECSuccess) {
      return PR_FAILURE;
    }
    rv = ATOB_ConvertAsciiToItem(&ias.serialNumber,
                                 const_cast<char*>(entry.serial_base64));
    PR_ASSERT(rv == SECSuccess);
    if (rv != SECSuccess) {
      SECITEM_FreeItem(&ias.derIssuer, false);
      return PR_FAILURE;
    }

    ias.serialNumber.type = siUnsignedInteger;

    entry.cert = CERT_FindCertByIssuerAndSN(nullptr, &ias);

    SECITEM_FreeItem(&ias.derIssuer, false);
    SECITEM_FreeItem(&ias.serialNumber, false);

    // If an entry is missing in the NSS root database, it may be because the
    // root database is out of sync with what we expect (e.g. a different
    // version of system NSS is installed). We will just silently avoid
    // treating that root cert as EV.
    if (!entry.cert) {
#ifdef DEBUG
      // The debug CA info is at position 0, and is NOT on the NSS root db
      if (iEV == 0) {
        continue;
      }
#endif
      PR_NOT_REACHED("Could not find EV root in NSS storage");
      continue;
    }

    unsigned char certFingerprint[20];
    rv = PK11_HashBuf(SEC_OID_SHA1, certFingerprint,
                      entry.cert->derCert.data, entry.cert->derCert.len);
    PR_ASSERT(rv == SECSuccess);
    if (rv == SECSuccess) {
      bool same = !memcmp(certFingerprint, entry.ev_root_sha1_fingerprint, 20);
      PR_ASSERT(same);
      if (same) {

        SECItem ev_oid_item;
        ev_oid_item.data = nullptr;
        ev_oid_item.len = 0;
        rv = SEC_StringToOID(nullptr, &ev_oid_item, entry.dotted_oid, 0);
        PR_ASSERT(rv == SECSuccess);
        if (rv == SECSuccess) {
          entry.oid_tag = register_oid(&ev_oid_item, entry.oid_name);
          if (entry.oid_tag == SEC_OID_UNKNOWN) {
            rv = SECFailure;
          }
          SECITEM_FreeItem(&ev_oid_item, false);
        }
      } else {
        PR_SetError(SEC_ERROR_BAD_DATA, 0);
        rv = SECFailure;
      }
    }

    if (rv != SECSuccess) {
      CERT_DestroyCertificate(entry.cert);
      entry.cert = nullptr;
      entry.oid_tag = SEC_OID_UNKNOWN;
      return PR_FAILURE;
    }
  }

  return PR_SUCCESS;
}
示例#22
0
static PRPollDesc *_pr_setfd(
    PR_fd_set *set, PRInt16 flags, PRPollDesc *polldesc)
{
    PRUintn fsidx, pdidx;
    PRPollDesc *poll = polldesc;

    if (NULL == set) return poll;

	/* First set the pr file handle osfds */
	for (fsidx = 0; fsidx < set->hsize; fsidx++)
	{
	    for (pdidx = 0; 1; pdidx++)
        {
            if ((PRFileDesc*)-1 == poll[pdidx].fd)
            {
                /* our vector is full - extend and condition it */
                poll = PR_Realloc(
                    poll, (pdidx + 1 + PD_INCR) * sizeof(PRPollDesc));
                if (NULL == poll) goto out_of_memory;
                memset(
                    poll + pdidx * sizeof(PRPollDesc),
                    0, PD_INCR * sizeof(PRPollDesc));
                poll[pdidx + PD_INCR].fd = (PRFileDesc*)-1;
            }
            if ((NULL == poll[pdidx].fd)
            || (poll[pdidx].fd == set->harray[fsidx]))
            {
                /* PR_ASSERT(0 == (poll[pdidx].in_flags & flags)); */
                /* either empty or prevously defined */
                poll[pdidx].fd = set->harray[fsidx];  /* possibly redundant */
                poll[pdidx].in_flags |= flags;  /* possibly redundant */
                break;
            }
        }
	}

#if 0
	/* Second set the native osfds */
	for (fsidx = 0; fsidx < set->nsize; fsidx++)
	{
	    for (pdidx = 0; ((PRFileDesc*)-1 != poll[pdidx].fd); pdidx++)
        {
            if ((PRFileDesc*)-1 == poll[pdidx].fd)
            {
                /* our vector is full - extend and condition it */
                poll = PR_Realloc(
                    poll, (pdidx + PD_INCR) * sizeof(PRPollDesc));
                if (NULL == poll) goto out_of_memory;
                memset(
                    poll + pdidx * sizeof(PRPollDesc),
                    0, PD_INCR * sizeof(PRPollDesc));
                poll[(pdidx + PD_INCR)].fd = (PRFileDesc*)-1;
            }
            if ((NULL == poll[pdidx].fd)
            || (poll[pdidx].fd == set->narray[fsidx]))
            {
                /* either empty or prevously defined */
                poll[pdidx].fd = set->narray[fsidx];
                PR_ASSERT(0 == (poll[pdidx].in_flags & flags));
                poll[pdidx].in_flags |= flags;
                break;
            }
        }
	}
#endif /* 0 */

	return poll;

out_of_memory:
    if (NULL != polldesc) PR_DELETE(polldesc);
    return NULL;
}  /* _pr_setfd */
示例#23
0
文件: layer.c 项目: bringhurst/vbox
PRIntn main(PRIntn argc, char **argv)
{
    PRStatus rv;
    PRIntn mits;
    PLOptStatus os;
    PRFileDesc *client, *service;
    PRFileDesc *client_stack, *service_stack;
    PRNetAddr any_address;
    const char *server_name = NULL;
    const PRIOMethods *stubMethods;
    PRThread *client_thread, *server_thread;
    PRThreadScope thread_scope = PR_LOCAL_THREAD;
    PLOptState *opt = PL_CreateOptState(argc, argv, "dqGC:c:p:");
    while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
    {
        if (PL_OPT_BAD == os) continue;
        switch (opt->option)
        {
        case 0:
            server_name = opt->value;
            break;
        case 'd':  /* debug mode */
            if (verbosity < noisy)
                verbosity = ChangeVerbosity(verbosity, 1);
            break;
        case 'q':  /* debug mode */
            if (verbosity > silent)
                verbosity = ChangeVerbosity(verbosity, -1);
            break;
        case 'G':  /* use global threads */
            thread_scope = PR_GLOBAL_THREAD;
            break;
        case 'C':  /* number of threads waiting */
            major_iterations = atoi(opt->value);
            break;
        case 'c':  /* number of client threads */
            minor_iterations = atoi(opt->value);
            break;
        case 'p':  /* default port */
            default_port = atoi(opt->value);
            break;
        default:
            break;
        }
    }
    PL_DestroyOptState(opt);
    PR_STDIO_INIT();

    logFile = PR_GetSpecialFD(PR_StandardError);

    identity = PR_GetUniqueIdentity("Dummy");
    stubMethods = PR_GetDefaultIOMethods();

    /*
    ** The protocol we're going to implement is one where in order to initiate
    ** a send, the sender must first solicit permission. Therefore, every
    ** send is really a send - receive - send sequence.
    */
    myMethods = *stubMethods;  /* first get the entire batch */
    myMethods.recv = MyRecv;  /* then override the ones we care about */
    myMethods.send = MySend;  /* then override the ones we care about */

    if (NULL == server_name)
        rv = PR_InitializeNetAddr(
            PR_IpAddrLoopback, default_port, &server_address);
    else
    {
        rv = PR_StringToNetAddr(server_name, &server_address);
        PR_ASSERT(PR_SUCCESS == rv);
        rv = PR_InitializeNetAddr(
            PR_IpAddrNull, default_port, &server_address);
    }
    PR_ASSERT(PR_SUCCESS == rv);

    /* one type w/o layering */

    mits = minor_iterations;
    while (major_iterations-- > 0)
    {
        if (verbosity > silent)
            PR_fprintf(logFile, "Beginning non-layered test\n");
        client = PR_NewTCPSocket(); PR_ASSERT(NULL != client);
        service = PR_NewTCPSocket(); PR_ASSERT(NULL != service);
        rv = PR_InitializeNetAddr(PR_IpAddrAny, default_port, &any_address);
        PR_ASSERT(PR_SUCCESS == rv);
        rv = PR_Bind(service, &any_address); PR_ASSERT(PR_SUCCESS == rv);
        rv = PR_Listen(service, 10); PR_ASSERT(PR_SUCCESS == rv);

        minor_iterations = mits;
        server_thread = PR_CreateThread(
            PR_USER_THREAD, Server, service,
            PR_PRIORITY_HIGH, thread_scope,
            PR_JOINABLE_THREAD, 16 * 1024);
        PR_ASSERT(NULL != server_thread);

        client_thread = PR_CreateThread(
            PR_USER_THREAD, Client, client,
            PR_PRIORITY_NORMAL, thread_scope,
            PR_JOINABLE_THREAD, 16 * 1024);
        PR_ASSERT(NULL != client_thread);

        rv = PR_JoinThread(client_thread);
        PR_ASSERT(PR_SUCCESS == rv);
        rv = PR_JoinThread(server_thread);
        PR_ASSERT(PR_SUCCESS == rv);

        rv = PR_Close(client); PR_ASSERT(PR_SUCCESS == rv);
        rv = PR_Close(service); PR_ASSERT(PR_SUCCESS == rv);
        if (verbosity > silent)
            PR_fprintf(logFile, "Ending non-layered test\n");

        /* with layering */
        if (verbosity > silent)
            PR_fprintf(logFile, "Beginning layered test\n");
        client = PR_NewTCPSocket(); PR_ASSERT(NULL != client);
        PushLayer(client);
        service = PR_NewTCPSocket(); PR_ASSERT(NULL != service);
        PushLayer(service);
        rv = PR_InitializeNetAddr(PR_IpAddrAny, default_port, &any_address);
        PR_ASSERT(PR_SUCCESS == rv);
        rv = PR_Bind(service, &any_address); PR_ASSERT(PR_SUCCESS == rv);
        rv = PR_Listen(service, 10); PR_ASSERT(PR_SUCCESS == rv);

        minor_iterations = mits;
        server_thread = PR_CreateThread(
            PR_USER_THREAD, Server, service,
            PR_PRIORITY_HIGH, thread_scope,
            PR_JOINABLE_THREAD, 16 * 1024);
        PR_ASSERT(NULL != server_thread);

        client_thread = PR_CreateThread(
            PR_USER_THREAD, Client, client,
            PR_PRIORITY_NORMAL, thread_scope,
            PR_JOINABLE_THREAD, 16 * 1024);
        PR_ASSERT(NULL != client_thread);

        rv = PR_JoinThread(client_thread);
        PR_ASSERT(PR_SUCCESS == rv);
        rv = PR_JoinThread(server_thread);
        PR_ASSERT(PR_SUCCESS == rv);

        rv = PR_Close(client); PR_ASSERT(PR_SUCCESS == rv);
        rv = PR_Close(service); PR_ASSERT(PR_SUCCESS == rv);
        /* with layering, using new style stack */
        if (verbosity > silent)
            PR_fprintf(logFile,
							"Beginning layered test with new style stack\n");
        client = PR_NewTCPSocket(); PR_ASSERT(NULL != client);
    	client_stack = PR_CreateIOLayer(client);
        PushNewLayers(client_stack);
        service = PR_NewTCPSocket(); PR_ASSERT(NULL != service);
    	service_stack = PR_CreateIOLayer(service);
        PushNewLayers(service_stack);
        rv = PR_InitializeNetAddr(PR_IpAddrAny, default_port, &any_address);
        PR_ASSERT(PR_SUCCESS == rv);
        rv = PR_Bind(service, &any_address); PR_ASSERT(PR_SUCCESS == rv);
        rv = PR_Listen(service, 10); PR_ASSERT(PR_SUCCESS == rv);

        minor_iterations = mits;
        server_thread = PR_CreateThread(
            PR_USER_THREAD, Server, service_stack,
            PR_PRIORITY_HIGH, thread_scope,
            PR_JOINABLE_THREAD, 16 * 1024);
        PR_ASSERT(NULL != server_thread);

        client_thread = PR_CreateThread(
            PR_USER_THREAD, Client, client_stack,
            PR_PRIORITY_NORMAL, thread_scope,
            PR_JOINABLE_THREAD, 16 * 1024);
        PR_ASSERT(NULL != client_thread);

        rv = PR_JoinThread(client_thread);
        PR_ASSERT(PR_SUCCESS == rv);
        rv = PR_JoinThread(server_thread);
        PR_ASSERT(PR_SUCCESS == rv);

        rv = PR_Close(client_stack); PR_ASSERT(PR_SUCCESS == rv);
        rv = PR_Close(service_stack); PR_ASSERT(PR_SUCCESS == rv);
        if (verbosity > silent)
            PR_fprintf(logFile, "Ending layered test\n");
    }
    return 0;
}  /* main */
示例#24
0
PR_IMPLEMENT(PRInt32) PR_Select(
    PRInt32 unused, PR_fd_set *pr_rd, PR_fd_set *pr_wr, 
    PR_fd_set *pr_ex, PRIntervalTime timeout)
{

#if !defined(NEED_SELECT)
    PRInt32 npds = 0; 
    /*
    ** Find out how many fds are represented in the three lists.
    ** Then allocate a polling descriptor for the logical union
    ** (there can't be any overlapping) and call PR_Poll().
    */

    PRPollDesc *copy, *poll;

    static PRBool warning = PR_TRUE;
    if (warning) warning = _PR_Obsolete( "PR_Select()", "PR_Poll()");

    /* try to get an initial guesss at how much space we need */
    npds = 0;
    if ((NULL != pr_rd) && ((pr_rd->hsize + pr_rd->nsize - npds) > 0))
        npds = pr_rd->hsize + pr_rd->nsize;
    if ((NULL != pr_wr) && ((pr_wr->hsize + pr_wr->nsize - npds) > 0))
        npds = pr_wr->hsize + pr_wr->nsize;
    if ((NULL != pr_ex) && ((pr_ex->hsize + pr_ex->nsize - npds) > 0))
        npds = pr_ex->hsize + pr_ex->nsize;

    if (0 == npds)
    {
        PR_Sleep(timeout);
        return 0;
    }

    copy = poll = PR_Calloc(npds + PD_INCR, sizeof(PRPollDesc));
    if (NULL == poll) goto out_of_memory;
    poll[npds + PD_INCR - 1].fd = (PRFileDesc*)-1;

    poll = _pr_setfd(pr_rd, PR_POLL_READ, poll);
    if (NULL == poll) goto out_of_memory;
    poll = _pr_setfd(pr_wr, PR_POLL_WRITE, poll);
    if (NULL == poll) goto out_of_memory;
    poll = _pr_setfd(pr_ex, PR_POLL_EXCEPT, poll);
    if (NULL == poll) goto out_of_memory;
    unused = 0;
    while (NULL != poll[unused].fd && (PRFileDesc*)-1 != poll[unused].fd)
    {
        ++unused;
    }

    PR_ASSERT(unused > 0);
    npds = PR_Poll(poll, unused, timeout);

    if (npds > 0)
    {
        /* Copy the results back into the fd sets */
        if (NULL != pr_rd) pr_rd->nsize = pr_rd->hsize = 0;
        if (NULL != pr_wr) pr_wr->nsize = pr_wr->hsize = 0;
        if (NULL != pr_ex) pr_ex->nsize = pr_ex->hsize = 0;
        for (copy = &poll[unused - 1]; copy >= poll; --copy)
        {
            if (copy->out_flags & PR_POLL_NVAL)
            {
                PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0);
                npds = -1;
                break;
            }
            if (copy->out_flags & PR_POLL_READ)
                if (NULL != pr_rd) pr_rd->harray[pr_rd->hsize++] = copy->fd;
            if (copy->out_flags & PR_POLL_WRITE)
                if (NULL != pr_wr) pr_wr->harray[pr_wr->hsize++] = copy->fd;
            if (copy->out_flags & PR_POLL_EXCEPT)
                if (NULL != pr_ex) pr_ex->harray[pr_ex->hsize++] = copy->fd;
        }
    }
    PR_DELETE(poll);

    return npds;
out_of_memory:
    PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
    return -1;    

#endif /* !defined(NEED_SELECT) */
    
}
示例#25
0
/*
** The workhorse sprintf code.
*/
static int dosprintf(SprintfState *ss, const char *fmt, va_list ap)
{
    char c;
    int flags, width, prec, radix, type;
    union {
	char ch;
	int i;
	long l;
	PRInt64 ll;
	double d;
	const char *s;
	int *ip;
    } u;
    const char *fmt0;
    static char *hex = "0123456789abcdef";
    static char *HEX = "0123456789ABCDEF";
    char *hexp;
    int rv, i;
    struct NumArg* nas = NULL;
    struct NumArg* nap;
    struct NumArg  nasArray[ NAS_DEFAULT_NUM ];
    char  pattern[20];
    const char* dolPt = NULL;  /* in "%4$.2f", dolPt will point to . */


    /*
    ** build an argument array, IF the fmt is numbered argument
    ** list style, to contain the Numbered Argument list pointers
    */

    nas = BuildArgArray( fmt, ap, &rv, nasArray );
    if( rv < 0 ){
	/* the fmt contains error Numbered Argument format, [email protected] */
	PR_ASSERT(0);
	return rv;
    }

    while ((c = *fmt++) != 0) {
	if (c != '%') {
	    rv = (*ss->stuff)(ss, fmt - 1, 1);
	    if (rv < 0) {
		return rv;
	    }
	    continue;
	}
	fmt0 = fmt - 1;

	/*
	** Gobble up the % format string. Hopefully we have handled all
	** of the strange cases!
	*/
	flags = 0;
	c = *fmt++;
	if (c == '%') {
	    /* quoting a % with %% */
	    rv = (*ss->stuff)(ss, fmt - 1, 1);
	    if (rv < 0) {
		return rv;
	    }
	    continue;
	}

	if( nas != NULL ){
	    /* the fmt contains the Numbered Arguments feature */
	    i = 0;
	    while( c && c != '$' ){	    /* should imporve error check later */
		i = ( i * 10 ) + ( c - '0' );
		c = *fmt++;
	    }

	    if( nas[i-1].type == TYPE_UNKNOWN ){
		if( nas && ( nas != nasArray ) )
		    PR_DELETE( nas );
		return -1;
	    }

	    nap = &nas[i-1];
	    dolPt = fmt;
	    c = *fmt++;
	}

	/*
	 * Examine optional flags.  Note that we do not implement the
	 * '#' flag of sprintf().  The ANSI C spec. of the '#' flag is
	 * somewhat ambiguous and not ideal, which is perhaps why
	 * the various sprintf() implementations are inconsistent
	 * on this feature.
	 */
#ifdef VBOX
        /* this is not expected so just ignore this flags */
        while (c == '#')
            c = *fmt++;
#endif
	while ((c == '-') || (c == '+') || (c == ' ') || (c == '0')) {
	    if (c == '-') flags |= FLAG_LEFT;
	    if (c == '+') flags |= FLAG_SIGNED;
	    if (c == ' ') flags |= FLAG_SPACED;
	    if (c == '0') flags |= FLAG_ZEROS;
	    c = *fmt++;
	}
	if (flags & FLAG_SIGNED) flags &= ~FLAG_SPACED;
	if (flags & FLAG_LEFT) flags &= ~FLAG_ZEROS;

	/* width */
	if (c == '*') {
	    c = *fmt++;
	    width = va_arg(ap, int);
	} else {
示例#26
0
PR_IMPLEMENT(PRStatus) PR_GetConnectStatus(const PRPollDesc *pd)
{
    PRInt32 osfd;
    PRFileDesc *bottom = pd->fd;
    int err, len;

    if (pd->out_flags & PR_POLL_NVAL) {
        PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0);
        return PR_FAILURE;
    }
    if ((pd->out_flags & (PR_POLL_WRITE | PR_POLL_EXCEPT | PR_POLL_ERR)) == 0) {
        PR_ASSERT(pd->out_flags == 0);
        PR_SetError(PR_IN_PROGRESS_ERROR, 0);
        return PR_FAILURE;
    }

    while (bottom->lower != NULL) {
        bottom = bottom->lower;
    }
    osfd = bottom->secret->md.osfd;

#if defined(XP_UNIX)

    err = _MD_unix_get_nonblocking_connect_error(osfd);
    if (err != 0) {
        _PR_MD_MAP_CONNECT_ERROR(err);
        return PR_FAILURE;
    }
    return PR_SUCCESS;

#elif defined(WIN32) || defined(WIN16)

    if (pd->out_flags & PR_POLL_EXCEPT) {
#if defined(WIN32)
/* Note: There is a bug in Win32 WinSock. The sleep circumvents the
** bug. See wtc. /s lth.
*/
        Sleep(0);
#endif /* WIN32 */
        len = sizeof(err);
        if (getsockopt(osfd, (int)SOL_SOCKET, SO_ERROR, (char *) &err, &len)
                == SOCKET_ERROR) {
            _PR_MD_MAP_GETSOCKOPT_ERROR(WSAGetLastError());
            return PR_FAILURE;
        }
        if (err != 0) {
            _PR_MD_MAP_CONNECT_ERROR(err);
        } else {
            PR_SetError(PR_UNKNOWN_ERROR, 0);
        }
        return PR_FAILURE;
    }

    PR_ASSERT(pd->out_flags & PR_POLL_WRITE);
    return PR_SUCCESS;

#elif defined(XP_OS2)

    if (pd->out_flags & PR_POLL_EXCEPT) {
        len = sizeof(err);
        if (getsockopt(osfd, SOL_SOCKET, SO_ERROR, (char *) &err, &len)
                < 0) {
            _PR_MD_MAP_GETSOCKOPT_ERROR(sock_errno());
            return PR_FAILURE;
        }
        if (err != 0) {
            _PR_MD_MAP_CONNECT_ERROR(err);
        } else {
            PR_SetError(PR_UNKNOWN_ERROR, 0);
        }
        return PR_FAILURE;
    }

    PR_ASSERT(pd->out_flags & PR_POLL_WRITE);
    return PR_SUCCESS;

#elif defined(XP_MAC)

    err = _MD_mac_get_nonblocking_connect_error(osfd);
    if (err == -1)
        return PR_FAILURE;
	else     
		return PR_SUCCESS;

#else
    PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
    return PR_FAILURE;
#endif
}
示例#27
0
static void PR_CALLBACK
clientThreadFunc(void *arg)
{
    PRUintn port = (PRUintn)arg;
    PRFileDesc *sock;
    PRNetAddr addr;
    char buf[CHUNK_SIZE];
    int i;
    PRIntervalTime unitTime = PR_MillisecondsToInterval(UNIT_TIME);
    PRIntn optval = 1;
    PRStatus retVal;
    PRInt32 nBytes;

    addr.inet.family = AF_INET;
    addr.inet.port = PR_htons((PRUint16)port);
    addr.inet.ip = PR_htonl(INADDR_LOOPBACK);
    PR_snprintf(buf, sizeof(buf), "%hu", addr.inet.ip);

    /* time 1 */
    PR_Sleep(unitTime);
    sock = PR_NewTCPSocket();
    PR_SetSockOpt(sock, PR_SockOpt_Nonblocking, &optval, sizeof(optval));
    retVal = PR_Connect(sock, &addr, PR_INTERVAL_NO_TIMEOUT);
    if (retVal == PR_FAILURE && PR_GetError() == PR_IN_PROGRESS_ERROR) {
#if !defined(USE_PR_SELECT)
	PRPollDesc pd;
	PRInt32 n;
	fprintf(stderr, "connect: EWOULDBLOCK, good\n");
	pd.fd = sock;
	pd.in_flags = PR_POLL_WRITE;
	n = PR_Poll(&pd, 1, PR_INTERVAL_NO_TIMEOUT);
	PR_ASSERT(n == 1);
        PR_ASSERT(pd.out_flags == PR_POLL_WRITE);
#else
        PR_fd_set writeSet;
        PRInt32 n;
        fprintf(stderr, "connect: EWOULDBLOCK, good\n");
        PR_FD_ZERO(&writeSet);
        PR_FD_SET(sock, &writeSet);
        n = PR_Select(0, NULL, &writeSet, NULL, PR_INTERVAL_NO_TIMEOUT);
        PR_ASSERT(n == 1);
        PR_ASSERT(PR_FD_ISSET(sock, &writeSet));
#endif
    }
    printf("client connected\n");
    fflush(stdout);

    /* time 4, 7, 11, etc. */
    for (i = 0; i < NUMBER_ROUNDS; i++) {
        PR_Sleep(3 * unitTime);
    	nBytes = PR_Write(sock, buf, sizeof(buf));
	    if (nBytes == -1) {
	    if (PR_GetError() == PR_WOULD_BLOCK_ERROR) {
		fprintf(stderr, "write: EWOULDBLOCK\n");
		exit(1);
            } else {
		fprintf(stderr, "write: failed\n");
            }
	}
	printf("client sent %d bytes\n", nBytes);
	fflush(stdout);
    }

    PR_Close(sock);
}
示例#28
0
static PRFileDesc* PR_CALLBACK SocketAccept(PRFileDesc *fd, PRNetAddr *addr,
PRIntervalTime timeout)
{
	PRInt32 osfd;
	PRFileDesc *fd2;
	PRUint32 al;
	PRThread *me = _PR_MD_CURRENT_THREAD();
#ifdef WINNT
	PRNetAddr addrCopy;
#endif

	if (_PR_PENDING_INTERRUPT(me)) {
		me->flags &= ~_PR_INTERRUPT;
		PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
		return 0;
	}
	if (_PR_IO_PENDING(me)) {
		PR_SetError(PR_IO_PENDING_ERROR, 0);
		return 0;
	}

#ifdef WINNT
	if (addr == NULL) {
		addr = &addrCopy;
	}
#endif
	al = sizeof(PRNetAddr);
	osfd = _PR_MD_ACCEPT(fd, addr, &al, timeout);
	if (osfd == -1)
		return 0;

	fd2 = PR_AllocFileDesc(osfd, PR_GetTCPMethods());
	if (!fd2) {
		_PR_MD_CLOSE_SOCKET(osfd);
		return NULL;
	}

	fd2->secret->nonblocking = fd->secret->nonblocking;
#ifdef WINNT
	fd2->secret->md.io_model_committed = PR_TRUE;
	PR_ASSERT(al == PR_NETADDR_SIZE(addr));
	fd2->secret->md.accepted_socket = PR_TRUE;
	memcpy(&fd2->secret->md.peer_addr, addr, al);
#endif

	/*
	 * On some platforms, the new socket created by accept()
	 * inherits the nonblocking (or overlapped io) attribute
	 * of the listening socket.  As an optimization, these
	 * platforms can skip the following _PR_MD_MAKE_NONBLOCK
	 * call.
	 */
#if !defined(SOLARIS) && !defined(IRIX) && !defined(WINNT)
	_PR_MD_MAKE_NONBLOCK(fd2);
#endif

	PR_ASSERT((NULL == addr) || (PR_NETADDR_SIZE(addr) == al));
#if defined(_PR_INET6)
	PR_ASSERT((NULL == addr) || (addr->raw.family == AF_INET)
		|| (addr->raw.family == AF_INET6));
#else
	PR_ASSERT((NULL == addr) || (addr->raw.family == AF_INET));
#endif

	return fd2;
}
void Resolver :: ar_receive()
{
    char ar_rcvbuf[HFIXEDSZ + MAXPACKET];
    HEADER* hptr = NULL;        /* Name Server query header */
    DNSSession* session = NULL;
    int rc = 0;
    datapacket* newpkt = NULL;
    unsigned int id = 0;

    if (ar_vc)
        rc = PR_Recv(afd, ar_rcvbuf, HFIXEDSZ+MAXPACKET, 0, 
            PR_INTERVAL_NO_TIMEOUT);
    else
        rc = PR_Read(afd, ar_rcvbuf,  HFIXEDSZ+MAXPACKET);

    ar_reinfo.re_replies++;

    /* Create a reslist_pkt_t to queue against the reslist */
    newpkt = new datapacket();
    PR_ASSERT(newpkt);

    newpkt->next = NULL;
    if (rc >0)
    {
        // packet received

	    /*
	     * Wakeup corresponding thread.
	     */
	    hptr = (HEADER *)ar_rcvbuf;
	    /*
	     * convert things to be in the right order.
	     */
	    id = ntohs(hptr->id);
	    /*
	     * response for an id which we have already received an answer for
	     * just ignore this response.
	     */
	    session = DNShash.lookup(id);
	    if (!session)
        {            
            delete(newpkt);
	        /* Request no longer in queue, so just return. */
	        return;
	    }

        newpkt->buflen = rc;
        memset(newpkt, 0, HFIXEDSZ + MAXPACKET);
        memcpy(newpkt, ar_rcvbuf, rc);
    }
    else
    {
        // no packet received
        newpkt->buflen = 0;
    }

    // Append new data packet to end of known data packets
    session->reslist_add_pkt(newpkt);

    session->setStatus(DNS_RCVD);

    // Wakeup corresponding thread.

    DNShash.remove(session); // remove this completed session from the hash table
    session->complete();
}
示例#30
0
文件: aclinit.c 项目: Firstyear/ds
int
aclinit_search_and_update_aci ( int thisbeonly, const Slapi_DN *base,
								char *be_name, int scope, int op,
								acl_lock_flag_t lock_flag )
{
	char				*attrs[2] = { "aci", NULL };
	 /* Tell __aclinit_handler whether it's an add or a delete */
	Slapi_PBlock 	*aPb;
	LDAPControl		**ctrls=NULL;
	struct berval	*bval;
	aclinit_handler_callback_data_t call_back_data;

	PR_ASSERT( lock_flag == DONT_TAKE_ACLCACHE_WRITELOCK ||
				lock_flag == DO_TAKE_ACLCACHE_WRITELOCK);

	if ( thisbeonly && be_name == NULL) {
		slapi_log_err(SLAPI_LOG_ERR, plugin_name, 
						"aclinit_search_and_update_aci - be_name must be specified.\n");
		return -1;
	}


	/*
	 * We need to explicitly request (objectclass=ldapsubentry)
	 * in order to get all the subentry acis too.
	 * Note that subentries can be added under subentries (although its not
	 * recommended) so that
	 * there may be non-trivial acis under a subentry.
	*/ 

	/* Use new search internal API                 */
	/* and never retrieve aci from a remote server */
	aPb = slapi_pblock_new ();
		
	/*
	 * Set up the control to say "Only get acis from this Backend--
	 * there may be more backends under this one.
	*/

	if ( thisbeonly ) {		
		
		bval = (struct berval *)slapi_ch_malloc(sizeof(struct berval));
		bval->bv_len = strlen(be_name) + 1;
		bval->bv_val = slapi_ch_strdup(be_name);

		ctrls = (LDAPControl **)slapi_ch_calloc( 2, sizeof(LDAPControl *));
		ctrls[0] = NULL;
		ctrls[1] = NULL;
	
		slapi_build_control_from_berval(
										MTN_CONTROL_USE_ONE_BACKEND_OID,
                						bval,
										1 /* is critical */, 
										ctrls);

	}	

	slapi_search_internal_set_pb (	aPb,
					slapi_sdn_get_dn(base),
					scope,
					"(|(aci=*)(objectclass=ldapsubentry))",
					attrs,
					0 /* attrsonly */,
					ctrls /* controls: SLAPI_ARGCONTROLS */,
					NULL /* uniqueid */,
					aclplugin_get_identity (ACL_PLUGIN_IDENTITY),
					SLAPI_OP_FLAG_NEVER_CHAIN /* actions : get local aci only */);
	
	if (thisbeonly) {
		slapi_pblock_set(aPb, SLAPI_REQCONTROLS, ctrls);
	}

	call_back_data.op = op;
	call_back_data.retCode = 0;
	call_back_data.lock_flag = lock_flag;

	slapi_search_internal_callback_pb(aPb,
					  &call_back_data /* callback_data */,
					  NULL/* result_callback */,
					  __aclinit_handler,
					  NULL /* referral_callback */);

	if (thisbeonly) {				
		slapi_ch_free((void **)&bval);				
	}	

	/*
	 * This frees the control oid, the bv_val and the control itself and the 
	 * ctrls array mem by caling ldap_controls_free()--so we
	 * don't need to do it ourselves.
	*/
	slapi_pblock_destroy (aPb);
	
	return call_back_data.retCode; 

}