コード例 #1
0
ファイル: edsc.c プロジェクト: dehnert/discuss
void our_com_err(const char *who, long code, const char *fmt, va_list args)
{
  /* A simple com_err that keeps library errors from confusing emacs */
  fprintf(stderr, ";%s: %s\n", who, error_message(code));
}
コード例 #2
0
ファイル: auth.c プロジェクト: joshtriplett/tin-sample
/*
 * Read the ${TIN_HOMEDIR:-"$HOME"}/.newsauth file and put authentication
 * username and password for the specified server in the given strings.
 * Returns TRUE if at least a password was found, FALSE if there was
 * no .newsauth file or no matching server.
 */
static t_bool
read_newsauth_file(
	char *server,
	char *authuser,
	char *authpass)
{
	FILE *fp;
	char *_authpass;
	char *ptr;
	char filename[PATH_LEN];
	char line[PATH_LEN];
	int found = 0;
	int fd;
	struct stat statbuf;

	joinpath(filename, sizeof(filename), homedir, ".newsauth");

	if ((fp = fopen(filename, "r"))) {
		if ((fd = fileno(fp)) == -1) {
			fclose(fp);
			return FALSE;
		}
		if (fstat(fd, &statbuf) == -1) {
			fclose(fp);
			return FALSE;
		}

#	ifndef FILE_MODE_BROKEN
		if (S_ISREG(statbuf.st_mode) && (statbuf.st_mode|S_IRUSR|S_IWUSR) != (S_IRUSR|S_IWUSR|S_IFREG)) {
			error_message(4, _(txt_error_insecure_permissions), filename, statbuf.st_mode);
			/*
			 * TODO: fix permssions?
			 * fchmod(fd, S_IRUSR|S_IWUSR);
			 */
		}
#	endif /* !FILE_MODE_BROKEN */

		/*
		 * Search through authorization file for correct NNTP server
		 * File has format: 'nntp-server' 'password' ['username']
		 */
		while (fgets(line, sizeof(line), fp) != NULL) {
			/* strip trailing newline character */
			ptr = strchr(line, '\n');
			if (ptr != NULL)
				*ptr = '\0';

			/* Get server from 1st part of the line */
			ptr = strpbrk(line, " \t");

			if (ptr == NULL)		/* no passwd, no auth, skip */
				continue;

			*ptr++ = '\0';		/* cut off server part */

			if ((strcasecmp(line, server)))
				continue;		/* wrong server, keep on */

			/* Get password from 2nd part of the line */
			while (*ptr == ' ' || *ptr == '\t')
				ptr++;	/* skip any blanks */

			_authpass = ptr;

			if (*_authpass == '"') {	/* skip "embedded" password string */
				ptr = strrchr(_authpass, '"');
				if ((ptr != NULL) && (ptr > _authpass)) {
					_authpass++;
					*ptr++ = '\0';	/* cut off trailing " */
				} else	/* no matching ", proceede as normal */
					ptr = _authpass;
			}

			/* Get user from 3rd part of the line */
			ptr = strpbrk(ptr, " \t");	/* find next separating blank */

			if (ptr != NULL) {	/* a 3rd argument follows */
				while (*ptr == ' ' || *ptr == '\t')	/* skip any blanks */
					*ptr++ = '\0';
				if (*ptr != '\0')	/* if its not just empty */
					strcpy(authuser, ptr);	/* so will replace default user */
			}
			strcpy(authpass, _authpass);
			found++;
			break;	/* if we end up here, everything seems OK */
		}
		fclose(fp);
		return (found > 0);
	}
	return FALSE;
}
コード例 #3
0
ファイル: filterbank_header.c プロジェクト: gitj/dspsr
void filterbank_header(FILE *outptr) /* includefile */
{
  if (sigproc_verbose)
    fprintf (stderr, "sigproc::filterbank_header\n");

  int i,j;
  output=outptr;
  if (obits == -1) obits=nbits;
  /* go no further here if not interested in header parameters */

  if (headerless)
  {
    if (sigproc_verbose)
      fprintf (stderr, "sigproc::filterbank_header headerless - abort\n");
    return;
  }

  if (sigproc_verbose)
    fprintf (stderr, "sigproc::filterbank_header HEADER_START");

  send_string("HEADER_START");
  send_string("rawdatafile");
  send_string(inpfile);
  if (!strings_equal(source_name,""))
  {
    send_string("source_name");
    send_string(source_name);
  }
    send_int("machine_id",machine_id);
    send_int("telescope_id",telescope_id);
    send_coords(src_raj,src_dej,az_start,za_start);
    if (zerolagdump) {
      /* time series data DM=0.0 */
      send_int("data_type",2);
      refdm=0.0;
      send_double("refdm",refdm);
      send_int("nchans",1);
    } else {
      /* filterbank data */
      send_int("data_type",1);
      send_double("fch1",fch1);
      send_double("foff",foff);
      send_int("nchans",nchans);
    }
    /* beam info */
    send_int("nbeams",nbeams);
    send_int("ibeam",ibeam);
    /* number of bits per sample */
    send_int("nbits",obits);
    /* start time and sample interval */
    send_double("tstart",tstart+(double)start_time/86400.0);
    send_double("tsamp",tsamp);
    if (sumifs) {
      send_int("nifs",1);
    } else {
      j=0;
      for (i=1;i<=nifs;i++) if (ifstream[i-1]=='Y') j++;
      if (j==0) error_message("no valid IF streams selected!");
      send_int("nifs",j);
    }
    send_string("HEADER_END");
}
コード例 #4
0
ファイル: network_http.cpp プロジェクト: xapantu/stkolddroid
CURLcode NetworkHttp::init()
{
    news_manager->clearErrorMessage();
    core::stringw error_message("");
    // The news message must be updated if either it has never been updated,
    // or if the time of the last update was more than news_frequency ago.
    bool download = UserConfigParams::m_news_last_updated==0  ||
                    UserConfigParams::m_news_last_updated
                        +UserConfigParams::m_news_frequency
                    < Time::getTimeSinceEpoch();

    if(!download)
    {
        // If there is no old news message file, force a new download
        std::string xml_file = file_manager->getAddonsFile("news.xml");
        if(!file_manager->fileExists(xml_file))
            download=true;
    }

    // Initialise the online portion of the addons manager.
    if(download && UserConfigParams::logAddons())
        printf("[addons] Downloading list.\n");

    Request r(Request::HC_DOWNLOAD_FILE, 9999, false,
              "news.xml", "news.xml");
    CURLcode status = download ? downloadFileInternal(&r)
                               : CURLE_OK;
    if(download && 
        status==CURLE_COULDNT_RESOLVE_HOST)
    {
        // Assume that the server address is wrong. And retry
        // with the default server address again (just in case
        // that a redirect went wrong, or a wrong/incorrect
        // address somehow made its way into the config file.
        UserConfigParams::m_server_addons.revertToDefaults();
        status = downloadFileInternal(&r);
    }

    if(status==CURLE_OK)
    {
        std::string xml_file = file_manager->getAddonsFile("news.xml");
        if(download)
            UserConfigParams::m_news_last_updated = Time::getTimeSinceEpoch();
        const XMLNode *xml = new XMLNode(xml_file);

        // A proper news file has at least a version number, mtime, and
        // frequency defined. If this is not the case, assume that
        // it's an invalid download. Try downloading again after
        // resetting the news server back to the default.
        int version=-1;
        if( !xml->get("version", &version) || version!=1 ||
             !xml->get("mtime", &version)  ||
             !xml->get("frequency", &version)                )
        {
            UserConfigParams::m_server_addons.revertToDefaults();
            status = downloadFileInternal(&r);
            if(status==CURLE_OK)
                UserConfigParams::m_news_last_updated = 
                    Time::getTimeSinceEpoch();
            delete xml;
            xml = new XMLNode(xml_file);
        }
        news_manager->init();
        status = loadAddonsList(xml, xml_file);
        delete xml;
        if(status==CURLE_OK)
        {
            return status;
        }
        else
        {
            // This message must be translated dynamically in the main menu.
            // If it would be translated here, it wouldn't be translated
            // if the language is changed in the menu!
            error_message=
                N_("Can't download addons list, check terminal for details.");
        }
        // Now fall through to error handling.
    }
    else
    {
        // This message must be translated dynamically in the main menu.
        // If it would be translated here, it wouldn't be translated
        // if the language is changed in the menu!
        error_message=
            N_("Can't download news file, check terminal for details.");
    }

    // Abort requested by stk -> display no error message and return
    if(status==CURLE_ABORTED_BY_CALLBACK)
        return status;

    addons_manager->setErrorState();
    news_manager->setErrorMessage(error_message);

    if(UserConfigParams::logAddons())
        printf("[addons] %s\n", core::stringc(error_message).c_str());
    return status;
}   // init
コード例 #5
0
ファイル: alert.cpp プロジェクト: bendikro/libtorrent
	std::string scrape_failed_alert::message() const
	{
		return tracker_alert::message() + " scrape failed: " + error_message();
	}
コード例 #6
0
ファイル: auks_krb5_cred.c プロジェクト: 3van/auks
int
auks_krb5_cred_deladdr_buffer(char *in_buf,size_t in_buf_len,
			      char** pout_buf,size_t *pout_buf_len)
{
	int fstatus = AUKS_ERROR ;

	/* kerberos related variables */
	krb5_error_code err_code;
	krb5_context context;
	krb5_auth_context auth_context;

	krb5_creds **creds;
	krb5_data data;
	krb5_replay_data krdata;

	krb5_data *p_outbuf;

	krb5_creds fwd_cred;
	krb5_creds *p_cred_out = NULL;

	krb5_address **addresses;

	char* buffer;
	size_t length;

	/* initialize kerberos context */
	err_code = krb5_init_context(&context);
	if (err_code) {
		auks_error("unable to initialize kerberos context : %s",
			   error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_INIT_CTX ; 
		goto exit;
	}
	auks_log("kerberos context successfully initialized");

	/* initialize a nullified kerberos authentication context in order */
	/* to decode credential from buffer */
	err_code = krb5_auth_con_init(context, &auth_context);
	if (err_code) {
		auks_error("unable to initialize kerberos authentication"
			   " context : %s",error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_INIT_AUTH_CTX ;
		goto ctx_exit;
	}
	auks_log("kerberos authentication context successfully initialized");

	/* clear kerberos authentication context flags */
	krb5_auth_con_setflags(context, auth_context, 0);

	/* build a kerberos data structure with input buffer */
	data.data = in_buf;
	data.length = in_buf_len;

	/* build kerberos credential structure using this data structure */
	err_code = krb5_rd_cred(context, auth_context, &data,&creds,&krdata);
	if (err_code) {
		auks_error("unable to deserialize credential data : %s",
			   error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_RD_CRED ;
		goto auth_ctx_exit;
	}
	auks_log("credential data successfully deserialized");

	memset(&fwd_cred, 0,sizeof(fwd_cred));

	/* copy client principal in futur credential */
	err_code = krb5_copy_principal(context,(*creds)->client,
				       &fwd_cred.client);
	if (err_code) {
		auks_error("unable to put client principal into "
			   "request cred : %s",error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_CP_PRINC ;
		goto cred_exit;
	}
	auks_log("client principal successfully put into request cred");

	/* copy krbtgt/... principal in futur credential as required */
	/* server principal for TGS */
	err_code = krb5_copy_principal(context,(*creds)->server,
				       &fwd_cred.server);
	if (err_code) {
		auks_error("unable to put server principal into "
			   "request cred : %s",error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_CP_PRINC ;
		goto cred_exit;
	}
	auks_log("server principal successfully put into request cred");

	/* get addressless forwarded ticket */
	err_code = krb5_get_cred_via_tkt(context,(*creds),
					 ( KDC_OPT_CANONICALIZE |
					   KDC_OPT_FORWARDED |
					   ( (*creds)->ticket_flags &
					     KDC_TKT_COMMON_MASK )  ),
					 addresses=NULL,
					 &fwd_cred,&p_cred_out);
	if (err_code) {
		auks_error("unable to get addressless forwarded cred from auks"
			   " cred buffer : %s",error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_GET_FWD_CRED ;
		goto cred_exit;
	}
	auks_log("addressless forwarded cred successfully"
		 " got using auks cred buffer");

	/* extract credential data */
	err_code = krb5_mk_1cred(context,auth_context,p_cred_out,
				 &p_outbuf,&krdata);
	if (err_code) {
		auks_error("unable to dump credential into working buffer : %s",
			   error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_MK_CRED ;
		goto fwd_exit;
	}
	auks_log("credential successfully dumped into buffer");

	/* allocate output buffer */
	length = p_outbuf->length;
	buffer = (char *) malloc(length * sizeof(char));
	if (buffer == NULL) {
		auks_error("unable to allocate memory for credential data "
			   "storage");
		fstatus = AUKS_ERROR_KRB5_CRED_MALLOC ;
		goto mk_exit;
	}

	/* copy credential data into output buffer */
	memcpy(buffer,p_outbuf->data,length);
	*pout_buf = buffer;
	*pout_buf_len = length;
	auks_log("credential successfully stored in output buffer");
	fstatus = AUKS_SUCCESS ;

	auks_log("in length : %u | out length : %u",
		 in_buf_len,
		 p_outbuf->length);
mk_exit:
	krb5_free_data(context,p_outbuf);

fwd_exit:
	krb5_free_creds(context,p_cred_out);

cred_exit:
	krb5_free_cred_contents(context,&fwd_cred);
	krb5_free_creds(context, *creds);
	free(creds);

auth_ctx_exit:
	krb5_auth_con_free(context, auth_context);

ctx_exit:
	krb5_free_context(context);

exit:
	return fstatus;
}
コード例 #7
0
ファイル: ksetpwd.c プロジェクト: Akasurde/krb5
int main( int argc, char ** argv )
{
    char * new_password;
    char * new_password2;
    krb5_context    kcontext;
    krb5_error_code kerr;
    krb5_principal  target_principal;


    if( argc < 2 )
    {
        fprintf( stderr, "Usage: setpass user@REALM\n");
        exit(1);
    }

/*
** verify credentials -
*/
    if( verify_creds() )
        init_creds();
    if( verify_creds() )
    {
        fprintf( stderr, "No user credentials available\n");
        exit(1);
    }
/*
** check the principal name -
*/
    krb5_init_context(&kcontext);
    kerr = krb5_parse_name( kcontext, argv[1], &target_principal );

    {
        char * pname = NULL;
        kerr = krb5_unparse_name( kcontext, target_principal, &pname );
        printf( "Changing password for %s:\n", pname);
        fflush( stdout );
        free( pname );
    }
/*
** get the new password -
*/
    for (;;)
    {
        new_password = getpass("Enter new password: "******"Verify new password: "******"Passwords do not match\n");
        free( new_password );
        free( new_password2 );
    }
/*
** change the password -
*/
    {
        int pw_result;
        krb5_ccache ccache;
        krb5_data       pw_res_string, res_string;

        kerr = krb5_cc_default( kcontext, &ccache );
        if( kerr == 0 )
        {
            kerr = krb5_set_password_using_ccache(kcontext, ccache, new_password, target_principal,
                                                  &pw_result, &pw_res_string, &res_string );
            if( kerr )
                fprintf( stderr, "Failed: %s\n", error_message(kerr) );
            else
            {
                if( pw_result )
                {
                    fprintf( stderr, "Failed(%d)", pw_result );
                    if( pw_res_string.length > 0 )
                        fprintf( stderr, ": %s", pw_res_string.data);
                    if( res_string.length > 0 )
                        fprintf( stderr, " %s", res_string.data);
                    fprintf( stderr, "\n");
                }
            }
        }
    }
    return(0);
}
コード例 #8
0
ファイル: ipropd_svc.c プロジェクト: aosm/KerberosLibraries
kdb_incr_result_t *
iprop_get_updates_1_svc(kdb_last_t *arg, struct svc_req *rqstp)
{
    static kdb_incr_result_t ret;
    char *whoami = "iprop_get_updates_1";
    int kret;
    kadm5_server_handle_t handle = global_server_handle;
    char *client_name = 0, *service_name = 0;
    char obuf[256] = {0};

    /* default return code */
    ret.ret = UPDATE_ERROR;

    DPRINT(("%s: start, last_sno=%lu\n", whoami,
	    (unsigned long) arg->last_sno));

    if (!handle) {
	krb5_klog_syslog(LOG_ERR,
			 _("%s: server handle is NULL"),
			 whoami);
	goto out;
    }

    {
	gss_buffer_desc client_desc, service_desc;

	if (setup_gss_names(rqstp, &client_desc, &service_desc) < 0) {
	    krb5_klog_syslog(LOG_ERR,
			     _("%s: setup_gss_names failed"),
			     whoami);
	    goto out;
	}
	client_name = buf_to_string(&client_desc);
	service_name = buf_to_string(&service_desc);
	if (client_name == NULL || service_name == NULL) {
	    free(client_name);
	    free(service_name);
	    krb5_klog_syslog(LOG_ERR,
			     "%s: out of memory recording principal names",
			     whoami);
	    goto out;
	}
    }

    DPRINT(("%s: clprinc=`%s'\n\tsvcprinc=`%s'\n",
	    whoami, client_name, service_name));

    if (!kadm5int_acl_check(handle->context,
			    rqst2name(rqstp),
			    ACL_IPROP,
			    NULL,
			    NULL)) {
	ret.ret = UPDATE_PERM_DENIED;

	krb5_klog_syslog(LOG_NOTICE, LOG_UNAUTH, whoami,
			 "<null>", client_name, service_name,
			 client_addr(rqstp));
	goto out;
    }

    kret = ulog_get_entries(handle->context, *arg, &ret);

    if (ret.ret == UPDATE_OK) {
	(void) snprintf(obuf, sizeof (obuf),
			_("%s; Incoming SerialNo=%lu; Outgoing SerialNo=%lu"),
			replystr(ret.ret),
			(unsigned long)arg->last_sno,
			(unsigned long)ret.lastentry.last_sno);
    } else {
	(void) snprintf(obuf, sizeof (obuf),
			_("%s; Incoming SerialNo=%lu; Outgoing SerialNo=N/A"),
			replystr(ret.ret),
			(unsigned long)arg->last_sno);
    }

    krb5_klog_syslog(LOG_NOTICE, LOG_DONE, whoami,
		     obuf,
		     ((kret == 0) ? "success" : error_message(kret)),
		     client_name, service_name,
		     client_addr(rqstp));

out:
    if (nofork)
	debprret(whoami, ret.ret, ret.lastentry.last_sno);
    free(client_name);
    free(service_name);
    return (&ret);
}
コード例 #9
0
ファイル: ipropd_svc.c プロジェクト: aosm/KerberosLibraries
kdb_fullresync_result_t *
iprop_full_resync_1_svc(/* LINTED */ void *argp, struct svc_req *rqstp)
{
    static kdb_fullresync_result_t ret;
    char *tmpf = 0;
    char *ubuf = 0;
    char clhost[MAXHOSTNAMELEN] = {0};
    int pret, fret;
    kadm5_server_handle_t handle = global_server_handle;
    OM_uint32 min_stat;
    gss_name_t name = NULL;
    char *client_name = NULL, *service_name = NULL;
    char *whoami = "iprop_full_resync_1";

    /* default return code */
    ret.ret = UPDATE_ERROR;

    if (!handle) {
	krb5_klog_syslog(LOG_ERR,
			 _("%s: server handle is NULL"),
			 whoami);
	goto out;
    }

    DPRINT(("%s: start\n", whoami));

    {
	gss_buffer_desc client_desc, service_desc;

	if (setup_gss_names(rqstp, &client_desc, &service_desc) < 0) {
	    krb5_klog_syslog(LOG_ERR,
			     _("%s: setup_gss_names failed"),
			     whoami);
	    goto out;
	}
	client_name = buf_to_string(&client_desc);
	service_name = buf_to_string(&service_desc);
	if (client_name == NULL || service_name == NULL) {
	    free(client_name);
	    free(service_name);
	    krb5_klog_syslog(LOG_ERR,
			     "%s: out of memory recording principal names",
			     whoami);
	    goto out;
	}
    }

    DPRINT(("%s: clprinc=`%s'\n\tsvcprinc=`%s'\n",
	    whoami, client_name, service_name));

    if (!kadm5int_acl_check(handle->context,
			    rqst2name(rqstp),
			    ACL_IPROP,
			    NULL,
			    NULL)) {
	ret.ret = UPDATE_PERM_DENIED;

	krb5_klog_syslog(LOG_NOTICE, LOG_UNAUTH, whoami,
			 "<null>", client_name, service_name,
			 client_addr(rqstp));
	goto out;
    }

    if (!getclhoststr(client_name, clhost, sizeof (clhost))) {
	krb5_klog_syslog(LOG_ERR,
			 _("%s: getclhoststr failed"),
			 whoami);
	goto out;
    }

    /*
     * construct db dump file name; kprop style name + clnt fqdn
     */
    if (asprintf(&tmpf, "%s_%s", KPROP_DEFAULT_FILE, clhost) < 0) {
	krb5_klog_syslog(LOG_ERR,
			 _("%s: unable to construct db dump file name; out of memory"),
			 whoami);
	goto out;
    }

    /*
     * note the -i; modified version of kdb5_util dump format
     * to include sno (serial number)
     */
    if (asprintf(&ubuf, "%s dump -i %s", KPROPD_DEFAULT_KDB5_UTIL,
		 tmpf) < 0) {
	krb5_klog_syslog(LOG_ERR,
			 _("%s: cannot construct kdb5 util dump string too long; out of memory"),
			 whoami);
	goto out;
    }

    /*
     * Fork to dump the db and xfer it to the slave.
     * (the fork allows parent to return quickly and the child
     * acts like a callback to the slave).
     */
    fret = fork();
    DPRINT(("%s: fork=%d (%d)\n", whoami, fret, getpid()));

    switch (fret) {
    case -1: /* error */
	if (nofork) {
	    perror(whoami);
	}
	krb5_klog_syslog(LOG_ERR,
			 _("%s: fork failed: %s"),
			 whoami,
			 error_message(errno));
	goto out;

    case 0: /* child */
	DPRINT(("%s: run `%s' ...\n", whoami, ubuf));
	(void) signal(SIGCHLD, SIG_DFL);
	/* run kdb5_util(1M) dump for IProp */
	/* XXX popen can return NULL; is pclose(NULL) okay?  */
	pret = pclose(popen(ubuf, "w"));
	DPRINT(("%s: pclose=%d\n", whoami, pret));
	if (pret != 0) {
	    /* XXX popen/pclose may not set errno
	       properly, and the error could be from the
	       subprocess anyways.  */
	    if (nofork) {
		perror(whoami);
	    }
	    krb5_klog_syslog(LOG_ERR,
			     _("%s: pclose(popen) failed: %s"),
			     whoami,
			     error_message(errno));
	    goto out;
	}

	DPRINT(("%s: exec `kprop -f %s %s' ...\n",
		whoami, tmpf, clhost));
	/* XXX Yuck!  */
	if (getenv("KPROP_PORT"))
	    pret = execl(KPROPD_DEFAULT_KPROP, "kprop", "-f", tmpf,
			 "-P", getenv("KPROP_PORT"),
			 clhost, NULL);
	else
	    pret = execl(KPROPD_DEFAULT_KPROP, "kprop", "-f", tmpf,
			 clhost, NULL);
	if (pret == -1) {
	    if (nofork) {
		perror(whoami);
	    }
	    krb5_klog_syslog(LOG_ERR,
			     _("%s: exec failed: %s"),
			     whoami,
			     error_message(errno));
	    goto out;
	}

    default: /* parent */
	ret.ret = UPDATE_OK;
	/* not used by slave (sno is retrieved from kdb5_util dump) */
	ret.lastentry.last_sno = 0;
	ret.lastentry.last_time.seconds = 0;
	ret.lastentry.last_time.useconds = 0;

	krb5_klog_syslog(LOG_NOTICE, LOG_DONE, whoami,
			 "<null>",
			 "success",
			 client_name, service_name,
			 client_addr(rqstp));

	goto out;
    }

out:
    if (nofork)
	debprret(whoami, ret.ret, 0);
    free(client_name);
    free(service_name);
    if (name)
	gss_release_name(&min_stat, &name);
    free(tmpf);
    free(ubuf);
    return (&ret);
}
コード例 #10
0
void proxy_copy(const char *tag, char *sequence, char *name, int myrights,
                int usinguid, struct backend *s)
{
    char mytag[128];
    struct d {
        char *idate;
        char *flags;
        unsigned int seqno, uid;
        struct d *next;
    } *head, *p, *q;
    int c;

    /* find out what the flags & internaldate for this message are */
    proxy_gentag(mytag, sizeof(mytag));
    prot_printf(backend_current->out,
                "%s %s %s (Flags Internaldate)\r\n",
                tag, usinguid ? "Uid Fetch" : "Fetch", sequence);
    head = (struct d *) xmalloc(sizeof(struct d));
    head->flags = NULL; head->idate = NULL;
    head->seqno = head->uid = 0;
    head->next = NULL;
    p = head;
    /* read all the responses into the linked list */
    for (/* each FETCH response */;;) {
        unsigned int seqno = 0, uidno = 0;
        char *flags = NULL, *idate = NULL;

        /* read a line */
        c = prot_getc(backend_current->in);
        if (c != '*') break;
        c = prot_getc(backend_current->in);
        if (c != ' ') { /* protocol error */ c = EOF; break; }

        /* check for OK/NO/BAD/BYE response */
        if (!isdigit(c = prot_getc(backend_current->in))) {
            prot_printf(imapd_out, "* %c", c);
            pipe_to_end_of_response(backend_current, 0);
            continue;
        }

        /* read seqno */
        prot_ungetc(c, backend_current->in);
        c = getuint32(backend_current->in, &seqno);
        if (seqno == 0 || c != ' ') {
            /* we suck and won't handle this case */
            c = EOF; break;
        }
        c = chomp(backend_current->in, "fetch (");
        if (c == EOF) {
            c = chomp(backend_current->in, "exists\r");
            if (c == '\n') { /* got EXISTS response */
                prot_printf(imapd_out, "* %d EXISTS\r\n", seqno);
                continue;
            }
        }
        if (c == EOF) {
            /* XXX  the "exists" check above will eat "ex" */
            c = chomp(backend_current->in, "punge\r");
            if (c == '\n') { /* got EXPUNGE response */
                prot_printf(imapd_out, "* %d EXPUNGE\r\n", seqno);
                continue;
            }
        }
        if (c == EOF) {
            c = chomp(backend_current->in, "recent\r");
            if (c == '\n') { /* got RECENT response */
                prot_printf(imapd_out, "* %d RECENT\r\n", seqno);
                continue;
            }
        }
        /* huh, don't get this response */
        if (c == EOF) break;
        for (/* each fetch item */;;) {
            /* looking at the first character in an item */
            switch (c) {
            case 'f': case 'F': /* flags? */
                c = chomp(backend_current->in, "lags");
                if (c != ' ') { c = EOF; }
                else c = prot_getc(backend_current->in);
                if (c != '(') { c = EOF; }
                else {
                    flags = grab(backend_current->in, ')');
                    c = prot_getc(backend_current->in);
                }
                break;
            case 'i': case 'I': /* internaldate? */
                c = chomp(backend_current->in, "nternaldate");
                if (c != ' ') { c = EOF; }
                else c = prot_getc(backend_current->in);
                if (c != '"') { c = EOF; }
                else {
                    idate = grab(backend_current->in, '"');
                    c = prot_getc(backend_current->in);
                }
                break;
            case 'u': case 'U': /* uid */
                c = chomp(backend_current->in, "id");
                if (c != ' ') { c = EOF; }
                else c = getuint32(backend_current->in, &uidno);
                break;
            default: /* hmm, don't like the smell of it */
                c = EOF;
                break;
            }
            /* looking at either SP seperating items or a RPAREN */
            if (c == ' ') { c = prot_getc(backend_current->in); }
            else if (c == ')') break;
            else { c = EOF; break; }
        }
        /* if c == EOF we have either a protocol error or a situation
           we can't handle, and we should die. */
        if (c == ')') c = prot_getc(backend_current->in);
        if (c == '\r') c = prot_getc(backend_current->in);
        if (c != '\n') {
            c = EOF;
            free(flags);
            free(idate);
            break;
        }

        /* if we're missing something, we should echo */
        if (!flags || !idate) {
            char sep = '(';
            prot_printf(imapd_out, "* %d FETCH ", seqno);
            if (uidno) {
                prot_printf(imapd_out, "%cUID %d", sep, uidno);
                sep = ' ';
            }
            if (flags) {
                prot_printf(imapd_out, "%cFLAGS %s", sep, flags);
                sep = ' ';
            }
            if (idate) {
                prot_printf(imapd_out, "%cINTERNALDATE %s", sep, flags);
                sep = ' ';
            }
            prot_printf(imapd_out, ")\r\n");
            if (flags) free(flags);
            if (idate) free(idate);
            continue;
        }

        /* add to p->next */
        p->next = xmalloc(sizeof(struct d));
        p = p->next;
        p->idate = idate;
        p->flags = editflags(flags);
        p->uid = uidno;
        p->seqno = seqno;
        p->next = NULL;
    }
    if (c != EOF) {
        prot_ungetc(c, backend_current->in);

        /* we should be looking at the tag now */
        pipe_until_tag(backend_current, tag, 0);
    }
    if (c == EOF) {
        /* uh oh, we're not happy */
        fatal("Lost connection to selected backend", EC_UNAVAILABLE);
    }

    /* start the append */
    prot_printf(s->out, "%s Append {" SIZE_T_FMT "+}\r\n%s",
                tag, strlen(name), name);
    prot_printf(backend_current->out, "%s %s %s (Rfc822.peek)\r\n",
                mytag, usinguid ? "Uid Fetch" : "Fetch", sequence);
    for (/* each FETCH response */;;) {
        unsigned int seqno = 0, uidno = 0;

        /* read a line */
        c = prot_getc(backend_current->in);
        if (c != '*') break;
        c = prot_getc(backend_current->in);
        if (c != ' ') { /* protocol error */ c = EOF; break; }

        /* check for OK/NO/BAD/BYE response */
        if (!isdigit(c = prot_getc(backend_current->in))) {
            prot_printf(imapd_out, "* %c", c);
            pipe_to_end_of_response(backend_current, 0);
            continue;
        }

        /* read seqno */
        prot_ungetc(c, backend_current->in);
        c = getuint32(backend_current->in, &seqno);
        if (seqno == 0 || c != ' ') {
            /* we suck and won't handle this case */
            c = EOF; break;
        }
        c = chomp(backend_current->in, "fetch (");
        if (c == EOF) { /* not a fetch response */
            c = chomp(backend_current->in, "exists\r");
            if (c == '\n') { /* got EXISTS response */
                prot_printf(imapd_out, "* %d EXISTS\r\n", seqno);
                continue;
            }
        }
        if (c == EOF) { /* not an exists response */
            /* XXX  the "exists" check above will eat "ex" */
            c = chomp(backend_current->in, "punge\r");
            if (c == '\n') { /* got EXPUNGE response */
                prot_printf(imapd_out, "* %d EXPUNGE\r\n", seqno);
                continue;
            }
        }
        if (c == EOF) { /* not an exists response */
            c = chomp(backend_current->in, "recent\r");
            if (c == '\n') { /* got RECENT response */
                prot_printf(imapd_out, "* %d RECENT\r\n", seqno);
                continue;
            }
        }
        if (c == EOF) {
            /* huh, don't get this response */
            break;
        }
        /* find seqno in the list */
        p = head;
        while (p->next && seqno != p->next->seqno) p = p->next;
        if (!p->next) break;
        q = p->next;
        p->next = q->next;
        for (/* each fetch item */;;) {
            int sz = 0;

            switch (c) {
            case 'u': case 'U':
                c = chomp(backend_current->in, "id");
                if (c != ' ') { c = EOF; }
                else c = getuint32(backend_current->in, &uidno);
                break;

            case 'r': case 'R':
                c = chomp(backend_current->in, "fc822");
                if (c == ' ') c = prot_getc(backend_current->in);
                if (c != '{') {
                    /* NIL? */
                    eatline(backend_current->in, c);
                    c = EOF;
                }
                else c = getint32(backend_current->in, &sz);
                if (c == '}') c = prot_getc(backend_current->in);
                if (c == '\r') c = prot_getc(backend_current->in);
                if (c != '\n') c = EOF;

                if (c != EOF) {
                    /* append p to s->out */
                    prot_printf(s->out, " (%s) \"%s\" {%d+}\r\n",
                                q->flags, q->idate, sz);
                    while (sz) {
                        char buf[2048];
                        int j = (sz > (int) sizeof(buf) ?
                                 (int) sizeof(buf) : sz);

                        j = prot_read(backend_current->in, buf, j);
                        if(!j) break;
                        prot_write(s->out, buf, j);
                        sz -= j;
                    }
                    c = prot_getc(backend_current->in);
                }

                break; /* end of case */
            default:
                c = EOF;
                break;
            }
            /* looking at either SP seperating items or a RPAREN */
            if (c == ' ') { c = prot_getc(backend_current->in); }
            else if (c == ')') break;
            else { c = EOF; break; }
        }

        /* if c == EOF we have either a protocol error or a situation
           we can't handle, and we should die. */
        if (c == ')') c = prot_getc(backend_current->in);
        if (c == '\r') c = prot_getc(backend_current->in);
        if (c != '\n') { c = EOF; break; }

        /* free q */
        free(q->idate);
        free(q->flags);
        free(q);
    }
    if (c != EOF) {
        char *appenduid, *b;
        int res;

        /* pushback the first character of the tag we're looking at */
        prot_ungetc(c, backend_current->in);

        /* nothing should be left in the linked list */
        assert(head->next == NULL);

        /* ok, finish the append; we need the UIDVALIDITY and UIDs
           to return as part of our COPYUID response code */
        prot_printf(s->out, "\r\n");

        /* should be looking at 'mytag' on 'backend_current',
           'tag' on 's' */
        pipe_until_tag(backend_current, mytag, 0);
        res = pipe_until_tag(s, tag, 0);

        if (res == PROXY_OK) {
            if (myrights & ACL_READ) {
                appenduid = strchr(s->last_result.s, '[');
                /* skip over APPENDUID */
                if (appenduid) {
                    appenduid += strlen("[appenduid ");
                    b = strchr(appenduid, ']');
                    if (b) *b = '\0';
                    prot_printf(imapd_out, "%s OK [COPYUID %s] %s\r\n", tag,
                                appenduid, error_message(IMAP_OK_COMPLETED));
                }
                else
                    prot_printf(imapd_out, "%s OK %s\r\n", tag, s->last_result.s);
            }
            else {
                prot_printf(imapd_out, "%s OK %s\r\n", tag,
                            error_message(IMAP_OK_COMPLETED));
            }
        } else {
            prot_printf(imapd_out, "%s %s", tag, s->last_result.s);
        }
    } else {
        /* abort the append */
        prot_printf(s->out, " {0+}\r\n\r\n");
        pipe_until_tag(backend_current, mytag, 0);
        pipe_until_tag(s, tag, 0);

        /* report failure */
        prot_printf(imapd_out, "%s NO inter-server COPY failed\r\n", tag);
    }

    /* free dynamic memory */
    while (head) {
        p = head;
        head = head->next;
        if (p->idate) free(p->idate);
        if (p->flags) free(p->flags);
        free(p);
    }
}
コード例 #11
0
ファイル: pop.c プロジェクト: 0xAX/emacs
/*
 * Function: socket_connection
 *
 * Purpose: Opens the network connection with the mail host, without
 * 	doing any sort of I/O with it or anything.
 *
 * Arguments:
 * 	host	The host to which to connect.
 *	flags	Option flags.
 *
 * Return value: A file descriptor indicating the connection, or -1
 * 	indicating failure, in which case an error has been copied
 * 	into pop_error.
 */
static int
socket_connection (char *host, int flags)
{
  struct addrinfo *res, *it;
  struct addrinfo hints;
  int ret;
  struct servent *servent;
  struct sockaddr_in addr;
  char found_port = 0;
  const char *service;
  int sock;
  char *realhost;
#ifdef KERBEROS
#ifdef KERBEROS5
  krb5_error_code rem;
  krb5_context kcontext = 0;
  krb5_auth_context auth_context = 0;
  krb5_ccache ccdef;
  krb5_principal client, server;
  krb5_error *err_ret;
  register char *cp;
#else
  KTEXT ticket;
  MSG_DAT msg_data;
  CREDENTIALS cred;
  Key_schedule schedule;
  int rem;
#endif /* KERBEROS5 */
#endif /* KERBEROS */

  int try_count = 0;
  int connect_ok;

#ifdef WINDOWSNT
  {
    WSADATA winsockData;
    if (WSAStartup (0x101, &winsockData) == 0)
      have_winsock = 1;
  }
#endif

  memset (&addr, 0, sizeof (addr));
  addr.sin_family = AF_INET;

  /** "kpop" service is  never used: look for 20060515 to see why **/
#ifdef KERBEROS
  service = (flags & POP_NO_KERBEROS) ? POP_SERVICE : KPOP_SERVICE;
#else
  service = POP_SERVICE;
#endif

#ifdef HESIOD
  if (! (flags & POP_NO_HESIOD))
    {
      servent = hes_getservbyname (service, "tcp");
      if (servent)
	{
	  addr.sin_port = servent->s_port;
	  found_port = 1;
	}
    }
#endif
  if (! found_port)
    {
      servent = getservbyname (service, "tcp");
      if (servent)
	{
	  addr.sin_port = servent->s_port;
	}
      else
	{
  /** "kpop" service is  never used: look for 20060515 to see why **/
#ifdef KERBEROS
	  addr.sin_port = htons ((flags & POP_NO_KERBEROS) ?
				POP_PORT : KPOP_PORT);
#else
	  addr.sin_port = htons (POP_PORT);
#endif
	}
    }

#define POP_SOCKET_ERROR "Could not create socket for POP connection: "

  sock = socket (PF_INET, SOCK_STREAM, 0);
  if (sock < 0)
    {
      snprintf (pop_error, ERROR_MAX, "%s%s",
		POP_SOCKET_ERROR, strerror (errno));
      return (-1);

    }

  memset (&hints, 0, sizeof (hints));
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_flags = AI_CANONNAME;
  hints.ai_family = AF_INET;
  do
    {
      ret = getaddrinfo (host, service, &hints, &res);
      try_count++;
      if (ret != 0 && (ret != EAI_AGAIN || try_count == 5))
	{
	  strcpy (pop_error, "Could not determine POP server's address");
	  return (-1);
	}
    } while (ret != 0);

  for (it = res; it; it = it->ai_next)
    if (it->ai_addrlen == sizeof addr)
      {
	struct sockaddr_in *in_a = (struct sockaddr_in *) it->ai_addr;
	addr.sin_addr = in_a->sin_addr;
	if (! connect (sock, (struct sockaddr *) &addr, sizeof addr))
	  break;
      }
  connect_ok = it != NULL;
  if (connect_ok)
    {
      realhost = alloca (strlen (it->ai_canonname) + 1);
      strcpy (realhost, it->ai_canonname);
    }
  freeaddrinfo (res);

#define CONNECT_ERROR "Could not connect to POP server: "

  if (! connect_ok)
    {
      CLOSESOCKET (sock);
      snprintf (pop_error, ERROR_MAX, "%s%s", CONNECT_ERROR, strerror (errno));
      return (-1);

    }

#ifdef KERBEROS

#define KRB_ERROR "Kerberos error connecting to POP server: "
  if (! (flags & POP_NO_KERBEROS))
    {
#ifdef KERBEROS5
      if ((rem = krb5_init_context (&kcontext)))
	{
	krb5error:
	  if (auth_context)
	    krb5_auth_con_free (kcontext, auth_context);
	  if (kcontext)
	    krb5_free_context (kcontext);
	  snprintf (pop_error, ERROR_MAX, "%s%s",
		    KRB_ERROR, error_message (rem));
	  CLOSESOCKET (sock);
	  return (-1);
	}

      if ((rem = krb5_auth_con_init (kcontext, &auth_context)))
	goto krb5error;

      if (rem = krb5_cc_default (kcontext, &ccdef))
	goto krb5error;

      if (rem = krb5_cc_get_principal (kcontext, ccdef, &client))
	goto krb5error;

      for (cp = realhost; *cp; cp++)
	{
	  if (isupper (*cp))
	    {
	      *cp = tolower (*cp);
	    }
	}

      if (rem = krb5_sname_to_principal (kcontext, realhost,
					 POP_SERVICE, FALSE, &server))
	goto krb5error;

      rem = krb5_sendauth (kcontext, &auth_context,
			   (krb5_pointer) &sock, "KPOPV1.0", client, server,
			  AP_OPTS_MUTUAL_REQUIRED,
			  0,	/* no checksum */
			  0,	/* no creds, use ccache instead */
			  ccdef,
			  &err_ret,
			  0,	/* don't need subsession key */
			  0);	/* don't need reply */
      krb5_free_principal (kcontext, server);
      if (rem)
	{
	  int pop_error_len = snprintf (pop_error, ERROR_MAX, "%s%s",
					KRB_ERROR, error_message (rem));
#if defined HAVE_KRB5_ERROR_TEXT
	  if (err_ret && err_ret->text.length)
	    {
	      int errlen = err_ret->text.length;
	      snprintf (pop_error + pop_error_len, ERROR_MAX - pop_error_len,
			" [server says '%.*s']", errlen, err_ret->text.data);
	    }
#elif defined HAVE_KRB5_ERROR_E_TEXT
	  if (err_ret && err_ret->e_text && **err_ret->e_text)
	    snprintf (pop_error + pop_error_len, ERROR_MAX - pop_error_len,
		      " [server says '%s']", *err_ret->e_text);
#endif
	  if (err_ret)
	    krb5_free_error (kcontext, err_ret);
	  krb5_auth_con_free (kcontext, auth_context);
	  krb5_free_context (kcontext);

	  CLOSESOCKET (sock);
	  return (-1);
	}
#else  /* ! KERBEROS5 */
      ticket = (KTEXT) malloc (sizeof (KTEXT_ST));
      rem = krb_sendauth (0L, sock, ticket, "pop", realhost,
			  (char *) krb_realmofhost (realhost),
			  (unsigned long) 0, &msg_data, &cred, schedule,
			  (struct sockaddr_in *) 0,
			  (struct sockaddr_in *) 0,
			  "KPOPV0.1");
      free ((char *) ticket);
      if (rem != KSUCCESS)
	{
	  snprintf (pop_error, ERROR_MAX, "%s%s", KRB_ERROR, krb_err_txt[rem]);
	  CLOSESOCKET (sock);
	  return (-1);
	}
#endif /* KERBEROS5 */
    }
#endif /* KERBEROS */

  return (sock);
} /* socket_connection */
コード例 #12
0
ファイル: dedisperse_data.c プロジェクト: lbaehren/lofarsoft
/* 
   orders incoming blocks of data into dedispersed sub-bands 
*/
void dedisperse_data(FILE *input, FILE *output) /*includefile*/
{ 
  char message[80];
  float *buff[2], *dedisp, realtime, nextbaseline, *offset, *tmpblk;
  int readnext=0,isamp,bnum,nsamp,i,j,s,c,b,indx,ns[2],soffset,ddidx;
  int ic,ixnb,ixnc,*ishift,maxshift,nsblk,nsmax,cpb,d,spb,x,nsout,nxb;
  int *ignore;

  /* calculate table of shift values given the filterbank and DM */
  ishift=dmshift(fch1,foff,nchans,nbands,userdm,refrf,tsamp,frequency_table);
  maxshift=ishift[nchans-1];

  /* set the buffer size based on the maximum shift */
  nsblk=256*nchans; nsout=32*nchans;
  /*nsblk=256*nchans; nsout=32768*nchans;*/
  nsmax=maxshift*nifs*nchans;
  if (nsmax>nsblk) nsblk=nsmax;
  nxb=nifs*nbands;

  /* define the buffers and initialize counters */
  dedisp =(float *) malloc(nxb*nsout*sizeof(float));
  offset =(float *) malloc(nxb*sizeof(float));
  tmpblk =(float *) malloc(nsout*sizeof(float));
  buff[0]=(float *) malloc(nsblk*sizeof(float));
  buff[1]=(float *) malloc(nsblk*sizeof(float));
  for (i=0;i<nxb;i++) offset[i]=0.0;
  d=bnum=isamp=0;
  ic=nchans*nifs;
  nextbaseline=realtime=0.0;

  /* zero any channels that are in the ignored list of channels */
  if (file_exists(ignfile)) {
    ignore=ignored_channels(ignfile,nchans);
  } else {
    ignore=(int *) malloc(nchans*sizeof(int));
    for (i=0;i<nchans;i++) ignore[i]=0;
  }

  /* number of channels per band to dedisperse (cpb) must be an integer */
  cpb=nchans/nbands; 
  if ((cpb*nbands) != nchans) error_message("silly sub-band selection!");

  /* main loop - keep going until no more data comes in */
  while (1) {

    /* read in the buffer to be processed if not done so already */
    if (!readnext) {
      sprintf(message,"time:%.1fs:DM:%.1fpc/cc",realtime,refdm);
      update_log(message);
      if ((ns[bnum]=read_block(input,nbits,buff[bnum],nsblk))<=0) {
	if (isamp)write_dedisp(dedisp,isamp,nifs,nbands,offset,output);
	return;
      }
    }

    /* number of samples in this buffer */
    nsamp=ns[bnum]/ic;

    /* flag to signify whether next buffer has been read in (1=yes;0=no) */
    readnext=0;

    /* dedispersing loop over all samples in this buffer */
    for (s=0; s<nsamp; s++) {
      soffset=isamp*nxb;
      /* loop over the IFs */
      for (i=0; i<nifs; i++) {
	/* number of channels to skip within this IF */
	ixnc=i*nchans; 
	ixnb=i*nbands;
	for (b=0; b<nbands; b++) {
	  /* calculate index of this sample */
	  ddidx=soffset+ixnb+b;
	  /* clear array element for storing dedispersed subband */
	  dedisp[ddidx]=0.0; 
	  /* loop over the channels in this subband */
	  for (c=b*cpb;c<(b+1)*cpb;c++) {
	    /* proceed only if selected channel # is not in ignore list */
	    if (!ignore[c]) 
	    {
	      /* calculate index of sample to be added */
	      indx=(s+ishift[c])*ic+ixnc+c;
	      /* required sample will be in either this buffer or the next */
	      if (indx<ns[bnum]) {
	        dedisp[ddidx]+=buff[bnum][indx];
	      } else {
	        if (!readnext) {
		  if ((ns[!bnum]=read_block(input,nbits,buff[!bnum],nsblk))<=0) {
		    if (isamp) {
		      write_dedisp(dedisp,isamp,nifs,nbands,offset,output);
		    }
		    return;
		  }
		  sprintf(message,"time:%.1fs:DM:%.1fpc/cc",realtime,refdm);
		  update_log(message);
		  readnext=1;
	        }
	        dedisp[ddidx]+=buff[!bnum][indx-ns[bnum]];
	      }
	    }
	  }
	} /* end of loop over subbands */
      } /* end of loop over IFs */
      /* update number of samples dedispersed and elapsed time */
      isamp++; realtime+=tsamp;
      if (isamp==nsout) {
	if (baseline) {
	  for (i=0;i<nifs;i++) {
	    ixnb=i*nbands;
	    for (b=0;b<nbands;b++) {
	      for (j=0;j<nsout;j++) tmpblk[j]=dedisp[j*nxb+ixnb+b];
	      offset[ixnb+b]=nrselect(nsout/2,nsout,tmpblk-1);
	    }
	  }
	}
	write_dedisp(dedisp,nsout,nifs,nbands,offset,output);
	isamp=0;
      }
    } /* end of loop over samples */
    /* switch to next buffer */
    bnum=!bnum;
  } /* end of main loop */
}
コード例 #13
0
ファイル: dedisperse_data.c プロジェクト: lbaehren/lofarsoft
/* subtract current offset from the dedisperse time samples and write */
void write_dedisp(float *dedisp, int nsout, int nifs, int nbands, float *offset, FILE *output)/*includefile*/
{
  int s,i,b,ixnb,sxib,n;
  static int first=1;
  static float *clipthreshold;
  float *temp,outliers,sample,sumsq;
  char *onebyte;
  short *twobyte;

  /* multiply outgoing data by Jansky calibration factor if supplied */
  if (jyfactor != 1.0) for (i=0;i<nsout*nifs*nbands;i++) dedisp[i]*=jyfactor;

  if (first) {
    /* allocate an array for holding blocks from a given subband */
    temp=malloc(sizeof(float)*nsout);
    /* allocate an array for saving the clipping threshold */
    clipthreshold=malloc(sizeof(float)*nbands*nifs);
    for (i=0;i<nifs*nbands;i++) clipthreshold[i]=0.0;
  }
		       
  for (i=0;i<nifs;i++) {
    ixnb=i*nbands;
    for (b=0;b<nbands;b++) {
      if (first) {
	/* copy sub-band into temporary store for absolute value */
	for (s=0;s<nsout;s++) {
	  sxib=s*nifs*nbands;
	  temp[s]=fabs(dedisp[sxib+ixnb+b]-offset[ixnb+b]);
	}
	/* find the value below which 90% of the samples lie */
	outliers=nrselect(nsout/10,nsout,temp-1);
	n=0;
	sumsq=0.0;
	/* calculate sum of squares based on the inner 90% of samples */
	for (s=0;s<nsout;s++) {
	  if (temp[s]<outliers) {
	    sumsq+=temp[s]*temp[s];
	    n++;
	  }
	}
	/* now set the threshold based on the sum of squares */
	if (n) 
	  clipthreshold[ixnb+b]=clipvalue*sqrt((double)sumsq/(double)n);
	else 
	  clipping=0;
      }
      for (s=0;s<nsout;s++) {
	sxib=s*nifs*nbands;
	/* subtract off median value of this block */
	sample=dedisp[sxib+ixnb+b]-offset[ixnb+b];
	/* clip this sample if it exceeds the threshold */
	if (fabs(sample)>clipthreshold[ixnb+b] && clipping) sample=0.0;
	/* store the final produce and swap bytes if necessary */
	dedisp[sxib+ixnb+b]=sample;
	if (swapout) swap_float(&dedisp[sxib+ixnb+b]);
      }
    }
  }

  /* now write out samples and bat on */
  switch (nobits) {
  case 8:
    onebyte = (char *) malloc(nsout*nifs*nbands);
    for (i=0; i<nsout*nifs*nbands; i++) 
      onebyte[i] = (char) dedisp[i];
    fwrite(onebyte,sizeof(char),nsout*nifs*nbands,output);
    break;
  case 16:
    twobyte = (short *) malloc(nsout*nifs*nbands);
    for (i=0; i<nsout*nifs*nbands; i++) 
      twobyte[i] = (short) dedisp[i];
    fwrite(twobyte,sizeof(short),nsout*nifs*nbands,output);
    break;
  case 32:
    fwrite(dedisp,sizeof(float),nsout*nifs*nbands,output);
    break;
  default:
    error_message("requested output number of bits can only be 8, 16 or 32");
    break;
  }

  if (first) {
    first=0;
    free(temp);
  }
}
コード例 #14
0
ファイル: authdata.c プロジェクト: sprymak/samba
/*
 * Given the username/password, do a kinit, store the ticket in
 * cache_name if specified, and return the PAC_LOGON_INFO (the
 * structure containing the important user information such as
 * groups).
 */
NTSTATUS kerberos_return_pac(TALLOC_CTX *mem_ctx,
			     const char *name,
			     const char *pass,
			     time_t time_offset,
			     time_t *expire_time,
			     time_t *renew_till_time,
			     const char *cache_name,
			     bool request_pac,
			     bool add_netbios_addr,
			     time_t renewable_time,
			     const char *impersonate_princ_s,
			     struct PAC_LOGON_INFO **_logon_info)
{
	krb5_error_code ret;
	NTSTATUS status = NT_STATUS_INVALID_PARAMETER;
	DATA_BLOB tkt, tkt_wrapped, ap_rep, sesskey1;
	const char *auth_princ = NULL;
	const char *local_service = NULL;
	const char *cc = "MEMORY:kerberos_return_pac";
	struct auth_session_info *session_info;
	struct gensec_security *gensec_server_context;

	struct gensec_settings *gensec_settings;
	size_t idx = 0;
	struct auth4_context *auth_context;
	struct loadparm_context *lp_ctx;
	struct PAC_LOGON_INFO *logon_info = NULL;

	TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
	NT_STATUS_HAVE_NO_MEMORY(tmp_ctx);

	ZERO_STRUCT(tkt);
	ZERO_STRUCT(ap_rep);
	ZERO_STRUCT(sesskey1);

	if (!name || !pass) {
		return NT_STATUS_INVALID_PARAMETER;
	}

	if (cache_name) {
		cc = cache_name;
	}

	if (!strchr_m(name, '@')) {
		auth_princ = talloc_asprintf(mem_ctx, "%s@%s", name,
			lp_realm());
	} else {
		auth_princ = name;
	}
	NT_STATUS_HAVE_NO_MEMORY(auth_princ);

	local_service = talloc_asprintf(mem_ctx, "%s$@%s",
					lp_netbios_name(), lp_realm());
	NT_STATUS_HAVE_NO_MEMORY(local_service);

	ret = kerberos_kinit_password_ext(auth_princ,
					  pass,
					  time_offset,
					  expire_time,
					  renew_till_time,
					  cc,
					  request_pac,
					  add_netbios_addr,
					  renewable_time,
					  &status);
	if (ret) {
		DEBUG(1,("kinit failed for '%s' with: %s (%d)\n",
			auth_princ, error_message(ret), ret));
		/* status already set */
		goto out;
	}

	DEBUG(10,("got TGT for %s in %s\n", auth_princ, cc));
	if (expire_time) {
		DEBUGADD(10,("\tvalid until: %s (%d)\n",
			http_timestring(talloc_tos(), *expire_time),
			(int)*expire_time));
	}
	if (renew_till_time) {
		DEBUGADD(10,("\trenewable till: %s (%d)\n",
			http_timestring(talloc_tos(), *renew_till_time),
			(int)*renew_till_time));
	}

	/* we cannot continue with krb5 when UF_DONT_REQUIRE_PREAUTH is set,
	 * in that case fallback to NTLM - gd */

	if (expire_time && renew_till_time &&
	    (*expire_time == 0) && (*renew_till_time == 0)) {
		return NT_STATUS_INVALID_LOGON_TYPE;
	}

	ret = cli_krb5_get_ticket(mem_ctx,
				  local_service,
				  time_offset,
				  &tkt,
				  &sesskey1,
				  0,
				  cc,
				  NULL,
				  impersonate_princ_s);
	if (ret) {
		DEBUG(1,("failed to get ticket for %s: %s\n",
			local_service, error_message(ret)));
		if (impersonate_princ_s) {
			DEBUGADD(1,("tried S4U2SELF impersonation as: %s\n",
				impersonate_princ_s));
		}
		status = krb5_to_nt_status(ret);
		goto out;
	}

	/* wrap that up in a nice GSS-API wrapping */
	tkt_wrapped = spnego_gen_krb5_wrap(tmp_ctx, tkt, TOK_ID_KRB_AP_REQ);
	if (tkt_wrapped.data == NULL) {
		status = NT_STATUS_NO_MEMORY;
		goto out;
	}

	auth_context = talloc_zero(tmp_ctx, struct auth4_context);
	if (auth_context == NULL) {
		status = NT_STATUS_NO_MEMORY;
		goto out;
	}
	auth_context->generate_session_info_pac = kerberos_fetch_pac;

	lp_ctx = loadparm_init_s3(tmp_ctx, loadparm_s3_context());
	if (lp_ctx == NULL) {
		status = NT_STATUS_INVALID_SERVER_STATE;
		DEBUG(10, ("loadparm_init_s3 failed\n"));
		goto out;
	}

	gensec_settings = lpcfg_gensec_settings(tmp_ctx, lp_ctx);
	if (lp_ctx == NULL) {
		status = NT_STATUS_NO_MEMORY;
		DEBUG(10, ("lpcfg_gensec_settings failed\n"));
		goto out;
	}

	gensec_settings->backends = talloc_zero_array(gensec_settings,
						      struct gensec_security_ops *, 2);
	if (gensec_settings->backends == NULL) {
		status = NT_STATUS_NO_MEMORY;
		goto out;
	}

	gensec_init();

	gensec_settings->backends[idx++] = &gensec_gse_krb5_security_ops;

	status = gensec_server_start(tmp_ctx, gensec_settings,
					auth_context, &gensec_server_context);

	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, (__location__ "Failed to start server-side GENSEC to validate a Kerberos ticket: %s\n", nt_errstr(status)));
		goto out;
	}

	talloc_unlink(tmp_ctx, lp_ctx);
	talloc_unlink(tmp_ctx, gensec_settings);
	talloc_unlink(tmp_ctx, auth_context);

	status = gensec_start_mech_by_oid(gensec_server_context, GENSEC_OID_KERBEROS5);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, (__location__ "Failed to start server-side GENSEC krb5 to validate a Kerberos ticket: %s\n", nt_errstr(status)));
		goto out;
	}

	/* Do a client-server update dance */
	status = gensec_update(gensec_server_context, tmp_ctx, NULL, tkt_wrapped, &ap_rep);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, ("gensec_update() failed: %s\n", nt_errstr(status)));
		goto out;
	}

	/* Now return the PAC information to the callers.  We ingore
	 * the session_info and instead pick out the PAC via the
	 * private_data on the auth_context */
	status = gensec_session_info(gensec_server_context, tmp_ctx, &session_info);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, ("Unable to obtain PAC via gensec_session_info\n"));
		goto out;
	}

	logon_info = talloc_get_type_abort(gensec_server_context->auth_context->private_data,
					   struct PAC_LOGON_INFO);
	if (logon_info == NULL) {
		DEBUG(1,("no PAC\n"));
		status = NT_STATUS_INVALID_PARAMETER;
		goto out;
	}

	*_logon_info = talloc_move(mem_ctx, &logon_info);

out:
	talloc_free(tmp_ctx);
	if (cc != cache_name) {
		ads_kdestroy(cc);
	}

	data_blob_free(&tkt);
	data_blob_free(&ap_rep);
	data_blob_free(&sesskey1);

	return status;
}
コード例 #15
0
ファイル: auks_krb5_cred.c プロジェクト: 3van/auks
int
auks_krb5_cred_get_fwd(char *ccachefilename, char *serverName,
		       char **p_buffer,
		       size_t * p_buffer_length)
{

	int fstatus = AUKS_ERROR ;

	/* kerberos related variables */
	krb5_error_code err_code;
	krb5_context context;
	krb5_ccache ccache;
	krb5_principal principal;
	krb5_creds **out_creds_array = NULL;
	krb5_auth_context auth_context;
	krb5_flags authopts;
	krb5_data outbuf;
	krb5_data *p_outbuf;
	krb5_replay_data krdata;

	authopts = AP_OPTS_MUTUAL_REQUIRED;
	authopts &= (~OPTS_FORWARD_CREDS);
	authopts &= (~OPTS_FORWARDABLE_CREDS);

	if ( serverName == NULL ) {
		auks_error("no host specified");
		fstatus = AUKS_ERROR_KRB5_CRED_NO_HOST_SPECIFIED ;
		goto exit;
	}

	/* initialize kerberos context */
	err_code = krb5_init_context(&context);
	if (err_code) {
		auks_error("unable to initialize kerberos context : %s",
			   error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_INIT_CTX ;
		goto exit;
	}
	auks_log("kerberos context successfully initialized");

	/* initialize kerberos credential cache structure */
	if (ccachefilename == NULL)
		err_code = krb5_cc_default(context, &ccache);
	else
		err_code = krb5_cc_resolve(context,ccachefilename,&ccache);
	if (err_code) {
		auks_error("unable to resolve credential cache : %s",
			   error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_OPEN_CC ;
		goto ctx_exit ;
	}
	auks_log("credential cache successfully resolved");

	/* get principal using credential cache */
	err_code = krb5_cc_get_principal(context,ccache,&principal);
	if (err_code) {
		auks_error("unable to get principal from credential cache : %s",
			   error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_GET_PRINC ;
		goto cc_exit ;
	}
	auks_log("principal successfully extracted from credential cache");

	/* initialize kerberos authentication context */
	err_code = krb5_auth_con_init(context,&auth_context);
	if (err_code) {
		auks_error("unable to initialize kerberos authentication "
			   "context : %s",error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_INIT_AUTH_CTX ;
		goto princ_exit;
	}
	auks_log("kerberos authentication context successfully initialized");

	/* do replay detection using timestamps */
	krb5_auth_con_setflags(context,auth_context,KRB5_AUTH_CONTEXT_RET_TIME);

	/* get forwarded credential for server */
	err_code = krb5_fwd_tgt_creds(context,auth_context,serverName,
				      principal,NULL,NULL,authopts,&outbuf);
	if (err_code) {
		auks_error("unable to get serialized and crypted forwarded "
			   "credential for %s from KDC : %s",
			   serverName,error_message(err_code));
		fstatus =  AUKS_ERROR_KRB5_CRED_GET_FWD_CRED ;
		goto auth_ctx_exit;
	}
	auks_log("serialized and crypted forwarded credential for %s "
		 "successfully got from KDC",serverName);

	/* desactive replay detection */
	krb5_auth_con_setflags(context,auth_context,0);

	/* decrypt (using session key stored in auth context) and */
	/* unserialized forwarded credential in a kerberos credential */
	/* structure */
	err_code = krb5_rd_cred(context,auth_context,&outbuf,&out_creds_array,
				&krdata);
	if (err_code) {
		auks_error("unable to unserialize and decrypt forwarded "
			   "credential for %s : %s",serverName,
			   error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_RD_CRED ;
		goto fwd_exit;
	}
	auks_log("unserialization and decryption of forwarded "
		 "credential for %s succesfully done",serverName);

	/* Reinitialize kerberos authentication context in order to */
	/* write credential to output buffer */
	krb5_auth_con_free(context,auth_context);
	err_code = krb5_auth_con_init(context,&auth_context);
	if (err_code) {
		auks_error("unable to reinitialize kerberos connection "
			   "authentication context : %s",error_message
			   (err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_INIT_AUTH_CTX ;
		goto rd_cred_exit;
	}
	auks_log("kerberos connection authentication context "
		 "reinitialization successfully done");

	/* no flags */
	krb5_auth_con_setflags(context,auth_context,0);

	/* serialize forwarded credential (no encryption because auth */
	/* context session key is nullified) */
	err_code = krb5_mk_1cred(context,auth_context,*out_creds_array,
				 &p_outbuf,&krdata);
	if (err_code) {
		auks_error("unable to serialize forwarded credential for "
			   "%s : %s",serverName,error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_MK_CRED ;
		goto rd_cred_exit;
	}
	auks_log("forwarded credential for %s successfully serialized",
		 serverName);

	/* allocate output buffer and store serialized credential */
	(*p_buffer) = (char *) malloc(p_outbuf->length * sizeof(char));
	if ((*p_buffer) == NULL) {
		auks_error("unable to allocate serialized credential output "
			   "buffer for %s",serverName);
		*p_buffer_length = 0 ;
		fstatus = AUKS_ERROR_KRB5_CRED_MALLOC ;
	} else {
		/* copy data */
		memcpy(*p_buffer,p_outbuf->data,p_outbuf->length);
		*p_buffer_length = p_outbuf->length;
		auks_log("forwarded credential successfully stored "
			 "in output buffer");
		fstatus	= AUKS_SUCCESS ;
	}

	krb5_free_data(context,p_outbuf);

rd_cred_exit:
	krb5_free_creds(context,*out_creds_array);
	free(out_creds_array);

fwd_exit:
	krb5_free_data_contents(context, &outbuf);

auth_ctx_exit:
	krb5_auth_con_free(context,auth_context);

princ_exit:
	krb5_free_principal(context, principal);

cc_exit:
	krb5_cc_close(context, ccache);

ctx_exit:
	krb5_free_context(context);

exit:
	return fstatus;
}
コード例 #16
0
/*-------------------------------------------------------------------
 * (function: partial_map_node)
 * 	Depending on node type, figures out what to print for this node
 *------------------------------------------------------------------*/
void output_node(nnode_t *node, short traverse_number, FILE *fp)
{
	switch (node->type) 
	{
		case GT:
			define_set_input_logical_function(node, "100 1\n", fp);
			oassert(node->num_input_pins == 3);
			oassert(node->input_pins[2] != NULL);
			break;
		case LT:
			define_set_input_logical_function(node, "010 1\n", fp); // last input decides if this 
			oassert(node->num_input_pins == 3);
			oassert(node->input_pins[2] != NULL);
			break;
		case ADDER_FUNC:
			define_set_input_logical_function(node, "001 1\n010 1\n100 1\n111 1\n", fp);
			break;
		case CARRY_FUNC:
			define_set_input_logical_function(node, "011 1\n101 1\n110 1\n111 1\n", fp);
			break;
		case BITWISE_NOT:
			define_set_input_logical_function(node, "0 1\n", fp);
			break;	

		case LOGICAL_AND:
		case LOGICAL_OR:
		case LOGICAL_XOR:
		case LOGICAL_XNOR:
		case LOGICAL_NAND:
		case LOGICAL_NOR:
		case LOGICAL_EQUAL:
		case NOT_EQUAL:
		case LOGICAL_NOT:
			define_logical_function(node, node->type, fp);
			break;	

		case MUX_2:
			define_decoded_mux(node, fp);
			break;

		case FF_NODE:
			define_ff(node, fp);
			break;

		case MULTIPLY:
			if (hard_multipliers == NULL)
				oassert(FALSE); /* should be soft logic! */
			#ifdef VPR6
			define_mult_function(node, node->type, fp);
			#endif
			break;

		//case FULLADDER:
		case ADD:
			if (hard_adders == NULL)
				oassert(FALSE); /* should be soft logic! */
			#ifdef VPR6
			define_add_function(node, node->type, fp);
			#endif
			break;

		case MINUS:
			if (hard_adders == NULL)
				oassert(FALSE); /* should be soft logic! */
			#ifdef VPR6
			if(hard_adders != NULL)
				define_add_function(node, node->type, fp);
			#endif
			break;

		case MEMORY:
		case HARD_IP:
			#ifdef VPR6
			define_hard_block(node, node->type, fp);
			#endif
			break;
		case INPUT_NODE:
		case OUTPUT_NODE:
		case PAD_NODE:
		case CLOCK_NODE:
		case GND_NODE:
		case VCC_NODE:
			/* some nodes already converted */
			break;

		case BITWISE_AND:
		case BITWISE_NAND:
		case BITWISE_NOR:
		case BITWISE_XNOR:
		case BITWISE_XOR:
		case BITWISE_OR:
		case BUF_NODE:
		case MULTI_PORT_MUX:
		case SL:
		case SR:
		case CASE_EQUAL:
		case CASE_NOT_EQUAL:
		case DIVIDE:
		case MODULO:
		case GTE:
		case LTE:
		//case ADD:
		//case MINUS:
		default:
			/* these nodes should have been converted to softer versions */
			error_message(NETLIST_ERROR, 0,-1,"Output blif: node should have been converted to softer version.");
			break;
	}
}
コード例 #17
0
ファイル: auks_krb5_cred.c プロジェクト: 3van/auks
int
auks_krb5_cred_renew(char *ccachefilename)
{
	int fstatus = AUKS_ERROR ;

	int read_cred_is_tgt = 0;
	int read_cred_is_renewable = 0;

	/* kerberos related variables */
	krb5_context context;
	krb5_error_code err_code;
	krb5_ccache ccache;
	krb5_creds *p_cred_out = NULL;
	krb5_creds read_cred;
	krb5_creds renew_cred;
	krb5_cc_cursor cc_cursor;

	/* initialize kerberos context */
	err_code = krb5_init_context(&context);
	if (err_code) {
		auks_error("unable to initialize kerberos context : %s",
			   error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_INIT_CTX ;
		goto exit;
	}
	auks_log("kerberos context successfully initialized");

	/* initialize kerberos credential cache structure */
	if (ccachefilename == NULL)
		err_code = krb5_cc_default(context,&ccache);
	else
		err_code = krb5_cc_resolve(context,ccachefilename,&ccache);
	if (err_code) {
		auks_error("unable to resolve credential cache : %s",
			   error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_OPEN_CC ;
		goto ctx_exit ;
	}
	auks_log("credential cache successfully resolved");

	/* start credential cache sequential reading */
	err_code = krb5_cc_start_seq_get(context, ccache,&cc_cursor);
	if (err_code) {
		auks_error("unable to start credential cache sequential "
			   "read : %s",error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_READ_CC ;
		goto cc_exit;
	}
	auks_log("credential cache sequential read successfully started");

	/* try to get the first renewable TGT of the cache */
	do {
		err_code = krb5_cc_next_cred(context,ccache,
					     &cc_cursor,&read_cred);
		if (!err_code) {
			/* just check initial or forwarded tickets (TGTs) */
			if ((read_cred.ticket_flags & TKT_FLG_INITIAL)
			    || (read_cred.ticket_flags & TKT_FLG_FORWARDED)) {
				read_cred_is_tgt = 1;
				if (read_cred.ticket_flags
				    & TKT_FLG_RENEWABLE) {
					read_cred_is_renewable = 1;
					break;
				}
			}
		}
	}
	while (!err_code);

	/* stop credential cache sequential reading */
	err_code = krb5_cc_end_seq_get(context, ccache,&cc_cursor);
	if (err_code) {
		auks_error("unable to stop credential cache sequential "
			   "read : %s",error_message(err_code));
	} else
		auks_log("credential cache sequential read "
			 "successfully stopped");

	/* try to do renewal if a TGT was found */
	if (!read_cred_is_tgt) {
		auks_error("no TGT found in credential cache");
		fstatus = AUKS_ERROR_KRB5_CRED_NO_TGT_FOUND ;
		goto seq_exit;
	}

	/* try to do renewal if a renewable TGT was found */
	if (!read_cred_is_renewable) {
		auks_error("no renewable TGT found in credential cache");
		fstatus = AUKS_ERROR_KRB5_CRED_TGT_NOT_RENEWABLE ;
		goto seq_exit;
	}
	auks_log("renewable TGT found in credential cache");

	/* test if renewal is possible */
	if (read_cred.times.endtime >=
	    read_cred.times.renew_till) {
		auks_error("TGT can't be renew anymore");
		fstatus = AUKS_ERROR_KRB5_CRED_TGT_HAS_EXPIRED ;
		goto seq_exit;
	}
	auks_log("TGT is still renewable");

	/* renew credential cache TGT */
	memset(&renew_cred, 0,sizeof(renew_cred));

	/* copy client principal in futur credential */
	err_code = krb5_copy_principal(context,read_cred.client,
				       &renew_cred.client);
	if (err_code) {
		auks_error("unable to put client principal into "
			   "request cred : %s",error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_CP_PRINC ;
		goto cred_exit;
	}
	auks_log("client principal successfully put into request cred");

	/* copy krbtgt/... principal in futur credential as required */
	/* server principal for TGS */
	err_code = krb5_copy_principal(context,read_cred.server,
				       &renew_cred.server);
	if (err_code) {
		auks_error("unable to put server principal into "
			   "request cred : %s",error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_CP_PRINC ;
		goto cred_exit;
	}
	auks_log("server principal successfully put into request cred");

	/* renew credential cache TGT */
/* 	err_code = krb5_get_credentials_renew(context,KDC_OPT_RENEW,ccache, */
/* 					      &renew_cred,&p_cred_out); */
	err_code = krb5_get_cred_via_tkt(context,&read_cred,KDC_OPT_RENEW,
					 NULL,&renew_cred,&p_cred_out);

	if (err_code) {
		auks_error("unable to renew credential cache TGT : %s",
			   error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_TGT_RENEW ;
	} else {
		auks_log("credential cache TGT successfully renewed");
		krb5_free_creds(context,p_cred_out);
		fstatus = AUKS_SUCCESS ;
	}

cred_exit:
	/* potential bug to check */
	krb5_free_cred_contents(context,&renew_cred);

seq_exit:
	krb5_free_cred_contents(context,&read_cred);

cc_exit:
	krb5_cc_close(context, ccache);

ctx_exit:
	krb5_free_context(context);

exit:
	return fstatus;
}
コード例 #18
0
/*---------------------------------------------------------------------------
 * (function: output_blif)
 * 	The function that prints out the details for a blif formatted file
 *-------------------------------------------------------------------------*/
void output_blif(char *file_name, netlist_t *netlist)
{
	int i;
	int count = 0;
	short first_time_inputs = FALSE;
	short first_time_outputs = FALSE;
	FILE *out;
	char *out_file;

	/* open the file for output */
	if (global_args.high_level_block != NULL)
	{
		out_file = (char*)malloc(sizeof(char)*(1+strlen(file_name)+strlen(global_args.high_level_block)+6)); 
		sprintf(out_file, "%s_%s.blif", file_name, global_args.high_level_block); 
		out = fopen(out_file, "w");
	}
	else
	{
		out = fopen(file_name, "w");
	}
	
	if (out == NULL)
	{
		error_message(NETLIST_ERROR, -1, -1, "Could not open output file %s\n", file_name);
	}

	fprintf(out, ".model %s\n", top_module->children[0]->types.identifier);

	/* generate all te signals */
	for (i = 0; i < netlist->num_top_input_nodes; i++)
	{
		if (first_time_inputs == FALSE)
		{
			count = fprintf(out, ".inputs");
			first_time_inputs = TRUE;
		}

		if(netlist->top_input_nodes[i]->output_pins[0]->net->fanout_pins != NULL)
		{
			if (global_args.high_level_block != NULL)
			{
				if (strlen(netlist->top_input_nodes[i]->name) + count < 79)
					count = count + fprintf(out, " %s^^%i-%i", netlist->top_input_nodes[i]->name, netlist->top_input_nodes[i]->related_ast_node->far_tag, netlist->top_input_nodes[i]->related_ast_node->high_number);
				else
				{
					/* wrapping line */
					count = fprintf(out, " \\\n %s^^%i-%i", netlist->top_input_nodes[i]->name,netlist->top_input_nodes[i]->related_ast_node->far_tag, netlist->top_input_nodes[i]->related_ast_node->high_number);
					count = count - 3;
				}
			}
			else
			{
				if (strlen(netlist->top_input_nodes[i]->name) + count < 79)
				{
					count = count + fprintf(out, " %s", netlist->top_input_nodes[i]->name);
				}
				else
				{
					/* wrapping line */
					count = fprintf(out, " \\\n %s", netlist->top_input_nodes[i]->name);
					count = count - 3;
				}
			}
		}
	}
	fprintf(out, "\n");

	count = 0;
	for (i = 0; i < netlist->num_top_output_nodes; i++)
	{
		if (netlist->top_output_nodes[i]->input_pins[0]->net->driver_pin == NULL)
		{
			warning_message(NETLIST_ERROR, netlist->top_output_nodes[i]->related_ast_node->line_number, netlist->top_output_nodes[i]->related_ast_node->file_number, "This output is undriven (%s) and will be removed\n", netlist->top_output_nodes[i]->name);
		}
		else
		{	
			if (first_time_outputs == FALSE)
			{
				count = fprintf(out, ".outputs");
				first_time_outputs = TRUE;
			}

			if (global_args.high_level_block != NULL)
			{
				if ((strlen(netlist->top_output_nodes[i]->name) + count) < 79)
					count = count + fprintf(out, " %s^^%i-%i", netlist->top_output_nodes[i]->name,netlist->top_output_nodes[i]->related_ast_node->far_tag, netlist->top_output_nodes[i]->related_ast_node->high_number);
				else
				{
					/* wrapping line */
					count = fprintf(out, "\\\n %s^^%i-%i", netlist->top_output_nodes[i]->name,netlist->top_output_nodes[i]->related_ast_node->far_tag, netlist->top_output_nodes[i]->related_ast_node->high_number);
					count = count - 3;
				}
			}
			else
			{
				if ((strlen(netlist->top_output_nodes[i]->name) + count) < 79)
					count = count + fprintf(out, " %s", netlist->top_output_nodes[i]->name);
				else
				{
					/* wrapping line */
					count = fprintf(out, "\\\n %s", netlist->top_output_nodes[i]->name);
					count = count - 3;
				}
			}
		}
	}
	fprintf(out, "\n");

	/* add gnd, unconn, and vcc */
	fprintf(out, "\n.names gnd\n.names unconn\n.names vcc\n1\n");
	fprintf(out, "\n");

	/* traverse the internals of the flat net-list */
	if (strcmp(configuration.output_type, "blif") == 0)
	{
		depth_first_traversal_to_output(OUTPUT_TRAVERSE_VALUE, out, netlist);	
	}
	else
	{
		error_message(NETLIST_ERROR, 0, -1, "Invalid output file type.");
	}

	/* connect all the outputs up to the last gate */
	for (i = 0; i < netlist->num_top_output_nodes; i++)
	{
		/* KEN -- DPRAM WORKING HERE FOR JASON */
		nnode_t *node = netlist->top_output_nodes[i];
		if (node->input_pins[0]->net->driver_pin != NULL)
		{
			if (global_args.high_level_block != NULL)
			{
				fprintf(out, ".names %s^^%i-%i %s^^%i-%i\n1 1\n",
						node->input_pins[0]->net->driver_pin->node->name,
						node->input_pins[0]->net->driver_pin->node->related_ast_node->far_tag,
						node->input_pins[0]->net->driver_pin->node->related_ast_node->high_number,
						node->name,
						node->related_ast_node->far_tag,
						node->related_ast_node->high_number
				);
			}
			else
			{
				/*
				 *  Use the name of the driver pin as the name of the driver
				 *  as long as that name is set, and is not equal to the name of the output pin.
				 *
				 * 	Otherwise, use the name of the driver node.
				 */
				char *driver = node->input_pins[0]->net->driver_pin->name;
				char *output = node->name;
				if (!driver || !strcmp(driver,output))
					driver = node->input_pins[0]->net->driver_pin->node->name;

				/* Skip if the driver and output have the same name (i.e. the output of a flip-flop) */
				if (strcmp(driver,output) != 0) fprintf(out, ".names %s %s\n1 1\n", driver, output);
			}

		}
		fprintf(out, "\n");
	}

	/* finish off the top level module */
	fprintf(out, ".end\n");
	fprintf(out, "\n");

	/* Print out any hard block modules */
#ifdef VPR6
	add_the_blackbox_for_mults(out);
	add_the_blackbox_for_adds(out);
	output_hard_blocks(out);
#endif

	fclose(out);
}
コード例 #19
0
void do_test(FILE *in, FILE *out)
{
	char		buf[128];
	char		*cp, *cmd, *arg1, *arg2;
	__u32		num1, num2;
	int		size;
	errcode_t	retval;
	ext2_extent	extent = 0;
	const char	*no_table = "# No extent table\n";

	while (!feof(in)) {
		if (!fgets(buf, sizeof(buf), in))
			break;
		/*
		 * Ignore comments
		 */
		if (buf[0] =='#')
			continue;

		/*
		 * Echo command
		 */
		fputs(buf, out);

		cp = strchr(buf, '\n');
		if (cp)
			*cp = '\0';

		/*
		 * Parse command line; simple, at most two arguments
		 */
		cmd = buf;
		num1 = num2 = 0;
		arg1 = arg2 = 0;
		cp = strchr(buf, ' ');
		if (cp) {
			*cp++ = '\0';
			arg1 = cp;
			num1 = strtoul(arg1, 0, 0);

			cp = strchr(cp, ' ');
		}
		if (cp) {
			*cp++ = '\0';
			arg2 = cp;
			num2 = strtoul(arg2, 0, 0);
		}

		if (!strcmp(cmd, "create")) {
			retval = ext2fs_create_extent_table(&extent, num1);
			if (retval) {
			handle_error:
				fprintf(out, "# Error: %s\n",
					error_message(retval));
				continue;
			}
			continue;
		}
		if (!extent) {
			fputs(no_table, out);
			continue;
		}
		if (!strcmp(cmd, "free")) {
			ext2fs_free_extent_table(extent);
			extent = 0;
		} else if (!strcmp(cmd, "add")) {
			retval = ext2fs_add_extent_entry(extent, num1, num2);
			if (retval)
				goto handle_error;
		} else if (!strcmp(cmd, "lookup")) {
			num2 = ext2fs_extent_translate(extent, num1);
			fprintf(out, "# Answer: %u%s\n", num2,
				num2 ? "" : " (not found)");
		} else if (!strcmp(cmd, "dump")) {
			ext2fs_extent_dump(extent, out);
		} else if (!strcmp(cmd, "iter_test")) {
			retval = ext2fs_iterate_extent(extent, 0, 0, 0);
			if (retval)
				goto handle_error;
			while (1) {
				retval = ext2fs_iterate_extent(extent,
					       &num1, &num2, &size);
				if (retval)
					goto handle_error;
				if (!size)
					break;
				fprintf(out, "# %u -> %u (%d)\n",
					num1, num2, size);
			}
		} else
			fputs("# Syntax error\n", out);
	}
}
コード例 #20
0
ファイル: gensec_krb5.c プロジェクト: AllardJ/Tomato
static NTSTATUS gensec_krb5_common_client_start(struct gensec_security *gensec_security, bool gssapi)
{
	struct gensec_krb5_state *gensec_krb5_state;
	krb5_error_code ret;
	NTSTATUS nt_status;
	struct ccache_container *ccache_container;
	const char *hostname;

	const char *principal;
	krb5_data in_data;

	hostname = gensec_get_target_hostname(gensec_security);
	if (!hostname) {
		DEBUG(1, ("Could not determine hostname for target computer, cannot use kerberos\n"));
		return NT_STATUS_INVALID_PARAMETER;
	}
	if (is_ipaddress(hostname)) {
		DEBUG(2, ("Cannot do krb5 to an IP address"));
		return NT_STATUS_INVALID_PARAMETER;
	}
	if (strcmp(hostname, "localhost") == 0) {
		DEBUG(2, ("krb5 to 'localhost' does not make sense"));
		return NT_STATUS_INVALID_PARAMETER;
	}
			
	nt_status = gensec_krb5_start(gensec_security, gssapi);
	if (!NT_STATUS_IS_OK(nt_status)) {
		return nt_status;
	}

	gensec_krb5_state = (struct gensec_krb5_state *)gensec_security->private_data;
	gensec_krb5_state->state_position = GENSEC_KRB5_CLIENT_START;
	gensec_krb5_state->ap_req_options = AP_OPTS_USE_SUBKEY;

	if (gensec_krb5_state->gssapi) {
		/* The Fake GSSAPI modal emulates Samba3, which does not do mutual authentication */
		if (gensec_setting_bool(gensec_security->settings, "gensec_fake_gssapi_krb5", "mutual", false)) {
			gensec_krb5_state->ap_req_options |= AP_OPTS_MUTUAL_REQUIRED;
		}
	} else {
		/* The wrapping for KPASSWD (a user of the raw KRB5 API) should be mutually authenticated */
		if (gensec_setting_bool(gensec_security->settings, "gensec_krb5", "mutual", true)) {
			gensec_krb5_state->ap_req_options |= AP_OPTS_MUTUAL_REQUIRED;
		}
	}

	principal = gensec_get_target_principal(gensec_security);

	ret = cli_credentials_get_ccache(gensec_get_credentials(gensec_security), 
				         gensec_security->event_ctx, 
					 gensec_security->settings->lp_ctx, &ccache_container);
	switch (ret) {
	case 0:
		break;
	case KRB5KDC_ERR_PREAUTH_FAILED:
		return NT_STATUS_LOGON_FAILURE;
	case KRB5_KDC_UNREACH:
		DEBUG(3, ("Cannot reach a KDC we require to contact %s\n", principal));
		return NT_STATUS_INVALID_PARAMETER; /* Make SPNEGO ignore us, we can't go any further here */
	default:
		DEBUG(1, ("gensec_krb5_start: Aquiring initiator credentials failed: %s\n", error_message(ret)));
		return NT_STATUS_UNSUCCESSFUL;
	}
	in_data.length = 0;
	
	if (principal && lp_client_use_spnego_principal(gensec_security->settings->lp_ctx)) {
		krb5_principal target_principal;
		ret = krb5_parse_name(gensec_krb5_state->smb_krb5_context->krb5_context, principal,
				      &target_principal);
		if (ret == 0) {
			ret = krb5_mk_req_exact(gensec_krb5_state->smb_krb5_context->krb5_context, 
						&gensec_krb5_state->auth_context,
						gensec_krb5_state->ap_req_options, 
						target_principal,
						&in_data, ccache_container->ccache, 
						&gensec_krb5_state->enc_ticket);
			krb5_free_principal(gensec_krb5_state->smb_krb5_context->krb5_context, 
					    target_principal);
		}
	} else {
		ret = krb5_mk_req(gensec_krb5_state->smb_krb5_context->krb5_context, 
				  &gensec_krb5_state->auth_context,
				  gensec_krb5_state->ap_req_options,
				  gensec_get_target_service(gensec_security),
				  hostname,
				  &in_data, ccache_container->ccache, 
				  &gensec_krb5_state->enc_ticket);
	}
	switch (ret) {
	case 0:
		return NT_STATUS_OK;
	case KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN:
		DEBUG(3, ("Server [%s] is not registered with our KDC: %s\n", 
			  hostname, smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, ret, gensec_krb5_state)));
		return NT_STATUS_INVALID_PARAMETER; /* Make SPNEGO ignore us, we can't go any further here */
	case KRB5_KDC_UNREACH:
		DEBUG(3, ("Cannot reach a KDC we require to contact host [%s]: %s\n",
			  hostname, smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, ret, gensec_krb5_state)));
		return NT_STATUS_INVALID_PARAMETER; /* Make SPNEGO ignore us, we can't go any further here */
	case KRB5KDC_ERR_PREAUTH_FAILED:
	case KRB5KRB_AP_ERR_TKT_EXPIRED:
	case KRB5_CC_END:
		/* Too much clock skew - we will need to kinit to re-skew the clock */
	case KRB5KRB_AP_ERR_SKEW:
	case KRB5_KDCREP_SKEW:
	{
		DEBUG(3, ("kerberos (mk_req) failed: %s\n", 
			  smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, ret, gensec_krb5_state)));
		/*fall through*/
	}
	
	/* just don't print a message for these really ordinary messages */
	case KRB5_FCC_NOFILE:
	case KRB5_CC_NOTFOUND:
	case ENOENT:
		
		return NT_STATUS_UNSUCCESSFUL;
		break;
		
	default:
		DEBUG(0, ("kerberos: %s\n", 
			  smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, ret, gensec_krb5_state)));
		return NT_STATUS_UNSUCCESSFUL;
	}
}
コード例 #21
0
ファイル: ksetpwd.c プロジェクト: Akasurde/krb5
static kbrccache_t userinitcontext(
    const char * user, const char * domain, const char * passwd, const char * cachename, int initialize,
    int * outError )
{
    krb5_context    kcontext = 0;
    krb5_ccache             kcache = 0;
    krb5_creds              kcreds;
    krb5_principal  kme = 0;
    krb5_error_code kres;
    char *                  pPass = strdup( passwd );
    char *                  pName = NULL;
    char *                  pCacheName = NULL;
    int                             numCreds = 0;

    memset( &kcreds, 0, sizeof(kcreds) );
    kres = krb5_init_context( &kcontext );
    if( kres )
        goto return_error;
    if( domain )
        kres = krb5_build_principal( kcontext, &kme, strlen(domain), domain, user, (char *) 0 );
    else
        kres = krb5_parse_name( kcontext, user, &kme );
    if( kres )
        goto fail;
    krb5_unparse_name( kcontext, kme, &pName );
    if( cachename )
    {
        if (asprintf(&pCacheName, "%s%s", cachename, pName) < 0)
        {
            kres = KRB5_CC_NOMEM;
            goto fail;
        }
        kres = krb5_cc_resolve( kcontext, pCacheName, &kcache );
        if( kres )
        {
            kres = krb5_cc_resolve( kcontext, CCACHE_PREFIX_DEFAULT, &kcache );
            if( kres == 0 )
                pCacheName = strdup(CCACHE_PREFIX_DEFAULT);
        }
    }
    else
    {
        kres = krb5_cc_default( kcontext, &kcache );
        pCacheName = strdup( krb5_cc_get_name( kcontext, kcache ) );
    }
    if( kres )
    {
        krb5_free_context(kcontext);
        goto return_error;
    }
    if( initialize )
        krb5_cc_initialize( kcontext, kcache, kme );
    if( kres == 0 && user && passwd )
    {
        long timeneeded = time(0L) +TKTTIMELEFT;
        int have_credentials = 0;
        krb5_cc_cursor cc_curs = NULL;
        numCreds = 0;
        if( (kres=krb5_cc_start_seq_get(kcontext, kcache, &cc_curs)) >= 0 )
        {
            while( (kres=krb5_cc_next_cred(kcontext, kcache, &cc_curs, &kcreds))== 0)
            {
                numCreds++;
                if( krb5_principal_compare( kcontext, kme, kcreds.client ) )
                {
                    if( kcreds.ticket_flags & TKT_FLG_INITIAL && kcreds.times.endtime>timeneeded )
                        have_credentials = 1;
                }
                krb5_free_cred_contents( kcontext, &kcreds );
                if( have_credentials )
                    break;
            }
            krb5_cc_end_seq_get( kcontext, kcache, &cc_curs );
        }
        else
        {
            const char * errmsg = error_message(kres);
            fprintf( stderr, "%s user init(%s): %s\n", "setpass", pName, errmsg );
        }
        if( kres != 0 || have_credentials == 0 )
        {
            krb5_get_init_creds_opt *options = NULL;
            kres = krb5_get_init_creds_opt_alloc(kcontext, &options);
            if ( kres == 0 )
            {
                get_init_creds_opt_init(options);
/*
** no valid credentials - get new ones
*/
                kres = krb5_get_init_creds_password( kcontext, &kcreds, kme, pPass,
                                                     NULL /*prompter*/,
                                                     NULL /*data*/,
                                                     0 /*starttime*/,
                                                     0 /*in_tkt_service*/,
                                                     options /*options*/ );
            }
            if( kres == 0 )
            {
                if( numCreds <= 0 )
                    kres = krb5_cc_initialize( kcontext, kcache, kme );
                if( kres == 0 )
                    kres = krb5_cc_store_cred( kcontext, kcache, &kcreds );
                if( kres == 0 )
                    have_credentials = 1;
            }
            krb5_get_init_creds_opt_free(kcontext, options);
        }
#ifdef NOTUSED
        if( have_credentials )
        {
            int mstat;
            kres = gss_krb5_ccache_name( &mstat, pCacheName, NULL );
            if( getenv( ENV_DEBUG_LDAPKERB ) )
                fprintf( stderr, "gss credentials cache set to %s(%d)\n", pCacheName, kres );
        }
#endif
        krb5_cc_close( kcontext, kcache );
    }
fail:
    if( kres )
    {
        const char * errmsg = error_message(kres);
        fprintf( stderr, "%s user init(%s): %s\n", "setpass", pName, errmsg );
    }
    krb5_free_principal( kcontext, kme );
    krb5_free_cred_contents( kcontext, &kcreds );
    if( pName )
        free( pName );
    free(pPass);
    krb5_free_context(kcontext);

return_error:
    if( kres )
    {
        if( pCacheName )
        {
            free(pCacheName);
            pCacheName = NULL;
        }
    }
    if( outError )
        *outError = kres;
    return pCacheName;
}
コード例 #22
0
ファイル: ruby_krb5_auth.c プロジェクト: chrismoos/krb5-auth
void Krb5_register_error(int error)
{
  rb_raise(cKrb5_Exception, "%s", error_message(error));
}
コード例 #23
0
void MainWindow::startConnection() {
    Client *client = new Client(this);

    connect(client, SIGNAL(version_checked(QString, QString)), SLOT(checkVersion(QString, QString)));
    connect(client, SIGNAL(error_message(QString)), SLOT(networkError(QString)));
}
コード例 #24
0
 void SSS::handle_error(const std::string & msg, double x)const{
   report_error(msg + " in ScalarSliceSampler" +
                error_message(lo_, hi_, x, logplo_, logphi_, logp_slice_));
 }
コード例 #25
0
ファイル: auth.c プロジェクト: joshtriplett/tin-sample
/*
 * NNTP user authorization. Returns TRUE if authorization succeeded,
 * FALSE if not.
 *
 * tries AUTHINFO SASL PLAIN (if available) fist and if not succcessfull
 * AUTHINFO USER/PASS
 *
 * If username/passwd already given, and server wasn't changed, retry those.
 * Otherwise, read password from ~/.newsauth or, if not present or no matching
 * server found, from console.
 *
 * The ~/.newsauth authorization file has the format:
 *   nntpserver1 password [user]
 *   nntpserver2 password [user]
 *   etc.
 */
static t_bool
authinfo_plain(
	char *server,
	char *authuser,
	t_bool startup)
{
	char *authpass;
	int ret = ERR_AUTHBAD, changed;
	static char authusername[PATH_LEN] = "";
	static char authpassword[PATH_LEN] = "";
	static char last_server[PATH_LEN] = "";
	static t_bool already_failed = FALSE;
	static t_bool initialized = FALSE;

	changed = strcmp(server, last_server);	/* do we need new auth values? */
	strncpy(last_server, server, PATH_LEN - 1);
	last_server[PATH_LEN - 1] = '\0';

	/*
	 * Let's try the previous auth pair first, if applicable.
	 * Else, proceed to the other mechanisms.
	 */
	if (initialized && !changed && !already_failed) {
#	ifdef USE_SASL
		if (nntp_caps.sasl & SASL_PLAIN)
			ret = do_authinfo_sasl_plain(authusername, authpassword);
		if (ret != OK_AUTH)
#	endif /* USE_SASL */
		{
			if (nntp_caps.type != CAPABILITIES || nntp_caps.authinfo_user)
				ret = do_authinfo_user(server, authusername, authpassword);
		}
		return (ret == OK_AUTH);
	}

	authpassword[0] = '\0';
	authuser = strncpy(authusername, authuser, sizeof(authusername) - 1);
	authpass = authpassword;

	/*
	 * No username/password given yet.
	 * Read .newsauth only if we had not failed authentication yet for the
	 * current server (we don't want to try wrong username/password pairs
	 * more than once because this may lead to an infinite loop at connection
	 * startup: nntp_open tries to authenticate, it fails, server closes
	 * connection; next time tin tries to access the server it will do
	 * nntp_open again ...). This means, however, that if configuration
	 * changed on the server between two authentication attempts tin will
	 * prompt you the second time instead of reading .newsauth (except when
	 * at startup time; in this case, it will just leave); you have to leave
	 * and restart tin or change to another server and back in order to get
	 * it read again.
	 */
	if ((changed || !initialized) && !already_failed) {
		if (read_newsauth_file(server, authuser, authpass)) {
#	ifdef USE_SASL
			if (nntp_caps.sasl & SASL_PLAIN)
				ret = do_authinfo_sasl_plain(authuser, authpass);

			if (ret != OK_AUTH)
#	endif /* USE_SASL */
			{
				if (force_auth_on_conn_open || nntp_caps.type != CAPABILITIES || (nntp_caps.type == CAPABILITIES && nntp_caps.authinfo_user))
					ret = do_authinfo_user(server, authuser, authpass);
			}
			already_failed = (ret != OK_AUTH);

			if (ret == OK_AUTH) {
#	ifdef DEBUG
				if (debug & DEBUG_NNTP)
					debug_print_file("NNTP", "authorization succeeded");
#	endif /* DEBUG */
				initialized = TRUE;
				return TRUE;
			}
		}
	}

	/*
	 * At this point, either authentication with username/password pair from
	 * .newsauth has failed or there's no .newsauth file respectively no
	 * matching username/password for the current server. If we are not at
	 * startup we ask the user to enter such a pair by hand. Don't ask him
	 * at startup except if requested by -A option because if he doesn't need
	 * to authenticate (we don't know), the "Server expects authentication"
	 * messages are annoying (and even wrong).
	 * UNSURE: Maybe we want to make this decision configurable in the
	 * options menu, too, so that the user doesn't need -A.
	 * TODO: Put questions into do_authinfo_user() because it is possible
	 * that the server doesn't want a password; so only ask for it if needed.
	 */
	if (force_auth_on_conn_open || !startup) {
		if (batch_mode) { /* no interactive username/password prompting */
			error_message(0, _(txt_auth_needed));
			return (ret == OK_AUTH);
		}
		if (nntp_caps.type != CAPABILITIES || (nntp_caps.type == CAPABILITIES && !nntp_caps.authinfo_state && ((nntp_caps.sasl & SASL_PLAIN) || nntp_caps.authinfo_user || (!nntp_caps.authinfo_user && !(nntp_caps.sasl & SASL_PLAIN))))) {
#	ifdef USE_CURSES
			int state = RawState();
#	endif /* USE_CURSES */

			wait_message(0, _(txt_auth_needed));
#	ifdef USE_CURSES
			Raw(TRUE);
#	endif /* USE_CURSES */
			if (!prompt_default_string(_(txt_auth_user), authuser, PATH_LEN, authusername, HIST_NONE)) {
#	ifdef DEBUG
				if (debug & DEBUG_NNTP)
					debug_print_file("NNTP", "authorization failed: no username");
#	endif /* DEBUG */
				return FALSE;
			}

#	ifdef USE_CURSES
			Raw(state);
			my_printf("%s", _(txt_auth_pass));
			wgetnstr(stdscr, authpassword, sizeof(authpassword));
			Raw(TRUE);
#	else
			/*
			 * on some systems (i.e. Solaris) getpass(3) is limited to 8 chars ->
			 * we use tin_getline()
			 */
			authpass = strncpy(authpassword, tin_getline(_(txt_auth_pass), FALSE, NULL, PATH_LEN, TRUE, HIST_NONE), sizeof(authpassword) - 1);
#	endif /* USE_CURSES */

#	ifdef USE_SASL
			if (nntp_caps.sasl & SASL_PLAIN)
				ret = do_authinfo_sasl_plain(authuser, authpass);
			if (ret != OK_AUTH)
#	endif /* USE_SASL */
			{
				if (nntp_caps.type != CAPABILITIES || (nntp_caps.authinfo_user || !nntp_caps.authinfo_sasl)) {
#	ifdef DEBUG
					if (debug & DEBUG_NNTP) {
						if (nntp_caps.type == CAPABILITIES && !nntp_caps.authinfo_sasl && !nntp_caps.authinfo_user)
							debug_print_file("NNTP", "!!! No supported authmethod available, trying AUTHINFO USER/PASS");
					}
#	endif /* DEBUG */
					ret = do_authinfo_user(server, authuser, authpass);
					if (ret != OK_AUTH)
						already_failed = TRUE;
					/*
					 * giganews once responded to CAPABILITIES with just
					 * "VERSION 2", no mode-switching indication, no reader
					 * indication, no post indication, no authentication
					 * indication, ... so in case AUTHINFO USER/PASS succeeds
					 * if not advertized we simply go on but fully ignore
					 * CAPABILITIES
					 */
					if (nntp_caps.type == CAPABILITIES && !nntp_caps.authinfo_user && !nntp_caps.authinfo_sasl && ret == OK_AUTH)
						nntp_caps.type = BROKEN;
				}
			}
			initialized = TRUE;
			my_retouch();			/* Get rid of the chaff */
		} else {
			/*
			 * TODO:
			 * nntp_caps.type == CAPABILITIES && nntp_caps.authinfo_state
			 * can we change the sate here? and if so how? SARTTLS? MODE
			 * READER?
			 */
#	ifdef DEBUG
			if (debug & DEBUG_NNTP)
				debug_print_file("NNTP", "authorization not allowed in current sate");
#	endif /* DEBUG */
			/*
			 * we return OK_AUTH here once so tin doesn't exit just because a
			 * single command requested auth ...
			 */
			if (!already_failed)
				ret = OK_AUTH;
		}
	}

#	ifdef DEBUG
	if (debug & DEBUG_NNTP)
		debug_print_file("NNTP", "authorization %s", (ret == OK_AUTH ? "succeeded" : "failed"));
#	endif /* DEBUG */

	return (ret == OK_AUTH);
}
コード例 #26
0
ファイル: auks_krb5_cred.c プロジェクト: 3van/auks
int
auks_krb5_cred_get(char *ccachefilename,char **pbuffer,
		   size_t * plength)
{
	int fstatus = AUKS_ERROR ;

	/* kerberos related variables */
	krb5_error_code err_code;
	krb5_context context;
	krb5_auth_context auth_context;
	krb5_ccache ccache;
	krb5_creds read_cred;
	krb5_cc_cursor cc_cursor;
	krb5_data *p_outbuf;
	krb5_replay_data krdata;

	int read_cred_was_used = 0;
	int read_cred_is_tgt = 0;

	char *buffer;
	size_t length;

	/* initialize kerberos context */
	err_code = krb5_init_context(&context);
	if (err_code) {
		auks_error("unable to initialize kerberos context : %s",
			   error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_INIT_CTX ;
		goto exit;
	}
	auks_log("kerberos context successfully initialized");

	/* initialize kerberos credential cache structure */
	if (ccachefilename == NULL)
		err_code = krb5_cc_default(context, &ccache);
	else
		err_code = krb5_cc_resolve(context, ccachefilename,&ccache);
	if (err_code) {
		auks_error("unable to resolve credential cache : %s",
			   error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_OPEN_CC ;
		goto ctx_exit ;
	}
	auks_log("credential cache successfully resolved");

	/* start credential cache sequential reading */
	err_code = krb5_cc_start_seq_get(context, ccache,&cc_cursor);
	if (err_code) {
		auks_error("unable to start credential cache sequential "
			   "read : %s",error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_READ_CC ;
		goto cc_exit;
	}
	auks_log("credential cache sequential read successfully started");

	/* look for the first TGT of the cache */
	do {
		err_code = krb5_cc_next_cred(context,ccache,
					     &cc_cursor,&read_cred);
		if (!err_code) {
			/* mark read_cred variable as used */
			read_cred_was_used = 1;
			/* just check initial or forwarded tickets (TGTs) */
			if ((read_cred.ticket_flags & TKT_FLG_INITIAL)
			    || (read_cred.ticket_flags & TKT_FLG_FORWARDED)) {
				read_cred_is_tgt = 1 ;
				break;
			}
		}
	}
	while (!err_code);

	/* stop credential cache sequential reading */
	err_code = krb5_cc_end_seq_get(context,ccache,&cc_cursor);
	if (err_code) {
		auks_error("unable to stop credential cache sequential "
			   "read : %s",error_message(err_code));
	} else
		auks_log("credential cache sequential read "
			 "successfully stopped");

	/* extract credential if a TGT was found */
	if (!read_cred_is_tgt) {
		auks_error("no TGT found in credential cache");
		fstatus = AUKS_ERROR_KRB5_CRED_NO_TGT_FOUND ;
		goto seq_exit;
	}
	auks_log("TGT found in credential cache");

	/* initialize a nullified kerberos authentication context in order */
	/* to serialize credential into buffer */
	err_code = krb5_auth_con_init(context,&auth_context);
	if (err_code) {
		auks_error("unable to initialize kerberos authentication "
			   "context : %s",error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_INIT_AUTH_CTX ;
		goto seq_exit;
	}
	auks_log("kerberos authentication context successfully initialized");

	/* clear kerberos authentication context flags */
	krb5_auth_con_setflags(context,auth_context,0);

	/* extract credential data */
	err_code = krb5_mk_1cred(context,auth_context,&read_cred,
				 &p_outbuf,&krdata);
	if (err_code) {
		auks_error("unable to dump credential into working buffer : %s",
			   error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_MK_CRED ;
		goto auth_ctx_exit;
	}
	auks_log("credential successfully dumped into buffer");

	/* allocate output buffer */
	length = p_outbuf->length;
	buffer = (char *) malloc(length * sizeof(char));
	if (buffer == NULL) {
		auks_error("unable to allocate memory for credential data "
			   "storage");
		fstatus = AUKS_ERROR_KRB5_CRED_MALLOC ;
		goto cred_exit;
	}

	/* copy credential data into output buffer */
	memcpy(buffer,p_outbuf->data,length);
	*pbuffer = buffer;
	*plength = length;
	auks_log("credential successfully stored in output buffer");
	fstatus = AUKS_SUCCESS ;

cred_exit:
	krb5_free_data(context,p_outbuf);

auth_ctx_exit:
	/* free kerberos authentication context */
	krb5_auth_con_free(context,auth_context);

seq_exit:
	/* free credential contents */
	if (read_cred_was_used)
		krb5_free_cred_contents(context,&read_cred);

cc_exit:
	krb5_cc_close(context, ccache);

ctx_exit:
	krb5_free_context(context);

exit:
	return fstatus;
}
コード例 #27
0
static _INLINE_ void expand_percent_expression(ext2_filsys fs, char ch,
					       struct problem_context *ctx)
{
	e2fsck_t e2fsck_ctx = fs ? (e2fsck_t) fs->priv_data : NULL;

	if (!ctx)
		goto no_context;

	switch (ch) {
	case '%':
		fputc('%', stdout);
		break;
	case 'b':
#ifdef EXT2_NO_64_TYPE
		printf("%u", (unsigned long) ctx->blk);
#else
		printf("%llu", (unsigned long long) ctx->blk);
#endif
		break;
	case 'B':
#ifdef EXT2_NO_64_TYPE
		printf("%d", ctx->blkcount);
#else
		printf("%lld", (long long)ctx->blkcount);
#endif
		break;
	case 'c':
#ifdef EXT2_NO_64_TYPE
		printf("%u", (unsigned long) ctx->blk2);
#else
		printf("%llu", (unsigned long long) ctx->blk2);
#endif
		break;
	case 'd':
		printf("%u", ctx->dir);
		break;
	case 'g':
		printf("%d", ctx->group);
		break;
	case 'i':
		printf("%u", ctx->ino);
		break;
	case 'j':
		printf("%u", ctx->ino2);
		break;
	case 'm':
		printf("%s", error_message(ctx->errcode));
		break;
	case 'N':
#ifdef EXT2_NO_64_TYPE
		printf("%u", ctx->num);
#else
		printf("%llu", (long long)ctx->num);
#endif
		break;
	case 'p':
		print_pathname(fs, ctx->ino, 0);
		break;
	case 'P':
		print_pathname(fs, ctx->ino2,
			       ctx->dirent ? ctx->dirent->inode : 0);
		break;
	case 'q':
		print_pathname(fs, ctx->dir, 0);
		break;
	case 'Q':
		print_pathname(fs, ctx->dir, ctx->ino);
		break;
	case 'S':
		printf("%u", get_backup_sb(NULL, fs, NULL, NULL));
		break;
	case 's':
		printf("%s", ctx->str ? ctx->str : "NULL");
		break;
	case 't':
		print_time((time_t) ctx->num);
		break;
	case 'T':
		print_time(e2fsck_ctx ? e2fsck_ctx->now : time(0));
		break;
	case 'X':
#ifdef EXT2_NO_64_TYPE
		printf("0x%x", ctx->num);
#else
		printf("0x%llx", (long long)ctx->num);
#endif
		break;
	default:
	no_context:
		printf("%%%c", ch);
		break;
	}
}
コード例 #28
0
ファイル: auks_krb5_cred.c プロジェクト: 3van/auks
int
auks_krb5_cred_store(char *cachefilename, char *buffer,
		     size_t buffer_length)
{
	int fstatus = AUKS_ERROR ;

	/* kerberos related variables */
	krb5_error_code err_code;
	krb5_context context;
	krb5_auth_context auth_context;
	krb5_ccache ccache;
	krb5_creds **creds;
	krb5_data data;
	krb5_replay_data krdata;

	/* initialize kerberos context */
	err_code = krb5_init_context(&context);
	if (err_code) {
		auks_error("unable to initialize kerberos context : %s",
			   error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_INIT_CTX ;
		goto exit;
	}
	auks_log("kerberos context successfully initialized");

	/* initialize a nullified kerberos authentication context in order */
	/* to decode credential from buffer */
	err_code = krb5_auth_con_init(context, &auth_context);
	if (err_code) {
		auks_error("unable to initialize kerberos authentication"
			   " context : %s",error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_INIT_AUTH_CTX ;
		goto ctx_exit;
	}
	auks_log("kerberos authentication context successfully initialized");

	/* clear kerberos authentication context flags */
	krb5_auth_con_setflags(context, auth_context, 0);

	/* build a kerberos data structure with input buffer */
	data.data = buffer;
	data.length = buffer_length;

	/* build kerberos credential structure using this data structure */
	err_code = krb5_rd_cred(context, auth_context, &data,&creds,&krdata);
	if (err_code) {
		auks_error("unable to deserialize credential data : %s",
			   error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_RD_CRED ;
		goto auth_ctx_exit;

	}
	auks_log("credential data successfully deserialized");

	/* resolve kerberos credential cache */
	if (cachefilename == NULL)
		err_code = krb5_cc_default(context,&ccache);
	else
		err_code = krb5_cc_resolve(context,cachefilename,&ccache);
	if (err_code) {
		auks_error("unable to resolve credential cache : %s",
			   error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_OPEN_CC ;
		goto cred_exit;
	}
	auks_log("credential cache successfully resolved");

	/* initialize kerberos credential structure */
	err_code = krb5_cc_initialize(context,ccache,(*creds)->client);
	if (err_code) {
		auks_error("unable to initialize credential cache : %s",
			   error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_INIT_CC ;
		goto cc_exit;

	}
	auks_log("credential cache successfully initialized",cachefilename);

	/* store credential in credential cache */
	err_code = krb5_cc_store_cred(context,ccache,*creds);
	if (err_code) {
		auks_error("unable to store credential in credential "
			   "cache : %s",error_message(err_code));
		fstatus = AUKS_ERROR_KRB5_CRED_STORE_CRED ;
	} else {
		auks_log("credential successfully stored in credential cache");
		fstatus = AUKS_SUCCESS ;
	}

cc_exit:
	krb5_cc_close(context, ccache);

cred_exit:
	krb5_free_creds(context, *creds);
	free(creds);

auth_ctx_exit:
	krb5_auth_con_free(context, auth_context);

ctx_exit:
	krb5_free_context(context);

exit:
	return fstatus;
}
コード例 #29
0
ファイル: rkerberos.c プロジェクト: brandonweeks/rkerberos
/* call-seq:
 *   krb5.get_init_creds_keytab(principal = nil, keytab = nil, service = nil, ccache = nil)
 *
 * Acquire credentials for +principal+ from +keytab+ using +service+. If
 * no principal is specified, then a principal is derived from the service
 * name. If no service name is specified, kerberos defaults to "host".
 *
 * If no keytab file is provided, the default keytab file is used. This is
 * typically /etc/krb5.keytab.
 *
 * If +ccache+ is supplied and is a Kerberos::Krb5::CredentialsCache, the
 * resulting credentials will be stored in the credential cache.
 */
static VALUE rkrb5_get_init_creds_keytab(int argc, VALUE* argv, VALUE self){
  RUBY_KRB5* ptr;
  VALUE v_user, v_keytab_name, v_service, v_ccache;
  char* user;
  char* service;
  char keytab_name[MAX_KEYTAB_NAME_LEN];

  krb5_error_code kerror;
  krb5_get_init_creds_opt* opt;
  krb5_creds cred;

  Data_Get_Struct(self, RUBY_KRB5, ptr); 

  if(!ptr->ctx)
    rb_raise(cKrb5Exception, "no context has been established");

  kerror = krb5_get_init_creds_opt_alloc(ptr->ctx, &opt);
  if(kerror)
    rb_raise(cKrb5Exception, "krb5_get_init_creds_opt_alloc: %s", error_message(kerror));

  rb_scan_args(argc, argv, "04", &v_user, &v_keytab_name, &v_service, &v_ccache);

  // We need the service information for later.
  if(NIL_P(v_service)){
    service = NULL;
  }
  else{
    Check_Type(v_service, T_STRING);
    service = StringValuePtr(v_service);
  }

  // Convert the name (or service name) to a kerberos principal.
  if(NIL_P(v_user)){
    kerror = krb5_sname_to_principal(
      ptr->ctx,
      NULL,
      service,
      KRB5_NT_SRV_HST,
      &ptr->princ
    );

    if(kerror) {
      krb5_get_init_creds_opt_free(ptr->ctx, opt);
      rb_raise(cKrb5Exception, "krb5_sname_to_principal: %s", error_message(kerror));
    }
  }
  else{
    Check_Type(v_user, T_STRING);
    user = StringValuePtr(v_user);

    kerror = krb5_parse_name(ptr->ctx, user, &ptr->princ); 

    if(kerror) {
      krb5_get_init_creds_opt_free(ptr->ctx, opt);
      rb_raise(cKrb5Exception, "krb5_parse_name: %s", error_message(kerror));
    }
  }

  // Use the default keytab if none is specified.
  if(NIL_P(v_keytab_name)){
    kerror = krb5_kt_default_name(ptr->ctx, keytab_name, MAX_KEYTAB_NAME_LEN);

    if(kerror) {
      krb5_get_init_creds_opt_free(ptr->ctx, opt);
      rb_raise(cKrb5Exception, "krb5_kt_default_name: %s", error_message(kerror));
    }
  }
  else{
    Check_Type(v_keytab_name, T_STRING);
    strncpy(keytab_name, StringValuePtr(v_keytab_name), MAX_KEYTAB_NAME_LEN);
  }

  kerror = krb5_kt_resolve(
    ptr->ctx,
    keytab_name,
    &ptr->keytab
  );

  if(kerror) {
    krb5_get_init_creds_opt_free(ptr->ctx, opt);
    rb_raise(cKrb5Exception, "krb5_kt_resolve: %s", error_message(kerror));
  }

  // Set the credential cache from the supplied Kerberos::Krb5::CredentialsCache
  if(!NIL_P(v_ccache)){
    RUBY_KRB5_CCACHE* ccptr;
    Data_Get_Struct(v_ccache, RUBY_KRB5_CCACHE, ccptr);

    kerror = krb5_get_init_creds_opt_set_out_ccache(ptr->ctx, opt, ccptr->ccache);
    if(kerror) {
      krb5_get_init_creds_opt_free(ptr->ctx, opt);
      rb_raise(cKrb5Exception, "krb5_get_init_creds_opt_set_out_ccache: %s", error_message(kerror));
    }
  }

  kerror = krb5_get_init_creds_keytab(
    ptr->ctx,
    &cred,
    ptr->princ,
    ptr->keytab,
    0,
    service,
    opt
  );

  if(kerror) {
    krb5_get_init_creds_opt_free(ptr->ctx, opt);
    rb_raise(cKrb5Exception, "krb5_get_init_creds_keytab: %s", error_message(kerror));
  }

  krb5_get_init_creds_opt_free(ptr->ctx, opt);

  return self; 
}
コード例 #30
0
ファイル: main.c プロジェクト: AlainODea/illumos-gate
int main(int argc, char **argv)
{
    krb5_error_code	retval;
    krb5_context	kcontext;
    int errout = 0;

    krb5_boolean log_stderr_set;

    (void) setlocale(LC_ALL, "");

#if !defined(TEXT_DOMAIN)		/* Should be defined by cc -D */
#define	TEXT_DOMAIN	"KRB5KDC_TEST"	/* Use this only if it weren't */
#endif

    (void) textdomain(TEXT_DOMAIN);

    if (strrchr(argv[0], '/'))
	argv[0] = strrchr(argv[0], '/')+1;

    if (!(kdc_realmlist = (kdc_realm_t **) malloc(sizeof(kdc_realm_t *) * 
						  KRB5_KDC_MAX_REALMS))) {
	fprintf(stderr, gettext("%s: cannot get memory for realm list\n"), argv[0]);
	exit(1);
    }
    memset((char *) kdc_realmlist, 0,
	   (size_t) (sizeof(kdc_realm_t *) * KRB5_KDC_MAX_REALMS));

    /*
     * A note about Kerberos contexts: This context, "kcontext", is used
     * for the KDC operations, i.e. setup, network connection and error
     * reporting.  The per-realm operations use the "realm_context"
     * associated with each realm.
     */
    retval = krb5int_init_context_kdc(&kcontext);
    if (retval) {
	    com_err(argv[0], retval, gettext("while initializing krb5"));
	    exit(1);
    }
    krb5_klog_init(kcontext, "kdc", argv[0], 1);

    /*
     * Solaris Kerberos:
     * In the early stages of krb5kdc it is desirable to log error messages
     * to stderr as well as any other logging locations specified in config
     * files.
     */
     log_stderr_set = krb5_klog_logging_to_stderr();
     if (log_stderr_set != TRUE) {
     	krb5_klog_add_stderr();
     }

    /* initialize_kdc5_error_table();  SUNWresync121 XXX */

    /*
     * Scan through the argument list
     */
    initialize_realms(kcontext, argc, argv);

    setup_signal_handlers();

    load_preauth_plugins(kcontext);

    retval = setup_sam();
    if (retval) {
	com_err(argv[0], retval, gettext("while initializing SAM"));
	finish_realms(argv[0]);
	return 1;
    }

    if ((retval = setup_network(argv[0]))) {
	com_err(argv[0], retval, gettext("while initializing network"));
	finish_realms(argv[0]);
	return 1;
    }

    /* Solaris Kerberos: Remove the extra stderr logging */
    if (log_stderr_set != TRUE)
	krb5_klog_remove_stderr();

    /*
     * Solaris Kerberos:
     * List the logs (FILE, STDERR, etc) which are currently being
     * logged to and print that to stderr. Useful when trying to
     * track down a failure via SMF.
     */
    if (retval = krb5_klog_list_logs(argv[0])) {
	com_err(argv[0], retval, gettext("while listing logs"));
	if (log_stderr_set != TRUE) {
		fprintf(stderr, gettext("%s: %s while listing logs\n"),
		    argv[0], error_message(retval));
	}
    }

    if (!nofork && daemon(0, 0)) {
	com_err(argv[0], errno, gettext("while detaching from tty"));
	if (log_stderr_set != TRUE) {
		fprintf(stderr, gettext("%s: %s while detaching from tty\n"),
		  argv[0], strerror(errno));
	}
	finish_realms(argv[0]);
	return 1;
    }
    if (retval = krb5_klog_syslog(LOG_INFO, "commencing operation")) {
	com_err(argv[0], retval, gettext("while logging message"));
	errout++;
	};

    if ((retval = listen_and_process(argv[0]))) {
	com_err(argv[0], retval, gettext("while processing network requests"));
	errout++;
    }
    if ((retval = closedown_network(argv[0]))) {
	com_err(argv[0], retval, gettext("while shutting down network"));
	errout++;
    }
    krb5_klog_syslog(LOG_INFO, "shutting down");
    unload_preauth_plugins(kcontext);
    krb5_klog_close(kdc_context);
    finish_realms(argv[0]);
    if (kdc_realmlist) 
      free(kdc_realmlist);
#ifdef USE_RCACHE
    (void) krb5_rc_close(kcontext, kdc_rcache);
#endif
#ifndef NOCACHE
    kdc_free_lookaside(kcontext);
#endif
    krb5_free_context(kcontext);
    return errout;
}