Esempio n. 1
0
static long
MakeMultiChannelCall(struct rx_connection *conn, int each, 
	             long expectedCode, long codes[])
{
    long code;
    int i;
    struct multiChannel mc;

    memset(&mc, 0, sizeof(mc));
    mc.conn = conn;
    for (i = 0; i < RX_MAXCALLS; i++) {
	codes[i] = RXKST_PROCESSRUNNING;
	mc.changes[i] = each;
    }
    mc.codes = codes;
    code = rxi_GetCallNumberVector(conn, mc.callNumbers);
    if (code)
	return code;
    mc.done = 0;
    code = CallSimultaneously(RX_MAXCALLS, &mc, UniChannelCall);
    if (((expectedCode == RXKST_INCFAILED) || (expectedCode == -1)) && ((code == expectedCode) || (code == -3)));	/* strange cases */
    else if (code != expectedCode) {
	afs_com_err(whoami, code,
		"problem making multichannel call, expected '%s'",
		((expectedCode == 0)
		 ? "no error" : (char *)afs_error_message(expectedCode)));
    }
    return code;
}
Esempio n. 2
0
void
redirect_errors(const char *who, afs_int32 code, const char *fmt, va_list ap)
{
    krb5_context context;

    if (who) {
        fputs(who, stderr);
        fputs(": ", stderr);
    }
    if (code) {
        int freestr = 0;
        char *str = (char *)afs_error_message(code);
        if (strncmp(str, "unknown", strlen(str)) == 0) {
            if (!krb5_init_context(&context))
            {
                str = krb5_get_error_message(NULL, code);
                freestr = 1;
            }
        }
        fputs(str, stderr);
        fputs(" ", stderr);
        if (freestr) {
            krb5_free_error_message(context, str);
            krb5_free_context(context);
        }
    }
    if (fmt) {
        vfprintf(stderr, fmt, ap);
    }
    putc('\n', stderr);
    fflush(stderr);
}
Esempio n. 3
0
static int
PrintLocks(struct rx_connection *aconn, int aint32)
{
    int i;
    struct AFSDBLock lock;
    afs_int32 code;

    for (i = 0; i < 1000; i++) {
	code = RXAFSCB_GetLock(aconn, i, &lock);
	if (code) {
	    if (code == 1)
		break;
	    /* otherwise we have an unrecognized error */
	    printf("cmdebug: error checking locks: %s\n",
		   afs_error_message(code));
	    return code;
	}
	/* here we have the lock information, so display it, perhaps */
	if (aint32 || IsLocked(&lock.lock)) {
	    printf("Lock %s status: ", lock.name);
	    PrintLock(&lock.lock);
	    printf("\n");
	}
    }
    return 0;
}
Esempio n. 4
0
/* Main program */
int
main(int argc, char **argv)
{
    XFILE input_file;
    afs_uint32 r;

    parse_options(argc, argv);
    initialize_acfg_error_table();
    initialize_AVds_error_table();
    initialize_rxk_error_table();
    initialize_u_error_table();
    initialize_vl_error_table();
    initialize_vols_error_table();
    initialize_xFil_error_table();
    r = xfopen(&input_file, O_RDONLY, input_path);
    if (r) {
	afs_com_err(argv0, r, "opening %s", input_path);
	exit(2);
    }

    memset(&dp, 0, sizeof(dp));
    dp.cb_error = my_error_cb;
    dp.print_flags = DSPRINT_DIR;
    if (input_file.is_seekable)
	dp.flags |= DSFLAG_SEEK;

    r = ParseDirectory(&input_file, &dp, 0, 1);
    xfclose(&input_file);

    if (verbose && error_count)
	fprintf(stderr, "*** %d errors\n", error_count);
    if (r && !quiet)
	fprintf(stderr, "*** FAILED: %s\n", afs_error_message(r));
    return 0;
}
Esempio n. 5
0
void
redirect_errors(const char *who, afs_int32 code, const char *fmt, va_list ap)
{
    if (who) {
        fputs(who, stderr);
        fputs(": ", stderr);
    }
    if (code) {
        int freestr = 0;
        char *str = (char *)afs_error_message(code);
        if (strncmp(str, "unknown", strlen(str)) == 0) {
            if (pkrb5_get_error_message) {
                str = pkrb5_get_error_message(NULL, code);
                freestr = 1;
            } else
                str = (char *)error_message(code);
        }
        fputs(str, stderr);
        fputs(" ", stderr);
        if (freestr)
            pkrb5_free_error_message(NULL, str);
    }
    if (fmt) {
        vfprintf(stderr, fmt, ap);
    }
    putc('\n', stderr);
    fflush(stderr);
}
Esempio n. 6
0
static int
PrintInterfaces(struct rx_connection *aconn)
{
    Capabilities caps;
    struct interfaceAddr addr;
#ifdef AFS_NT40_ENV
    char * p;
#else
    char uuidstr[128];
#endif
    int i, code;
    char hoststr[16];

    caps.Capabilities_val = NULL;
    caps.Capabilities_len = 0;

    code = RXAFSCB_TellMeAboutYourself(aconn, &addr, &caps);
    if (code == RXGEN_OPCODE)
        code = RXAFSCB_WhoAreYou(aconn, &addr);
    if (code) {
	printf("cmdebug: error checking interfaces: %s\n",
	       afs_error_message(code));
	return 0;
    }

#ifdef AFS_NT40_ENV
    UuidToString((UUID *)&addr.uuid, &p);
    printf("UUID: %s\n",p);
    RpcStringFree(&p);
#else
    afsUUID_to_string(&addr.uuid, uuidstr, sizeof(uuidstr));
    printf("UUID: %s\n",uuidstr);
#endif

    printf("Host interfaces:\n");
    for (i = 0; i < addr.numberOfInterfaces; i++) {
	printf("%s", afs_inet_ntoa_r(htonl(addr.addr_in[i]), hoststr));
	if (addr.subnetmask[i])
	    printf(", netmask %s", afs_inet_ntoa_r(htonl(addr.subnetmask[i]), hoststr));
	if (addr.mtu[i])
	    printf(", MTU %d", addr.mtu[i]);
	printf("\n");
    }

    if (caps.Capabilities_val) {
        printf("Capabilities:\n");
        if (caps.Capabilities_val[0] & CAPABILITY_ERRORTRANS) {
            printf("Error Translation\n");
        }
        printf("\n");
    }

    if (caps.Capabilities_val)
	free(caps.Capabilities_val);
    caps.Capabilities_val = NULL;
    caps.Capabilities_len = 0;

    return 0;
}
Esempio n. 7
0
int
main(int argc, char **argv)
{
    struct cmd_syndesc *ts;
    char tline[1000];
    afs_int32 tc;
    char *tp;
    long code;
    char *tv[100];

    initialize_CMD_error_table();

    ts = cmd_CreateSyntax("apple", cproc1, NULL, 0, "describe apple");

    ts = cmd_CreateSyntax("pear", cproc2, NULL, 0, "describe pear");
    cmd_AddParm(ts, "-num", CMD_LIST, 0, "number of pears");
    cmd_AddParm(ts, "-noauth", CMD_FLAG, CMD_OPTIONAL, "don't authenticate");
    cmd_AddParm(ts, "-spotpos", CMD_LIST, CMD_OPTIONAL | CMD_EXPANDS, 0);
    cmd_Seek(ts, 8);
    cmd_AddParm(ts, "-cell", CMD_SINGLE, CMD_OPTIONAL, "cell name");
    cmd_CreateAlias(ts, "alias");

    ts = cmd_CreateSyntax("quit", cproc3, 0, 0, "quit");

    while (1) {
	printf("> ");
	tp = gets(tline);
	if (tp == NULL)
	    break;
	code = cmd_ParseLine(tline, tv, &tc, 100);
	if (code) {
	    printf("itest: parsing failure: %s\n", afs_error_message(code));
	    exit(1);
	}
	code = cmd_Dispatch(tc, tv);
	cmd_FreeArgv(tv);
	if (code) {
	    printf("itest: execution failed: %s\n", afs_error_message(code));
	}
    }
    return 0;
}
Esempio n. 8
0
int
main(int argc, char *argv[])
{
    int i;
    afs_int32 code;
    afs_int32 offset;

#ifdef	AFS_AIX32_ENV
    /*
     * The following signal action for AIX is necessary so that in case of a 
     * crash (i.e. core is generated) we can include the user's data section 
     * in the core dump. Unfortunately, by default, only a partial core is
     * generated which, in many cases, isn't too useful.
     */
    struct sigaction nsa;

    sigemptyset(&nsa.sa_mask);
    nsa.sa_handler = SIG_DFL;
    nsa.sa_flags = SA_FULLDUMP;
    sigaction(SIGSEGV, &nsa, NULL);
#endif
    initialize_KA_error_table();
    initialize_RXK_error_table();
    initialize_KTC_error_table();
    initialize_ACFG_error_table();
    initialize_CMD_error_table();
    initialize_VL_error_table();
    initialize_PT_error_table();
    initialize_BZ_error_table();
    initialize_U_error_table();
    initialize_VOLS_error_table();

    if (argc < 2) {
	fprintf(stderr, "Usage is: %s [<code>]+\n", argv[0]);
	exit(1);
    }

    for (i = 1; i < argc; i++) {
	code = atoi(argv[i]);
	offset = code & ((1 << ERRCODE_RANGE) - 1);

	printf("%d (%s).%d = %s\n", (int)code, afs_error_table_name(code),
	       (int)offset, afs_error_message(code));
    }
    return 0;
}
Esempio n. 9
0
static int
PrintCacheConfig(struct rx_connection *aconn)
{
    struct cacheConfig c;
    afs_uint32 srv_ver, conflen;
    int code;

    c.cacheConfig_len = 0;
    c.cacheConfig_val = NULL;
    code = RXAFSCB_GetCacheConfig(aconn, 1, &srv_ver, &conflen, &c);
    if (code) {
	printf("cmdebug: error checking cache config: %s\n",
	       afs_error_message(code));
	return 0;
    }

    if (srv_ver == AFS_CLIENT_RETRIEVAL_FIRST_EDITION) {
	struct cm_initparams_v1 *c1;

	if (c.cacheConfig_len != sizeof(*c1) / sizeof(afs_uint32)) {
	    printf("cmdebug: configuration data size mismatch (%d != %" AFS_SIZET_FMT ")\n",
		   c.cacheConfig_len, sizeof(*c1) / sizeof(afs_uint32));
	    return 0;
	}

	c1 = (struct cm_initparams_v1 *)c.cacheConfig_val;
	printf("Chunk files:   %d\n", c1->nChunkFiles);
	printf("Stat caches:   %d\n", c1->nStatCaches);
	printf("Data caches:   %d\n", c1->nDataCaches);
	printf("Volume caches: %d\n", c1->nVolumeCaches);
	printf("Chunk size:    %d", c1->otherChunkSize);
	if (c1->firstChunkSize != c1->otherChunkSize)
	    printf(" (first: %d)", c1->firstChunkSize);
	printf("\n");
	printf("Cache size:    %d kB\n", c1->cacheSize);
	printf("Set time:      %s\n", c1->setTime ? "yes" : "no");
	printf("Cache type:    %s\n", c1->memCache ? "memory" : "disk");
    } else {
	printf("cmdebug: unsupported server version %d\n", srv_ver);
    }
    return 0;
}
Esempio n. 10
0
int
process_udp_appl(int ksoc, struct packet *pkt)
{
    char *packet = pkt->rest;
    afs_int32 kvno;
    char realm[MAXKTCREALMLEN];
    char ticket[MAXKTCTICKETLEN];
    char auth[3 * MAXKTCNAMELEN + 4 + 5];
    int slen;
    int ticketLen, authLen;
    afs_int32 code;

    if (krb_udp_debug) {
	printf("Processing APPL Request\n");
    }
    kvno = *packet++;
    getstr(realm);
    ticketLen = *(unsigned char *)packet++;
    authLen = *(unsigned char *)packet++;
    if (ticketLen > sizeof(ticket)) {
	err_packet(ksoc, pkt, KERB_ERR_TEXT_LENGTH, "ticket too long");
	return -1;
    }
    memcpy(ticket, packet, ticketLen);
    packet += ticketLen;
    if (authLen > sizeof(auth)) {
	err_packet(ksoc, pkt, KERB_ERR_TEXT_LENGTH, "authenticator too long");
	return -1;
    }
    memcpy(auth, packet, authLen);
    pkt->rest = packet + authLen;
    code =
	UDP_GetTicket(ksoc, pkt, kvno, realm, ticket, ticketLen, auth,
		      authLen);
    if (code) {
	if (code == KANOENT)
	    code = KERB_ERR_PRINCIPAL_UNKNOWN;
	err_packet(ksoc, pkt, code, (char *)afs_error_message(code));
	return -1;
    }
    return 0;
}
Esempio n. 11
0
static void
default_com_err_proc(const char *whoami, afs_int32 code, const char *fmt,
		     va_list args)
{
    if (whoami) {
	fputs(whoami, stderr);
	fputs(": ", stderr);
    }
    if (code) {
	fputs(afs_error_message(code), stderr);
	fputs(" ", stderr);
    }
    if (fmt) {
	vfprintf(stderr, fmt, args);
    }
    putc('\n', stderr);
    /* should do this only on a tty in raw mode */
    putc('\r', stderr);
    fflush(stderr);
}
Esempio n. 12
0
void
LogError(long code, char *fmt, ... )
{
    va_list ap;
    time_t now;

    va_start(ap, fmt);
    globalConfPtr->log = fopen(AFSDIR_SERVER_BUDBLOG_FILEPATH, "a");

    if (globalConfPtr->log != NULL) {
	now = time(0);
	fprintf(globalConfPtr->log, "%s ", TimeStamp(now));

	if (code)
	    fprintf(globalConfPtr->log, "%s: %s\n", afs_error_table_name(code),
		    afs_error_message(code));
	vfprintf(globalConfPtr->log, fmt, ap );
	fflush(globalConfPtr->log);
	fclose(globalConfPtr->log);
    }
}
Esempio n. 13
0
void
LogError(long code, char *fmt, ... )
{
    va_list ap;
    int len;
    char buffer[1024];

    va_start(ap, fmt);
    len = vsnprintf(buffer, sizeof(buffer), fmt, ap);
    va_end(ap);
    if (len >= 1024) {
	len = 1023;
	buffer[1023] = '\0';
    }
    /* Be consistent with (unintentional?) historic behavior. */
    if (code) {
	FSLog("%s: %s\n", afs_error_table_name(code), afs_error_message(code));
	WriteLogBuffer(buffer, len);
    } else {
	FSLog("%s", buffer);
    }
}
Esempio n. 14
0
afs_int32
ka_UserReadPassword(char *prompt, char *password, int plen, char **reasonP)
{
    afs_int32 code = 0;

    if (reasonP)
	*reasonP = "";
    code = ka_Init(0);
    if (code)
	return code;
    code = UI_UTIL_read_pw_string(password, plen, prompt, 0);
    if (code)
	code = KAREADPW;
    else if (strlen(password) == 0)
	code = KANULLPASSWORD;
    else
	return 0;

    if (reasonP) {
	*reasonP = (char *)afs_error_message(code);
    }
    return code;
}
Esempio n. 15
0
static long
CheckCallFailure(struct rx_connection *conn, long codes[], long code,
		 char *msg)
{
    if (code == 0) {
	fprintf(stderr, "Failed to detect %s\n", msg);
	return RXKST_NODUPLICATECALL;
    } else {
	int i;
	int okay = 1;
	int someZero = 0;
	for (i = 0; i < RX_MAXCALLS; i++)
	    if (!((codes[i] == 0) || (codes[i] == code) || (codes[i] == -3)))
		okay = 0;
	if (conn->error)
	    okay = 0;
	if (!okay) {
	    fprintf(stderr, "%s produced these errors:\n", msg);
	    for (i = 0; i < RX_MAXCALLS; i++) {
		assert(codes[i] != RXKST_PROCESSRUNNING);
		if (codes[i] == 0) {
		    someZero++;
		    fprintf(stderr, "  %d no error\n", i);
		} else
		    fprintf(stderr, "  %d %s\n", i, afs_error_message(codes[i]));
	    }
	    if (someZero) {
		char buf[100];
		sprintf(buf, "connection dead following %s", msg);
		code = FastCall(conn);
		if (code)
		    afs_com_err(whoami, code, "%s", buf);
	    }
	}
    }
    return 0;
}
Esempio n. 16
0
static PrintCacheEntries(struct rx_connection *aconn, int aint32)
{
    register int i;
    register afs_int32 code, addr, inode, flags, time;
    char *fileName;

    for(i=0;i<100000;i++) {
	code = RXAFSCB_GetDE(aconn, i, &addr, &inode, &flags, &time, &fileName);
	if (code) {
	    if (code == 1) break;
	    printf("cmdebug: failed to get cache entry %d (%s)\n", i,
		   afs_error_message(code));
	    return code;
	}

	/* otherwise print this entry */
	printf("%d: ** dentry %d %08x %d %d %s\n",
	       i, addr, inode, flags, time, fileName);

	printf("\n");
    }
    printf("Returned %d entries.\n", i);
    return 0;
}
Esempio n. 17
0
static void
Die(int code, char *filename)
{				/*Die */

    if (errno == EINVAL) {
	if (filename)
	    fprintf(stderr,
		    "%s: Invalid argument; it is possible that %s is not in AFS.\n",
		    pn, filename);
	else
	    fprintf(stderr, "%s: Invalid argument.\n", pn);
    } else if (errno == ENOENT) {
	if (filename)
	    fprintf(stderr, "%s: File '%s' doesn't exist\n", pn, filename);
	else
	    fprintf(stderr, "%s: no such file returned\n", pn);
    } else if (errno == EROFS)
	fprintf(stderr,
		"%s: You can not change a backup or readonly volume\n", pn);
    else if (errno == EACCES || errno == EPERM) {
	if (filename)
	    fprintf(stderr,
		    "%s: You don't have the required access rights on '%s'\n",
		    pn, filename);
	else
	    fprintf(stderr,
		    "%s: You do not have the required rights to do this operation\n",
		    pn);
    } else {
	if (filename)
	    fprintf(stderr, "%s:'%s'", pn, filename);
	else
	    fprintf(stderr, "%s", pn);
	fprintf(stderr, ": %s\n", afs_error_message(errno));
    }
}				/*Die */
Esempio n. 18
0
void ViceIDToUsername(char *username, char *realm_of_user, char *realm_of_cell,
                      char * cell_to_use, CREDENTIALS *c,
                      int *status, 
                      struct ktc_principal *aclient, struct ktc_principal *aserver, struct ktc_token *atoken)
{
    static char lastcell[MAXCELLCHARS+1] = { 0 };
    static char confname[512] = { 0 };
    char username_copy[BUFSIZ];
    afs_int32 viceId;			/* AFS uid of user */

    if (confname[0] == '\0') {
        strncpy(confname, AFSDIR_CLIENT_ETC_DIRPATH, sizeof(confname));
        confname[sizeof(confname) - 2] = '\0';
    }

    if (dflag)
        printf("About to resolve name %s to id\n", username);

    strcpy(lastcell, aserver->cell);

    if (!pr_Initialize (0, confname, aserver->cell)) {
        char sname[PR_MAXNAMELEN], *at;

        strncpy(sname, username, PR_MAXNAMELEN);
        sname[PR_MAXNAMELEN-1] = '\0';

	at = strchr(sname, '@');
	if (at && !stricmp(at+1, realm_of_cell))
	    *at = '\0';
	*status = pr_SNameToId (sname, &viceId);
    }

    if (dflag)
    {
        if (*status)
            printf("pr_SNameToId Error %s\n",  afs_error_message(*status));
        else
            printf("Id %d\n", viceId);
    }       

    /*
     * This code is taken from cklog -- it lets people
     * automatically register with the ptserver in foreign cells
     */

#ifdef ALLOW_REGISTER
    if (*status == 0) {
        if (viceId != ANONYMOUSID) {
#else /* ALLOW_REGISTER */
            if ((*status == 0) && (viceId != ANONYMOUSID))
#endif /* ALLOW_REGISTER */
            {
#ifdef AFS_ID_TO_NAME
                strncpy(username_copy, username, BUFSIZ);
                snprintf (username, BUFSIZ, "%s (AFS ID %d)", username_copy, (int) viceId);
#endif /* AFS_ID_TO_NAME */
            }
#ifdef ALLOW_REGISTER
        } else if (strcmp(realm_of_user, realm_of_cell) != 0) {
            int i;
            if (dflag) {
                printf("doing first-time registration of %s "
                        "at %s\n", username, cell_to_use);
            }
            strncpy(aclient->name, username, MAXKTCNAMELEN - 1);
            aclient->name[MAXKTCNAMELEN - 1] = '\0';
            strcpy(aclient->instance, "");
            strncpy(aclient->cell, cell_to_use, MAXKTCREALMLEN - 1);
            aclient->cell[MAXKTCREALMLEN - 1] = '\0';

            for ( i=0; aclient->cell[i]; i++ ) {
                if ( islower(aclient->cell[i]) )
                    aclient->cell[i] = toupper(aclient->cell[i]);
            }

            if ((*status = ktc_SetToken(aserver, atoken, aclient, 0))) {
                afs_com_err(progname, *status,
                             "while obtaining tokens for cell %s\n",
                             cell_to_use);
                *status = AKLOG_TOKEN;
                return ;
            }

            /*
             * In case you're wondering, we don't need to change the
             * filename here because we're still connecting to the
             * same cell -- we're just using a different authentication
             * level
             */

            if ((*status = pr_Initialize(1L, confname, aserver->cell))) {
                printf("pr_Initialize Error %s\n",  afs_error_message(*status));
                return;
            }

            /* copy the name because pr_CreateUser lowercases the realm */
            strncpy(username_copy, username, BUFSIZ);

            viceId = 0;
            *status = pr_CreateUser(username_copy, &viceId);

            if (*status) {
                printf("%s: unable to create remote PTS "
                        "user %s in cell %s (status: %s).\n", progname,
                        username_copy, cell_to_use, afs_error_message(*status));
            } else {
                printf("created cross-cell entry for %s (Id %d) at %s\n",
                        username_copy, viceId, cell_to_use);
#ifdef AFS_ID_TO_NAME
                snprintf (username, BUFSIZ, "%s (AFS ID %d)", username_copy, (int) viceId);
#endif /* AFS_ID_TO_NAME */
            }
        }
    }
#endif /* ALLOW_REGISTER */
}
Esempio n. 19
0
int
process_udp_auth(int ksoc, struct packet *pkt)
{
    char *packet = pkt->rest;
    char name[MAXKTCNAMELEN];
    char inst[MAXKTCNAMELEN];
    char realm[MAXKTCREALMLEN];
    char sname[MAXKTCNAMELEN];
    char sinst[MAXKTCNAMELEN];
    int slen;
    Date now = time(0);
    Date startTime, endTime;
    unsigned char lifetime;
    afs_int32 code;

    pkt->name = packet;
    getstr(name);
    pkt->inst = packet;
    getstr(inst);
    pkt->realm = packet;
    getstr(realm);
    if (krb_udp_debug) {
	printf("Processing KDC Request from '%s'.'%s'@'%s'\n", name, inst,
	       realm);
    }

    if ((strlen(realm) > 0) && (strcmp(realm, lrealm) != 0)) {
	err_packet(ksoc, pkt, KERB_ERR_NONNULL_REALM,
		   "null realm name not allowed");
	return -1;
    }
    memcpy(&startTime, packet, sizeof(startTime));
    packet += sizeof(startTime);
    startTime = ktohl(pkt->byteOrder, startTime);
    pkt->time = startTime;
    lifetime = *packet++;
    endTime = life_to_time(startTime, lifetime);
    code = tkt_CheckTimes(startTime, endTime, now);
    if (code < 0) {
	err_packet(ksoc, pkt, KERB_ERR_BAD_LIFETIME,
		   "requested ticket lifetime invalid");
	return -1;
    }
    getstr(sname);
    getstr(sinst);
    if ((packet - pkt->data) != pkt->len) {
	err_packet(ksoc, pkt, KERB_ERR_PKT_LENGTH,
		   "packet length inconsistent");
	return -1;
    }
    pkt->rest = packet;
    code =
	UDP_Authenticate(ksoc, &pkt->from, name, inst, startTime, endTime,
			 sname, sinst);
    if (code) {
	if (code == KANOENT) {
	    code = KERB_ERR_PRINCIPAL_UNKNOWN;
	    err_packet(ksoc, pkt, code, (char *)afs_error_message(code));
	} else if (code == KAPWEXPIRED) {
	    code = KERB_ERR_NAME_EXP;
	    err_packet(ksoc, pkt, code, "password has expired");
	} else
	    err_packet(ksoc, pkt, code, (char *)afs_error_message(code));
    }
    return 0;
}
Esempio n. 20
0
int
main(int argc, char **argv)
{				/*main */
    char *targv[MAXV];		/*Ptr to parsed argv stuff */
    afs_int32 targc;		/*Num parsed arguments */
    afs_int32 code;		/*Return code */
    struct cmd_syndesc *ts;	/*Ptr to parsed command line */
    int i;


#ifdef	AFS_AIX32_ENV
    /*
     * The following signal action for AIX is necessary so that in case of a
     * crash (i.e. core is generated) we can include the user's data section
     * in the core dump. Unfortunately, by default, only a partial core is
     * generated which, in many cases, isn't too useful.
     */
    struct sigaction nsa;

    sigemptyset(&nsa.sa_mask);
    nsa.sa_handler = SIG_DFL;
    nsa.sa_flags = SA_FULLDUMP;
    sigaction(SIGSEGV, &nsa, NULL);
#endif
    Lock_Init(&dispatchLock);
    InitErrTabs();		/* init all the error tables which may be used */

    /* setup the default backup dir */
    DefaultConfDir = AFSDIR_SERVER_BACKUP_DIRPATH;
    /* Get early warning if the command is interacive mode or not */
    interact = (((argc < 2) || (argv[1][0] == '-')) ? 1 : 0);

    cmd_SetBeforeProc(MyBeforeProc, NULL);

    ts = cmd_CreateSyntax("dump", bc_DumpCmd, NULL, "start dump");
    cmd_AddParm(ts, "-volumeset", CMD_SINGLE, CMD_OPTIONAL,
		"volume set name");
    cmd_AddParm(ts, "-dump", CMD_SINGLE, CMD_OPTIONAL, "dump level name");
    cmd_AddParm(ts, "-portoffset", CMD_SINGLE, CMD_OPTIONAL,
		"TC port offset");
    cmd_AddParm(ts, "-at", CMD_LIST, CMD_OPTIONAL, "Date/time to start dump");
    cmd_AddParm(ts, "-append", CMD_FLAG, CMD_OPTIONAL,
		"append to existing dump set");
    cmd_AddParm(ts, "-dryrun", CMD_FLAG, CMD_OPTIONAL,
                "list what would be done, don't do it");
    cmd_AddParmAlias(ts, 5, "-n");
    cmd_AddParm(ts, "-file", CMD_SINGLE, CMD_OPTIONAL, "load file");
    if (!interact)
	add_std_args(ts);

    ts = cmd_CreateSyntax("volrestore", bc_VolRestoreCmd, NULL,
			  "restore volume");
    cmd_AddParm(ts, "-server", CMD_SINGLE, CMD_REQUIRED,
		"destination machine");
    cmd_AddParm(ts, "-partition", CMD_SINGLE, CMD_REQUIRED,
		"destination partition");
    cmd_AddParm(ts, "-volume", CMD_LIST, CMD_REQUIRED,
		"volume(s) to restore");
    cmd_AddParm(ts, "-extension", CMD_SINGLE, CMD_OPTIONAL,
		"new volume name extension");
    cmd_AddParm(ts, "-date", CMD_LIST, CMD_OPTIONAL,
		"date from which to restore");
    cmd_AddParm(ts, "-portoffset", CMD_LIST, CMD_OPTIONAL, "TC port offsets");
    cmd_AddParm(ts, "-dryrun", CMD_FLAG, CMD_OPTIONAL,
                "list what would be done, don't do it");
    cmd_AddParmAlias(ts, 6, "-n");
    cmd_AddParm(ts, "-usedump", CMD_SINGLE, CMD_OPTIONAL,
		"specify the dumpID to restore from");
    if (!interact)
	add_std_args(ts);

    ts = cmd_CreateSyntax("diskrestore", bc_DiskRestoreCmd, NULL,
			  "restore partition");
    cmd_AddParm(ts, "-server", CMD_SINGLE, CMD_REQUIRED,
		"machine to restore");
    cmd_AddParm(ts, "-partition", CMD_SINGLE, CMD_REQUIRED,
		"partition to restore");
    cmd_AddParm(ts, "-portoffset", CMD_LIST, CMD_OPTIONAL, "TC port offset");
    cmd_Seek(ts, 8);
    cmd_AddParm(ts, "-newserver", CMD_SINGLE, CMD_OPTIONAL,
		"destination machine");
    cmd_AddParm(ts, "-newpartition", CMD_SINGLE, CMD_OPTIONAL,
		"destination partition");
    cmd_AddParm(ts, "-extension", CMD_SINGLE, CMD_OPTIONAL,
		"new volume name extension");
    cmd_AddParm(ts, "-dryrun", CMD_FLAG, CMD_OPTIONAL,
                "list what would be done, don't do it");
    cmd_AddParmAlias(ts, 11, "-n");
    if (!interact)
	add_std_args(ts);

    cmd_CreateSyntax("quit", bc_QuitCmd, NULL, "leave the program");

    ts = cmd_CreateSyntax("volsetrestore", bc_VolsetRestoreCmd, NULL,
			  "restore a set of volumes");
    cmd_AddParm(ts, "-name", CMD_SINGLE, CMD_OPTIONAL, "volume set name");
    cmd_AddParm(ts, "-file", CMD_SINGLE, CMD_OPTIONAL, "file name");
    cmd_AddParm(ts, "-portoffset", CMD_LIST, CMD_OPTIONAL, "TC port offset");
    cmd_AddParm(ts, "-extension", CMD_SINGLE, CMD_OPTIONAL,
		"new volume name extension");
    cmd_AddParm(ts, "-dryrun", CMD_FLAG, CMD_OPTIONAL,
                "list what would be done, don't do it");
    cmd_AddParmAlias(ts, 4, "-n");
    if (!interact)
	add_std_args(ts);

    ts = cmd_CreateSyntax("addhost", bc_AddHostCmd, NULL, "add host to config");
    cmd_AddParm(ts, "-tapehost", CMD_SINGLE, CMD_REQUIRED,
		"tape machine name");
    cmd_AddParm(ts, "-portoffset", CMD_SINGLE, CMD_OPTIONAL,
		"TC port offset");
    if (!interact)
	add_std_args(ts);

    ts = cmd_CreateSyntax("delhost", bc_DeleteHostCmd, NULL,
			  "delete host to config");
    cmd_AddParm(ts, "-tapehost", CMD_SINGLE, CMD_REQUIRED,
		"tape machine name");
    cmd_AddParm(ts, "-portoffset", CMD_SINGLE, CMD_OPTIONAL,
		"TC port offset");
    if (!interact)
	add_std_args(ts);

    ts = cmd_CreateSyntax("listhosts", bc_ListHostsCmd, NULL,
			  "list config hosts");
    if (!interact)
	add_std_args(ts);

    cmd_CreateSyntax("jobs", bc_JobsCmd, NULL, "list running jobs");

    ts = cmd_CreateSyntax("kill", bc_KillCmd, NULL, "kill running job");
    cmd_AddParm(ts, "-id", CMD_SINGLE, CMD_REQUIRED,
		"job ID or dump set name");

    ts = cmd_CreateSyntax("listvolsets", bc_ListVolSetCmd, NULL,
			  "list volume sets");
    cmd_AddParm(ts, "-name", CMD_SINGLE, CMD_OPTIONAL, "volume set name");
    if (!interact)
	add_std_args(ts);

    ts = cmd_CreateSyntax("listdumps", bc_ListDumpScheduleCmd, NULL,
			  "list dump schedules");
    if (!interact)
	add_std_args(ts);

    ts = cmd_CreateSyntax("addvolset", bc_AddVolSetCmd, NULL,
			  "create a new volume set");
    cmd_AddParm(ts, "-name", CMD_SINGLE, CMD_REQUIRED, "volume set name");
    cmd_AddParm(ts, "-temporary", CMD_FLAG, CMD_OPTIONAL,
		"temporary volume set");
    if (!interact)
	add_std_args(ts);

    ts = cmd_CreateSyntax("status", bc_GetTapeStatusCmd, NULL,
			  "get tape coordinator status");
    cmd_AddParm(ts, "-portoffset", CMD_SINGLE, CMD_OPTIONAL,
		"TC port offset");
    if (!interact)
	add_std_args(ts);

    ts = cmd_CreateSyntax("delvolset", bc_DeleteVolSetCmd, NULL,
			  "delete a volume set");
    cmd_AddParm(ts, "-name", CMD_LIST, CMD_REQUIRED, "volume set name");
    if (!interact)
	add_std_args(ts);

    ts = cmd_CreateSyntax("addvolentry", bc_AddVolEntryCmd, NULL,
			  "add a new volume entry");
    cmd_AddParm(ts, "-name", CMD_SINGLE, CMD_REQUIRED, "volume set name");
    cmd_AddParm(ts, "-server", CMD_SINGLE, CMD_REQUIRED, "machine name");
    cmd_AddParm(ts, "-partition", CMD_SINGLE, CMD_REQUIRED, "partition name");
    cmd_AddParm(ts, "-volumes", CMD_SINGLE, CMD_REQUIRED,
		"volume name (regular expression)");
    if (!interact)
	add_std_args(ts);

    ts = cmd_CreateSyntax("delvolentry", bc_DeleteVolEntryCmd, NULL,
			  "delete a volume set sub-entry");
    cmd_AddParm(ts, "-name", CMD_SINGLE, CMD_REQUIRED, "volume set name");
    cmd_AddParm(ts, "-entry", CMD_SINGLE, CMD_REQUIRED, "volume set index");
    if (!interact)
	add_std_args(ts);

    ts = cmd_CreateSyntax("adddump", bc_AddDumpCmd, NULL, "add dump schedule");
    cmd_AddParm(ts, "-dump", CMD_LIST, CMD_REQUIRED, "dump level name");
    cmd_AddParm(ts, "-expires", CMD_LIST, CMD_OPTIONAL, "expiration date");
    if (!interact)
	add_std_args(ts);

    ts = cmd_CreateSyntax("deldump", bc_DeleteDumpCmd, NULL,
			  "delete dump schedule");
    cmd_AddParm(ts, "-dump", CMD_SINGLE, CMD_REQUIRED, "dump level name");
    if (!interact)
	add_std_args(ts);

    ts = cmd_CreateSyntax("labeltape", bc_LabelTapeCmd, NULL, "label a tape");
    cmd_AddParm(ts, "-name", CMD_SINGLE, CMD_OPTIONAL,
		"AFS tape name, defaults to NULL");
    cmd_AddParm(ts, "-size", CMD_SINGLE, CMD_OPTIONAL,
		"tape size in Kbytes, defaults to size in tapeconfig");
    cmd_AddParm(ts, "-portoffset", CMD_SINGLE, CMD_OPTIONAL,
		"TC port offset");
    cmd_AddParm(ts, "-pname", CMD_SINGLE, CMD_OPTIONAL,
		"permanent tape name");
    if (!interact)
	add_std_args(ts);

    ts = cmd_CreateSyntax("readlabel", bc_ReadLabelCmd, NULL,
			  "read the label on tape");
    cmd_AddParm(ts, "-portoffset", CMD_SINGLE, CMD_OPTIONAL,
		"TC port offset");
    if (!interact)
	add_std_args(ts);

    ts = cmd_CreateSyntax("scantape", bc_ScanDumpsCmd, NULL,
			  "dump information recovery from tape");
    cmd_AddParm(ts, "-dbadd", CMD_FLAG, CMD_OPTIONAL,
		"add information to the database");
    cmd_AddParm(ts, "-portoffset", CMD_SINGLE, CMD_OPTIONAL,
		"TC port offset");
    if (!interact)
	add_std_args(ts);

    ts = cmd_CreateSyntax("volinfo", bc_dblookupCmd, NULL,
			  "query the backup database");
    cmd_AddParm(ts, "-volume", CMD_SINGLE, CMD_REQUIRED, "volume name");
    if (!interact)
	add_std_args(ts);

    ts = cmd_CreateSyntax("setexp", bc_SetExpCmd, NULL,
			  "set/clear dump expiration dates");
    cmd_AddParm(ts, "-dump", CMD_LIST, CMD_REQUIRED, "dump level name");
    cmd_AddParm(ts, "-expires", CMD_LIST, CMD_OPTIONAL, "expiration date");
    if (!interact)
	add_std_args(ts);

    ts = cmd_CreateSyntax("savedb", bc_saveDbCmd, NULL, "save backup database");
    cmd_AddParm(ts, "-portoffset", CMD_SINGLE, CMD_OPTIONAL,
		"TC port offset");
    cmd_AddParm(ts, "-archive", CMD_LIST, CMD_OPTIONAL, "date time");
    if (!interact)
	add_std_args(ts);

    ts = cmd_CreateSyntax("restoredb", bc_restoreDbCmd, NULL,
			  "restore backup database");
    cmd_AddParm(ts, "-portoffset", CMD_SINGLE, CMD_OPTIONAL,
		"TC port offset");
    if (!interact)
	add_std_args(ts);

    ts = cmd_CreateSyntax("dumpinfo", bc_dumpInfoCmd, NULL,
			  "provide information about a dump in the database");
    cmd_AddParm(ts, "-ndumps", CMD_SINGLE, CMD_OPTIONAL, "no. of dumps");
    cmd_AddParm(ts, "-id", CMD_SINGLE, CMD_OPTIONAL, "dump id");
    cmd_AddParm(ts, "-verbose", CMD_FLAG, CMD_OPTIONAL,
		"detailed description");
    if (!interact)
	add_std_args(ts);

    ts = cmd_CreateSyntax("dbverify", bc_dbVerifyCmd, NULL,
			  "check ubik database integrity");
    cmd_AddParm(ts, "-detail", CMD_FLAG, CMD_OPTIONAL, "additional details");
    if (!interact)
	add_std_args(ts);

    ts = cmd_CreateSyntax("deletedump", bc_deleteDumpCmd, NULL,
			  "delete dumps from the database");
    cmd_AddParm(ts, "-dumpid", CMD_LIST, CMD_OPTIONAL, "dump id");
    cmd_AddParm(ts, "-from", CMD_LIST, CMD_OPTIONAL, "date time");
    cmd_AddParm(ts, "-to", CMD_LIST, CMD_OPTIONAL, "date time");
    cmd_AddParm(ts, "-port", CMD_SINGLE, CMD_OPTIONAL, "TC port offset");
    cmd_AddParm(ts, "-groupid", CMD_SINGLE, CMD_OPTIONAL, "group ID");
    cmd_AddParm(ts, "-dbonly", CMD_FLAG, CMD_OPTIONAL,
		"delete the dump from the backup database only");
    cmd_AddParm(ts, "-force", CMD_FLAG, CMD_OPTIONAL,
		"always delete from backup database");
    cmd_AddParm(ts, "-noexecute", CMD_FLAG, CMD_OPTIONAL|CMD_HIDDEN, "");
    cmd_AddParm(ts, "-dryrun", CMD_FLAG, CMD_OPTIONAL,
		"list the dumps, don't delete anything");
    cmd_AddParmAlias(ts, 8, "-n");

    if (!interact)
	add_std_args(ts);

    ts = cmd_CreateSyntax("interactive", bc_interactCmd, NULL,
			  "enter interactive mode");
    add_std_args(ts);

    /*
     * Now execute the command.
     */

    targc = 0;
    targv[targc++] = argv[0];
    if (interact)
	targv[targc++] = "interactive";
    for (i = 1; i < argc; i++)
	targv[targc++] = argv[i];

    code = doDispatch(targc, targv, 1);

    if (!interact || !bcInit) {	/* Non-interactive mode */
	if (code)
	    exit(-1);
	if (bcInit)
	    code = bc_WaitForNoJobs();	/* wait for any jobs to finish */
	exit(code);		/* and exit */
    }

    /* Iterate on command lines, interpreting user commands (interactive mode) */
    while (1) {
	int ret;

	printf("backup> ");
	fflush(stdout);


	while ((ret = LWP_GetLine(lineBuffer, sizeof(lineBuffer))) == 0)
	    printf("%s: Command line too long\n", whoami);	/* line too long */

	if (ret == -1)
	    return 0;		/* Got EOF */

	if (!LineIsBlank(lineBuffer)) {
	    code = cmd_ParseLine(lineBuffer, targv, &targc, MAXV);
	    if (code)
		afs_com_err(whoami, code, "; Can't parse line: '%s'",
			afs_error_message(code));
	    else {
		doDispatch(targc, targv, 1);
		cmd_FreeArgv(targv);
	    }
	}
    }
}				/*main */
Esempio n. 21
0
afs_int32
ka_UserAuthenticateGeneral(afs_int32 flags, char *name, char *instance,
			   char *realm, char *password, Date lifetime,
			   afs_int32 * password_expires,	/* days 'til, or don't change if not set */
			   afs_int32 spare2, char **reasonP)
{
    int remainingTime = 0;
    struct ktc_encryptionKey key;
    afs_int32 code, dosetpag = 0;

    if (reasonP)
	*reasonP = "";
    if ((flags & KA_USERAUTH_VERSION_MASK) != KA_USERAUTH_VERSION)
	return KAOLDINTERFACE;
    if ((strcmp(name, "root") == 0) && (instance == 0)) {
	if (reasonP)
	    *reasonP = "root is only authenticated locally";
	return KANOENT;
    }
    code = ka_Init(0);
    if (code)
	return code;

    ka_StringToKey(password, realm, &key);

/*
 * alarm is set by kpasswd only so ignore for
 * NT
 */

#ifndef AFS_NT40_ENV
    {				/* Rx uses timers, save to be safe */
	if (rx_socket) {
	    /* don't reset alarms, rx already running */
	    remainingTime = 0;
	} else
	    remainingTime = alarm(0);
    }
#endif

#if !defined(AFS_NT40_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_USR_LINUX20_ENV) && (!defined(AFS_XBSD_ENV) || defined(AFS_FBSD_ENV))
    /* handle smoothly the case where no AFS system calls exists (yet) */
    (void)signal(SIGSYS, SIG_IGN);
#endif
#ifdef	AFS_DECOSF_ENV
    (void)signal(SIGTRAP, SIG_IGN);
#endif /* AFS_DECOSF_ENV */
    if (instance == 0)
	instance = "";
    if (flags & KA_USERAUTH_ONLY_VERIFY) {
	code = ka_VerifyUserToken(name, instance, realm, &key);
	if (code == KABADREQUEST) {
	    DES_string_to_key(password, ktc_to_cblockptr(&key));
	    code = ka_VerifyUserToken(name, instance, realm, &key);
	}
    } else {
#ifdef AFS_DUX40_ENV
	if (flags & KA_USERAUTH_DOSETPAG)
	    afs_setpag();
#else
#if !defined(UKERNEL) && !defined(AFS_NT40_ENV)
	if (flags & KA_USERAUTH_DOSETPAG)
	    setpag();
#endif
#endif
	if (flags & KA_USERAUTH_DOSETPAG2)
	    dosetpag = 1;
#ifdef AFS_KERBEROS_ENV
	if ((flags & KA_USERAUTH_DOSETPAG) || dosetpag)
	    ktc_newpag();
#endif
	if (lifetime == 0)
	    lifetime = MAXKTCTICKETLIFETIME;
	code =
	    GetTickets(name, instance, realm, &key, lifetime,
		       password_expires, dosetpag);
	if (code == KABADREQUEST) {
	    DES_string_to_key(password, ktc_to_cblockptr(&key));
	    code =
		GetTickets(name, instance, realm, &key, lifetime,
			   password_expires, dosetpag);
	}
    }

#ifndef AFS_NT40_ENV
    if (remainingTime) {
	pr_End();
	rx_Finalize();
	alarm(remainingTime);	/* restore timer, if any */
    }
#endif

    if (code && reasonP)
	switch (code) {
	case KABADREQUEST:
	    *reasonP = "password was incorrect";
	    break;
	case KAUBIKCALL:
	    *reasonP = "Authentication Server was unavailable";
	    break;
	default:
	    *reasonP = (char *)afs_error_message(code);
	}
    return code;
}
Esempio n. 22
0
/* Main program */
int
main(int argc, char **argv)
{
    XFILE input_file;
    afs_uint32 r;

    parse_options(argc, argv);
    initialize_acfg_error_table();
    initialize_AVds_error_table();
    initialize_rxk_error_table();
    initialize_u_error_table();
    initialize_vl_error_table();
    initialize_vols_error_table();
    initialize_xFil_error_table();
    r = xfopen(&input_file, O_RDONLY, input_path);
    if (r) {
	afs_com_err(argv0, r, "opening %s", input_path);
	exit(2);
    }

    memset(&dp, 0, sizeof(dp));
    dp.cb_error = my_error_cb;
    if (input_file.is_seekable)
	dp.flags |= DSFLAG_SEEK;
    dirs_done = 0;

    if (!use_vnum) {
	dt_uint64 where;

	memset(&phi, 0, sizeof(phi));
	phi.p = &dp;

	if (verbose)
	    printf("* Building pathname info...\n");
	if ((r = xftell(&input_file, &where))
	    || (r = Path_PreScan(&input_file, &phi, 1))
	    || (r = xfseek(&input_file, &where))) {
	    afs_com_err(argv0, r, "- path initialization failed");
	    xfclose(&input_file);
	    exit(1);
	}
    }

    dp.cb_vnode_dir = directory_cb;
    dp.cb_vnode_file = file_cb;
    dp.cb_vnode_link = symlink_cb;
    dp.cb_vnode_empty = lose_cb;
    dp.cb_vnode_wierd = lose_cb;
    if (do_headers) {
	dp.cb_dumphdr = dumphdr_cb;
	dp.cb_volhdr = volhdr_cb;
    }

    if (!nomode) {
	mkdir(target, 0755);
	if (chdir(target)) {
	    fprintf(stderr, "chdir %s failed: %s\n", target, strerror(errno));
	    exit(1);
	}
    }
    r = ParseDumpFile(&input_file, &dp);

    if (verbose && error_count)
	fprintf(stderr, "*** %d errors\n", error_count);
    if (r && !quiet)
	fprintf(stderr, "*** FAILED: %s\n", afs_error_message(r));
    exit(0);
}
Esempio n. 23
0
void
LogError(afs_int32 errcode)
{
    ViceLog(0,
	    ("%s: %s\n", afs_error_table_name(errcode), afs_error_message(errcode)));
}
Esempio n. 24
0
/* Main program */
void
main(int argc, char **argv)
{
    XFILE *X;
    afs_uint32 r;

    parse_options(argc, argv);
    initialize_UB_error_table();
    initialize_UBsp_error_table();
    initialize_AVds_error_table();
    r = xfopen(&X, input_path, O_RDONLY, 0);
    if (r) {
	afs_com_err(argv0, r, "opening %s", input_path);
	exit(2);
    }

    bzero(&dp, sizeof(dp));
    dp.cb_error = my_error_cb;
    dp.repair_flags = repairflags;
    if (X->is_seekable)
	dp.flags |= DSFLAG_SEEK;
    else {
	if (repairflags)
	    fprintf(stderr,
		    "Repair modes available only for seekable dumps\n");
	if (printflags & DSPRINT_PATH)
	    fprintf(stderr,
		    "Path-printing available only for seekable dumps\n");
	if (repairflags || (printflags & DSPRINT_PATH))
	    exit(1);
    }

    if (gendump_path && (r = setup_repair())) {
	afs_com_err(argv0, r, "setting up repair output");
	xfclose(X);
	exit(2);
    }

    if (printflags & DSPRINT_PATH) {
	u_int64 where;

	dp.print_flags = printflags & DSPRINT_DEBUG;
	bzero(&phi, sizeof(phi));
	phi.p = &dp;

	if ((r = xftell(X, &where))
	    || (r = Path_PreScan(X, &phi, 0))
	    || (r = xfseek(X, &where))) {
	    afs_com_err(argv0, r, "- path initialization failed");
	    xfclose(X);
	    exit(2);
	}

	dp.cb_vnode_dir = print_vnode_path;
	dp.cb_vnode_file = print_vnode_path;
	dp.cb_vnode_link = print_vnode_path;
	dp.cb_vnode_empty = print_vnode_path;
	dp.cb_vnode_wierd = print_vnode_path;
    }

    if (add_admin) {
	dp.cb_vnode_dir = munge_admin_acl;
    }

    dp.print_flags = printflags;
    r = ParseDumpFile(X, &dp);
    if (gendump_path) {
	if (!r)
	    r = DumpDumpEnd(&repair_output);
	if (!r)
	    r = xfclose(&repair_output);
	else
	    xfclose(&repair_output);
    }

    if (verbose && error_count)
	fprintf(stderr, "*** %d errors\n", error_count);
    if (r && !quiet)
	fprintf(stderr, "*** FAILED: %s\n", afs_error_message(r));
    exit(0);
}
Esempio n. 25
0
int
aklog_authenticate(char *userName, char *response, int *reenter, char **message)
{
    char *reason, *pword, prompt[256];
    struct passwd *pwd;
    int code, unixauthneeded, password_expires = -1;
    int status;
    krb5_context context;

    krb5_init_context(&context);
    *reenter = 0;
    *message = (char *)0;

    status = auth_to_cell(context, userName, NULL, NULL);

    if (status) {
        char *str = afs_error_message(status);
        *message = (char *)malloc(1024);
#ifdef HAVE_KRB5_SVC_GET_MSG
        if (strncmp(str, "unknown", strlen("unknown")) == 0) {
            krb5_svc_get_msg(status,&str);
            sprintf(*message, "Unable to obtain AFS tokens: %s.\n",
                    str);
            krb5_free_string(context, str);
        } else
#endif
            sprintf(*message, "Unable to obtain AFS tokens: %s.\n",
                    str);
        return AUTH_FAILURE; /* NOTFOUND? */
    }

#if 0
    /*
     * Local hack - if the person has a file in their home
     * directory called ".xlog", read that for a list of
     * extra cells to authenticate to
     */

    if ((pwd = getpwuid(getuid())) != NULL) {
        struct stat sbuf;
        FILE *f;
        char fcell[100], xlog_path[512];

        strcpy(xlog_path, pwd->pw_dir);
        strcat(xlog_path, "/.xlog");

        if ((stat(xlog_path, &sbuf) == 0) &&
                ((f = fopen(xlog_path, "r")) != NULL)) {

            while (fgets(fcell, 100, f) != NULL) {
                int auth_status;

                fcell[strlen(fcell) - 1] = '\0';

                auth_status = auth_to_cell(context, userName, fcell, NULL);
                if (status == AKLOG_SUCCESS)
                    status = auth_status;
                else
                    status = AKLOG_SOMETHINGSWRONG;
            }
        }
    }
#endif
    return AUTH_SUCCESS;
}
Esempio n. 26
0
static int
PrintCacheEntries64(struct rx_connection *aconn, int aint32)
{
    int i;
    afs_int32 code;
    struct AFSDBCacheEntry64 centry;
    char *cellname;

    for (i = 0; i < 1000000; i++) {
	code = RXAFSCB_GetCE64(aconn, i, &centry);
	if (code) {
	    if (code == 1)
		break;
	    printf("cmdebug: failed to get cache entry %d (%s)\n", i,
		   afs_error_message(code));
	    return code;
	}

	if (centry.addr == 0) {
	    /* PS output */
	    printf("Proc %4d sleeping at %08x, pri %3d\n",
		   centry.netFid.Vnode, centry.netFid.Volume,
		   centry.netFid.Unique - 25);
	    continue;
	}

	if ((aint32 == 0 && !IsLocked(&centry.lock)) ||
            (aint32 == 2 && centry.refCount == 0) ||
            (aint32 == 4 && centry.callback == 0))
	    continue;

	/* otherwise print this entry */
	printf("** Cache entry @ 0x%08x for %d.%d.%d.%d", centry.addr,
	       centry.cell, centry.netFid.Volume, centry.netFid.Vnode,
	       centry.netFid.Unique);

	cellname = GetCellName(aconn, centry.cell);
	if (cellname)
	    printf(" [%s]\n", cellname);
	else
	    printf("\n");

	if (IsLocked(&centry.lock)) {
	    printf("    locks: ");
	    PrintLock(&centry.lock);
	    printf("\n");
	}
#ifdef AFS_NT40_ENV
	printf("    %12I64d bytes  DV %12d  refcnt %5d\n", centry.Length,
	       centry.DataVersion, centry.refCount);
#else
	printf("    %12llu bytes  DV %12d  refcnt %5d\n", centry.Length,
	       centry.DataVersion, centry.refCount);
#endif
        if (print_ctime) {
            time_t t = centry.cbExpires;
            printf("    callback %08x\texpires %s\n", centry.callback,
                    ctime(&t));
        } else
            printf("    callback %08x\texpires %u\n", centry.callback,
                   centry.cbExpires);
	printf("    %d opens\t%d writers\n", centry.opens, centry.writers);

	/* now display states */
	printf("    ");
	if (centry.mvstat == 0)
	    printf("normal file");
	else if (centry.mvstat == 1)
	    printf("mount point");
	else if (centry.mvstat == 2)
	    printf("volume root");
	else if (centry.mvstat == 3)
	    printf("directory");
	else if (centry.mvstat == 4)
	    printf("symlink");
	else if (centry.mvstat == 5)
	    printf("microsoft dfs link");
	else if (centry.mvstat == 6)
	    printf("invalid link");
        else
	    printf("bogus mvstat %d", centry.mvstat);
	printf("\n    states (0x%x)", centry.states);
	if (centry.states & 1)
	    printf(", stat'd");
	if (centry.states & 2)
	    printf(", backup");
	if (centry.states & 4)
	    printf(", read-only");
	if (centry.states & 8)
	    printf(", mt pt valid");
	if (centry.states & 0x10)
	    printf(", pending core");
	if (centry.states & 0x40)
	    printf(", wait-for-store");
	if (centry.states & 0x80)
	    printf(", mapped");
	printf("\n");
    }
    return 0;
}
Esempio n. 27
0
int
main(int argc, char **argv)
{
    afs_int32 code;
    afs_uint32 myHost;
    struct rx_service *tservice;
    struct rx_securityClass **securityClasses;
    afs_int32 numClasses;
    struct afsconf_dir *tdir;
    struct ktc_encryptionKey tkey;
    struct afsconf_cell info;
    struct hostent *th;
    char hostname[VL_MAXNAMELEN];
    int noAuth = 0;
    char clones[MAXHOSTSPERCELL];
    afs_uint32 host = ntohl(INADDR_ANY);
    struct cmd_syndesc *opts;

    char *vl_dbaseName;
    char *configDir;
    char *logFile;

    char *auditFileName = NULL;
    char *interface = NULL;
    char *optstring = NULL;

#ifdef	AFS_AIX32_ENV
    /*
     * The following signal action for AIX is necessary so that in case of a
     * crash (i.e. core is generated) we can include the user's data section
     * in the core dump. Unfortunately, by default, only a partial core is
     * generated which, in many cases, isn't too useful.
     */
    struct sigaction nsa;

    rx_extraPackets = 100;	/* should be a switch, I guess... */
    sigemptyset(&nsa.sa_mask);
    nsa.sa_handler = SIG_DFL;
    nsa.sa_flags = SA_FULLDUMP;
    sigaction(SIGABRT, &nsa, NULL);
    sigaction(SIGSEGV, &nsa, NULL);
#endif
    osi_audit_init();

    /* Initialize dirpaths */
    if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
#ifdef AFS_NT40_ENV
	ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
#endif
	fprintf(stderr, "%s: Unable to obtain AFS server directory.\n",
		argv[0]);
	exit(2);
    }

    vl_dbaseName = strdup(AFSDIR_SERVER_VLDB_FILEPATH);
    configDir = strdup(AFSDIR_SERVER_ETC_DIRPATH);
    logFile = strdup(AFSDIR_SERVER_VLOG_FILEPATH);

    cmd_DisableAbbreviations();
    cmd_DisablePositionalCommands();
    opts = cmd_CreateSyntax(NULL, NULL, NULL, NULL);

    /* vlserver specific options */
    cmd_AddParmAtOffset(opts, OPT_noauth, "-noauth", CMD_FLAG,
		        CMD_OPTIONAL, "disable authentication");
    cmd_AddParmAtOffset(opts, OPT_smallmem, "-smallmem", CMD_FLAG,
		        CMD_OPTIONAL, "optimise for small memory systems");

    /* general server options */
    cmd_AddParmAtOffset(opts, OPT_auditlog, "-auditlog", CMD_SINGLE,
		        CMD_OPTIONAL, "location of audit log");
    cmd_AddParmAtOffset(opts, OPT_auditiface, "-audit-interface", CMD_SINGLE,
		        CMD_OPTIONAL, "interface to use for audit logging");
    cmd_AddParmAtOffset(opts, OPT_config, "-config", CMD_SINGLE,
		        CMD_OPTIONAL, "configuration location");
    cmd_AddParmAtOffset(opts, OPT_debug, "-d", CMD_SINGLE,
		        CMD_OPTIONAL, "debug level");
    cmd_AddParmAtOffset(opts, OPT_database, "-database", CMD_SINGLE,
		        CMD_OPTIONAL, "database file");
    cmd_AddParmAlias(opts, OPT_database, "-db");
    cmd_AddParmAtOffset(opts, OPT_logfile, "-logfile", CMD_SINGLE,
		        CMD_OPTIONAL, "location of logfile");
    cmd_AddParmAtOffset(opts, OPT_threads, "-p", CMD_SINGLE, CMD_OPTIONAL,
		        "number of threads");
#if !defined(AFS_NT40_ENV)
    cmd_AddParmAtOffset(opts, OPT_syslog, "-syslog", CMD_SINGLE_OR_FLAG,
		        CMD_OPTIONAL, "log to syslog");
#endif

    /* rx options */
    cmd_AddParmAtOffset(opts, OPT_peer, "-enable_peer_stats", CMD_FLAG,
		        CMD_OPTIONAL, "enable RX transport statistics");
    cmd_AddParmAtOffset(opts, OPT_process, "-enable_process_stats", CMD_FLAG,
		        CMD_OPTIONAL, "enable RX RPC statistics");
    cmd_AddParmAtOffset(opts, OPT_nojumbo, "-nojumbo", CMD_FLAG,
		        CMD_OPTIONAL, "disable jumbograms");
    cmd_AddParmAtOffset(opts, OPT_jumbo, "-jumbo", CMD_FLAG,
		        CMD_OPTIONAL, "enable jumbograms");
    cmd_AddParmAtOffset(opts, OPT_rxbind, "-rxbind", CMD_FLAG,
		        CMD_OPTIONAL, "bind only to the primary interface");
    cmd_AddParmAtOffset(opts, OPT_rxmaxmtu, "-rxmaxmtu", CMD_SINGLE,
		        CMD_OPTIONAL, "maximum MTU for RX");
    cmd_AddParmAtOffset(opts, OPT_trace, "-trace", CMD_SINGLE,
		        CMD_OPTIONAL, "rx trace file");

    /* rxkad options */
    cmd_AddParmAtOffset(opts, OPT_dotted, "-allow-dotted-principals",
		        CMD_FLAG, CMD_OPTIONAL,
		        "permit Kerberos 5 principals with dots");

    code = cmd_Parse(argc, argv, &opts);
    if (code)
	return -1;

    cmd_OptionAsString(opts, OPT_config, &configDir);

    cmd_OpenConfigFile(AFSDIR_SERVER_CONFIG_FILE_FILEPATH);
    cmd_SetCommandName("vlserver");

    /* vlserver options */
    cmd_OptionAsFlag(opts, OPT_noauth, &noAuth);
    cmd_OptionAsFlag(opts, OPT_smallmem, &smallMem);
    if (cmd_OptionAsString(opts, OPT_trace, &optstring) == 0) {
	extern char rxi_tracename[80];
	strcpy(rxi_tracename, optstring);
	free(optstring);
	optstring = NULL;
    }

    /* general server options */

    cmd_OptionAsString(opts, OPT_auditlog, &auditFileName);

    if (cmd_OptionAsString(opts, OPT_auditiface, &interface) == 0) {
	if (osi_audit_interface(interface)) {
	    printf("Invalid audit interface '%s'\n", interface);
	    return -1;
	}
	free(interface);
    }

    cmd_OptionAsInt(opts, OPT_debug, &LogLevel);
    cmd_OptionAsString(opts, OPT_database, &vl_dbaseName);
    cmd_OptionAsString(opts, OPT_logfile, &logFile);

    if (cmd_OptionAsInt(opts, OPT_threads, &lwps) == 0) {
	if (lwps > MAXLWP) {
	     printf("Warning: '-p %d' is too big; using %d instead\n",
		    lwps, MAXLWP);
	     lwps = MAXLWP;
	}
    }
#ifndef AFS_NT40_ENV
    if (cmd_OptionPresent(opts, OPT_syslog)) {
        serverLogSyslog = 1;
        cmd_OptionAsInt(opts, OPT_syslog, &serverLogSyslogFacility);
    }
#endif

    /* rx options */
    if (cmd_OptionPresent(opts, OPT_peer))
	rx_enablePeerRPCStats();
    if (cmd_OptionPresent(opts, OPT_process))
	rx_enableProcessRPCStats();
    if (cmd_OptionPresent(opts, OPT_nojumbo))
	rxJumbograms = 0;
    if (cmd_OptionPresent(opts, OPT_jumbo))
	rxJumbograms = 1;

    cmd_OptionAsFlag(opts, OPT_rxbind, &rxBind);

    cmd_OptionAsInt(opts, OPT_rxmaxmtu, &rxMaxMTU);

    /* rxkad options */
    cmd_OptionAsFlag(opts, OPT_dotted, &rxkadDisableDotCheck);

    if (auditFileName) {
	osi_audit_file(auditFileName);
    }

#ifndef AFS_NT40_ENV
    serverLogSyslogTag = "vlserver";
#endif
    OpenLog(logFile);	/* set up logging */
    SetupLogSignals();

    tdir = afsconf_Open(configDir);
    if (!tdir) {
	VLog(0,
	    ("vlserver: can't open configuration files in dir %s, giving up.\n",
	     configDir));
	exit(1);
    }

    /* initialize audit user check */
    osi_audit_set_user_check(tdir, vldb_IsLocalRealmMatch);

#ifdef AFS_NT40_ENV
    /* initialize winsock */
    if (afs_winsockInit() < 0) {
	ReportErrorEventAlt(AFSEVT_SVR_WINSOCK_INIT_FAILED, 0, argv[0], 0);
	VLog(0, ("vlserver: couldn't initialize winsock. \n"));
	exit(1);
    }
#endif
    /* get this host */
    gethostname(hostname, sizeof(hostname));
    th = gethostbyname(hostname);
    if (!th) {
	VLog(0, ("vlserver: couldn't get address of this host (%s).\n",
	       hostname));
	exit(1);
    }
    memcpy(&myHost, th->h_addr, sizeof(afs_uint32));

#if !defined(AFS_HPUX_ENV) && !defined(AFS_NT40_ENV)
    signal(SIGXCPU, CheckSignal_Signal);
#endif
    /* get list of servers */
    code =
	afsconf_GetExtendedCellInfo(tdir, NULL, AFSCONF_VLDBSERVICE, &info,
				    clones);
    if (code) {
	printf("vlserver: Couldn't get cell server list for 'afsvldb'.\n");
	exit(2);
    }

    vldb_confdir = tdir;	/* Preserve our configuration dir */
    /* rxvab no longer supported */
    memset(&tkey, 0, sizeof(tkey));

    if (noAuth)
	afsconf_SetNoAuthFlag(tdir, 1);

    if (rxBind) {
	afs_int32 ccode;
#ifndef AFS_NT40_ENV
        if (AFSDIR_SERVER_NETRESTRICT_FILEPATH ||
            AFSDIR_SERVER_NETINFO_FILEPATH) {
            char reason[1024];
            ccode = afsconf_ParseNetFiles(SHostAddrs, NULL, NULL,
					  ADDRSPERSITE, reason,
					  AFSDIR_SERVER_NETINFO_FILEPATH,
					  AFSDIR_SERVER_NETRESTRICT_FILEPATH);
        } else
#endif
	{
            ccode = rx_getAllAddr(SHostAddrs, ADDRSPERSITE);
        }
        if (ccode == 1) {
            host = SHostAddrs[0];
	    rx_InitHost(host, htons(AFSCONF_VLDBPORT));
	}
    }

    if (!rxJumbograms) {
	rx_SetNoJumbo();
    }
    if (rxMaxMTU != -1) {
	if (rx_SetMaxMTU(rxMaxMTU) != 0) {
	    VLog(0, ("rxMaxMTU %d invalid\n", rxMaxMTU));
	    return -1;
	}
    }

    ubik_nBuffers = 512;
    ubik_SetClientSecurityProcs(afsconf_ClientAuth, afsconf_UpToDate, tdir);
    ubik_SetServerSecurityProcs(afsconf_BuildServerSecurityObjects,
				afsconf_CheckAuth, tdir);

    ubik_SyncWriterCacheProc = vlsynccache;
    code =
	ubik_ServerInitByInfo(myHost, htons(AFSCONF_VLDBPORT), &info, clones,
			      vl_dbaseName, &VL_dbase);
    if (code) {
	VLog(0, ("vlserver: Ubik init failed: %s\n", afs_error_message(code)));
	exit(2);
    }
    rx_SetRxDeadTime(50);

    memset(rd_HostAddress, 0, sizeof(rd_HostAddress));
    memset(wr_HostAddress, 0, sizeof(wr_HostAddress));
    initialize_dstats();

    afsconf_BuildServerSecurityObjects(tdir, &securityClasses, &numClasses);

    tservice =
	rx_NewServiceHost(host, 0, USER_SERVICE_ID, "Vldb server",
			  securityClasses, numClasses,
			  VL_ExecuteRequest);
    if (tservice == (struct rx_service *)0) {
	VLog(0, ("vlserver: Could not create VLDB_SERVICE rx service\n"));
	exit(3);
    }
    rx_SetMinProcs(tservice, 2);
    if (lwps < 4)
	lwps = 4;
    rx_SetMaxProcs(tservice, lwps);

    if (rxkadDisableDotCheck) {
        rx_SetSecurityConfiguration(tservice, RXS_CONFIG_FLAGS,
                                    (void *)RXS_CONFIG_FLAGS_DISABLE_DOTCHECK);
    }

    tservice =
	rx_NewServiceHost(host, 0, RX_STATS_SERVICE_ID, "rpcstats",
			  securityClasses, numClasses,
			  RXSTATS_ExecuteRequest);
    if (tservice == (struct rx_service *)0) {
	VLog(0, ("vlserver: Could not create rpc stats rx service\n"));
	exit(3);
    }
    rx_SetMinProcs(tservice, 2);
    rx_SetMaxProcs(tservice, 4);

    LogCommandLine(argc, argv, "vlserver", VldbVersion, "Starting AFS", FSLog);
    VLog(0, ("%s\n", cml_version_number));

    /* allow super users to manage RX statistics */
    rx_SetRxStatUserOk(vldb_rxstat_userok);

    rx_StartServer(1);		/* Why waste this idle process?? */

    return 0; /* not reachable */
}
Esempio n. 28
0
int
main(int argc, char **argv)
{
    char scell[MAXCELLCHARS], dcell[MAXCELLCHARS];
    afs_uint32 ssrv, dsrv;
    char *databuffer, *srcf = NULL, *destd = NULL, *destf = NULL, *destpath = NULL;
    struct stat statbuf;

    struct AFSStoreStatus sst;
    struct AFSFetchStatus fst, dfst;
    struct AFSVolSync vs;
    struct AFSCallBack scb, dcb;
    struct AFSFid sf, dd, df;

    int filesz = 0;
    int ch, blksize, bytesremaining, bytes;
    struct timeval start, finish;
    struct timezone tz;
    struct rx_securityClass *ssc = 0, *dsc = 0;
    int sscindex, dscindex;
    struct rx_connection *sconn = NULL, *dconn = NULL;
    struct rx_call *scall = NULL, *dcall = NULL;
    int code = 0, fetchcode, storecode, printcallerrs = 0;
    int slcl = 0, dlcl = 0, unlock = 0;
    int sfd = 0, dfd = 0, unauth = 0;

    struct AFSCBFids theFids;
    struct AFSCBs theCBs;


    blksize = 8 * 1024;

    while ((ch = getopt(argc, argv, "iouUb:")) != -1) {
	switch (ch) {
	case 'b':
	    blksize = atoi(optarg);
	    break;
	case 'i':
	    slcl = 1;
	    break;
	case 'o':
	    dlcl = 1;
	    break;
	case 'u':
	    unauth = 1;
	    break;
	case 'U':
	    unlock = 1;
	    break;
	default:
	    printf("Unknown option '%c'\n", ch);
	    exit(1);
	}
    }


    if (argc - optind + unlock < 2) {
	fprintf(stderr,
		"Usage: afscp [-i|-o]] [-b xfersz] [-u] [-U] source [dest]\n");
	fprintf(stderr, "  -b   Set block size\n");
	fprintf(stderr, "  -i   Source is local (copy into AFS)\n");
	fprintf(stderr, "  -o   Dest is local (copy out of AFS)\n");
	fprintf(stderr, "  -u   Run unauthenticated\n");
	fprintf(stderr, "  -U   Send an unlock request for source. (dest path not required)\n");
	fprintf(stderr, "source and dest can be paths or specified as:\n");
	fprintf(stderr, "     @afs:cellname:servername:volume:vnode:uniq\n");
	exit(1);
    }
    srcf = argv[optind++];
    if (!unlock) {
	destpath = argv[optind++];
	destd = strdup(destpath);
	if (!destd) {
	    perror("strdup");
	    exit(1);
	}
	if ((destf = strrchr(destd, '/'))) {
	    *destf++ = 0;
	} else {
	    destf = destd;
	    destd = ".";
	}
    } else if (slcl) {
	fprintf(stderr, "-i and -U cannot be used together\n");
    }

    if (!slcl && statfile(srcf, scell, &ssrv, &sf)) {
	fprintf(stderr, "Cannot get attributes of %s\n", srcf);
	exit(1);
    }
    if (!unlock && !dlcl && statfile(destd, dcell, &dsrv, &dd)) {
	fprintf(stderr, "Cannot get attributes of %s\n", destd);
	exit(1);
    }

    if ((databuffer = malloc(blksize)) == NULL) {
	perror("malloc");
	exit(1);
    }

    if (do_rx_Init())
	exit(1);

    if (start_cb_server()) {
	printf("Cannot start callback service\n");
	goto Fail_rx;
    }

    if (!slcl) {
	sscindex = scindex_RXKAD;
	if (unauth || (ssc = get_sc(scell)) == NULL) {
	    ssc = rxnull_NewClientSecurityObject();
	    sscindex = scindex_NULL;
	    /*printf("Cannot get authentication for cell %s; running unauthenticated\n", scell); */
	}
	sscindex = scindex_NULL;

	if ((sconn =
	     rx_NewConnection(ssrv, htons(AFSCONF_FILEPORT), 1, ssc,
			      sscindex))
	    == NULL) {
	    struct in_addr s;
	    s.s_addr = ssrv;
	    printf("Cannot initialize rx connection to source server (%s)\n",
		   inet_ntoa(s));
	    goto Fail_sc;
	}
    }

    if (!dlcl && !unlock) {
	if (!slcl && ssrv == dsrv) {
	    dconn = sconn;
	    dsc = NULL;
	} else {
	    if (slcl || strcmp(scell, dcell)) {
		dscindex = scindex_RXKAD;
		if (unauth || (dsc = get_sc(dcell)) == NULL) {
		    dsc = rxnull_NewClientSecurityObject();
		    dscindex = scindex_NULL;
		    /*printf("Cannot get authentication for cell %s; running unauthenticated\n", dcell); */
		}
		dscindex = scindex_NULL;
	    } else {
		dsc = ssc;
		dscindex = sscindex;
	    }

	    if ((dconn =
		 rx_NewConnection(dsrv, htons(AFSCONF_FILEPORT), 1, dsc,
				  dscindex))
		== NULL) {
		struct in_addr s;
		s.s_addr = dsrv;
		printf
		    ("Cannot initialize rx connection to dest server (%s)\n",
		     inet_ntoa(s));
		goto Fail_sconn;
	    }
	}
    }


    memset(&sst, 0, sizeof(struct AFSStoreStatus));

    if (dlcl && !unlock) {
	dfd = open(destpath, O_RDWR | O_CREAT | O_EXCL, 0666);
	if (dfd < 0 && errno == EEXIST) {
	    printf("%s already exists, overwriting\n", destpath);
	    dfd = open(destpath, O_RDWR | O_TRUNC, 0666);
	    if (dfd < 0) {
		fprintf(stderr, "Cannot open %s (%s)\n", destpath,
			afs_error_message(errno));
		goto Fail_dconn;
	    }
	} else if (dfd < 0) {
	    fprintf(stderr, "Cannot open %s (%s)\n", destpath,
		    afs_error_message(errno));
	    goto Fail_dconn;
	}
    } else if (!unlock) {
	if ((code =
	     RXAFS_CreateFile(dconn, &dd, destf, &sst, &df, &fst, &dfst, &dcb,
			      &vs))) {
	    if (code == EEXIST) {
		printf("%s already exits, overwriting\n", destpath);
		if (statfile(destpath, dcell, &dsrv, &df))
		    fprintf(stderr, "Cannot get attributes of %s\n",
			    destpath);
		else
		    code = 0;
	    } else {
		printf("Cannot create %s (%s)\n", destpath,
		       afs_error_message(code));
		if (code)
		    goto Fail_dconn;
	    }
	}
    }

    if (slcl) {
	sfd = open(srcf, O_RDONLY, 0);
	if (sfd < 0) {
	    fprintf(stderr, "Cannot open %s (%s)\n", srcf,
		    afs_error_message(errno));
	    goto Fail_dconn;
	}
	if (fstat(sfd, &statbuf) < 0) {
	    fprintf(stderr, "Cannot stat %s (%s)\n", srcf,
		    afs_error_message(errno));
	    close(sfd);
	    goto Fail_dconn;
	}
    } else {
	if ((code = RXAFS_FetchStatus(sconn, &sf, &fst, &scb, &vs))) {
	    printf("Cannot fetchstatus of %d.%d (%s)\n", sf.Volume, sf.Vnode,
		   afs_error_message(code));
	    goto Fail_dconn;
	}
    }



    if (slcl) {
	filesz = statbuf.st_size;
    } else {
	filesz = fst.Length;
    }

    printcallerrs = 0;
    fetchcode = 0;
    storecode = 0;
    if (!slcl && !unlock)
	scall = rx_NewCall(sconn);
    if (!dlcl && !unlock)
	dcall = rx_NewCall(dconn);
    gettimeofday(&start, &tz);
    if (unlock) {
	if (fst.lockCount) {
	    printf("Sending 1 unlock for %s (%d locks)\n", srcf, fst.lockCount);
	    if ((code = RXAFS_ReleaseLock(sconn, &sf, &vs))) {
		printf("Unable to unlock %s (%s)\n", srcf,
		       afs_error_message(code));
	    }
	} else {
	    printf("No locks for %s\n", srcf);
	}
	fetchcode = code;
	goto Finish;
    }

    if (!slcl) {
	if ((code = StartRXAFS_FetchData(scall, &sf, 0, filesz))) {
	    printf("Unable to fetch data from %s (%s)\n", srcf,
		   afs_error_message(code));
	    goto Fail_call;
	}
    }

    if (!dlcl) {
	if (slcl) {
	    sst.Mask = AFS_SETMODTIME | AFS_SETMODE;
	    sst.ClientModTime = statbuf.st_mtime;
	    sst.UnixModeBits =
		statbuf.st_mode & ~(S_IFMT | S_ISUID | S_ISGID);
	} else {
	    sst.Mask = AFS_SETMODTIME | AFS_SETMODE;
	    sst.ClientModTime = fst.ClientModTime;
	    sst.UnixModeBits =
		fst.UnixModeBits & ~(S_IFMT | S_ISUID | S_ISGID);
	}

	if ((code =
	     StartRXAFS_StoreData(dcall, &df, &sst, 0, filesz, filesz))) {
	    printf("Unable to store data to %s (%s)\n", destpath,
		   afs_error_message(code));
	    goto Fail_call;
	}
    }

    if (slcl) {
	bytesremaining = statbuf.st_size;
    } else {
	rx_Read(scall, (char *)&bytesremaining, sizeof(afs_int32));
	bytesremaining = ntohl(bytesremaining);
    }

    while (bytesremaining > 0) {
	/*printf("%d bytes remaining\n",bytesremaining); */
	if (slcl) {
	    if ((bytes =
		 read(sfd, databuffer, min(blksize, bytesremaining))) <= 0) {
		fetchcode = errno;
		break;
	    }
	} else {
	    if ((bytes =
		 rx_Read(scall, databuffer,
			 min(blksize, bytesremaining))) <= 0)
		break;
	}
	if (dlcl) {
	    if (write(dfd, databuffer, bytes) != bytes) {
		storecode = errno;
		break;
	    }
	} else {
	    if (rx_Write(dcall, databuffer, bytes) != bytes)
		break;
	}
	bytesremaining -= bytes;
	/*printf("%d bytes copied\n",bytes); */
    }


    if (bytesremaining > 0) {
	printf("Some network error occured while copying data\n");
	goto Fail_call;
    }

    if (!slcl)
	fetchcode = EndRXAFS_FetchData(scall, &fst, &scb, &vs);
    if (!dlcl)
	storecode = EndRXAFS_StoreData(dcall, &fst, &vs);
    printcallerrs = 1;
  Fail_call:

    if (slcl) {
	if (close(sfd) && !fetchcode)
	    fetchcode = errno;
    } else {
	fetchcode = rx_EndCall(scall, fetchcode);
    }
    if (fetchcode && printcallerrs)
	printf("Error returned from fetch: %s\n", afs_error_message(fetchcode));

    if (dlcl) {
	if (close(dfd) && !storecode)
	    storecode = errno;
    } else if (!unlock) {
	storecode = rx_EndCall(dcall, storecode);
    }
    if (storecode && printcallerrs)
	printf("Error returned from store: %s\n", afs_error_message(storecode));
Finish:
    gettimeofday(&finish, &tz);

    if (!slcl) {
	theFids.AFSCBFids_len = 1;
	theFids.AFSCBFids_val = &sf;
	theCBs.AFSCBs_len = 1;
	theCBs.AFSCBs_val = &scb;
	scb.CallBackType = CB_DROPPED;
	if ((code = RXAFS_GiveUpCallBacks(sconn, &theFids, &theCBs)))
	    printf("Could not give up source callback: %s\n",
		   afs_error_message(code));
    }

    if (!dlcl) {
	theFids.AFSCBFids_len = 1;
	theFids.AFSCBFids_val = &df;
	theCBs.AFSCBs_len = 1;
	theCBs.AFSCBs_val = &dcb;
	dcb.CallBackType = CB_DROPPED;
	if ((code = RXAFS_GiveUpCallBacks(dconn, &theFids, &theCBs)))
	    printf("Could not give up target callback: %s\n",
		   afs_error_message(code));
    }

    if (code == 0)
	code = storecode;
    if (code == 0)
	code = fetchcode;

  Fail_dconn:
    if (!dlcl && !unlock && (slcl || dconn != sconn))
	rx_DestroyConnection(dconn);
  Fail_sconn:
    if (!slcl)
	rx_DestroyConnection(sconn);
  Fail_sc:
    if (dsc && dsc != ssc)
	RXS_Close(dsc);
    if (ssc)
	RXS_Close(ssc);
  Fail_rx:
    rx_Finalize();

    free(databuffer);
    if (printcallerrs && !unlock) {
	double rate, size, time;
	if (finish.tv_sec == start.tv_sec) {
	    printf("Copied %d bytes in %d microseconds\n", filesz,
		   (int)(finish.tv_usec - start.tv_usec));
	} else {
	    printf("Copied %d bytes in %d seconds\n", filesz,
		   (int)(finish.tv_sec - start.tv_sec));
	}

	size = filesz / 1024.0;
	time =
	    finish.tv_sec - start.tv_sec + (finish.tv_usec -
					    start.tv_usec) / 1e+06;
	rate = size / time;
	printf("Transfer rate %g Kbytes/sec\n", rate);

    }

    exit(code != 0);
}
Esempio n. 29
0
static int
CommandProc(struct cmd_syndesc *a_as, void *arock)
{
    int i;
    long code = 0;
    long upos;
    long gpos = 0;
    struct prentry uentry, gentry;
    struct ubik_hdr *uh;
    char *dfile = 0;
    const char *pbase = AFSDIR_SERVER_PRDB_FILEPATH;
    char *pfile = NULL;
    char pbuffer[1028];
    struct cmd_parmdesc *tparm;

    tparm = a_as->parms;

    if (tparm[0].items) {
	wflag++;
	/* so we are treated as admin and can create "mis"owned
	   groups */
	pr_noAuth = 1;
    }
    if (tparm[1].items) {
	flags |= DO_USR;
    }
    if (tparm[2].items) {
	flags |= DO_GRP;
    }
    if (tparm[3].items) {
	flags |= (DO_GRP | DO_MEM);
    }
    if (tparm[4].items) {
	nflag++;
    }
    if (tparm[5].items) {
	flags |= DO_SYS;
    }
    if (tparm[6].items) {
	flags |= DO_OTR;
    }
    if (tparm[7].items) {
	pfile = tparm[7].items->data;
    }
    if (tparm[8].items) {
	dfile = tparm[8].items->data;
    }

    if (pfile == NULL) {
        snprintf(pbuffer, sizeof(pbuffer), "%s.DB0", pbase);
        pfile = pbuffer;
    }
    if ((dbase_fd = open(pfile, (wflag ? O_RDWR : O_RDONLY) | O_CREAT, 0600))
	< 0) {
	fprintf(stderr, "pt_util: cannot open %s: %s\n", pfile,
		strerror(errno));
	exit(1);
    }
    if (read(dbase_fd, buffer, HDRSIZE) < 0) {
	fprintf(stderr, "pt_util: error reading %s: %s\n", pfile,
		strerror(errno));
	exit(1);
    }

    if (dfile) {
	if ((dfp = fopen(dfile, wflag ? "r" : "w")) == 0) {
	    fprintf(stderr, "pt_util: error opening %s: %s\n", dfile,
		    strerror(errno));
	    exit(1);
	}
    } else
	dfp = (wflag ? stdin : stdout);

    uh = (struct ubik_hdr *)buffer;
    if (ntohl(uh->magic) != UBIK_MAGIC)
	fprintf(stderr, "pt_util: %s: Bad UBIK_MAGIC. Is %x should be %x\n",
		pfile, ntohl(uh->magic), UBIK_MAGIC);
    memcpy(&uv, &uh->version, sizeof(struct ubik_version));

    if (wflag && ntohl(uv.epoch) == 0 && ntohl(uv.counter) == 0) {
	uv.epoch = htonl(2); /* a ubik version of 0 or 1 has special meaning */
	memcpy(&uh->version, &uv, sizeof(struct ubik_version));
	lseek(dbase_fd, 0, SEEK_SET);
	if (write(dbase_fd, buffer, HDRSIZE) < 0) {
	    fprintf(stderr, "pt_util: error writing ubik version to %s: %s\n",
		    pfile, strerror(errno));
	    exit(1);
	}
    }

    /* Now that any writeback is done, swap these */
    uv.epoch = ntohl(uv.epoch);
    uv.counter = ntohl(uv.counter);

    fprintf(stderr, "Ubik Version is: %d.%d\n", uv.epoch, uv.counter);
    if (read(dbase_fd, &prh, sizeof(struct prheader)) < 0) {
	fprintf(stderr, "pt_util: error reading %s: %s\n", pfile,
		strerror(errno));
	exit(1);
    }

    Initdb();
    initialize_PT_error_table();

    if (wflag) {
	struct usr_list *u;
	int seenGroup = 0, id = 0, flags = 0;

	while (fgets(buffer, sizeof(buffer), dfp)) {
	    int oid, cid, quota, uid;
	    char name[PR_MAXNAMELEN], mem[PR_MAXNAMELEN];

	    if (isspace(*buffer)) {
		code = sscanf(buffer, "%s %d", mem, &uid);
		if (code != 2) {
		    fprintf(stderr,
			    "Insuffient data provided for group membership\n");
		    exit(1);
		}

		if (!seenGroup) {
		    fprintf(stderr,
			    "Group member %s listed outside of group\n",
			    mem);
		    exit(1);
		}

		for (u = usr_head; u; u = u->next)
		    if (u->uid && u->uid == uid)
			break;
		if (u) {
		    /* Add user - deferred because it is probably foreign */
		    u->uid = 0;
		    if (FindByID(0, uid))
			code = PRIDEXIST;
		    else {
			if (!code
			    && (flags & (PRGRP | PRQUOTA)) ==
			    (PRGRP | PRQUOTA)) {
			    gentry.ngroups++;
			    code = pr_WriteEntry(0, 0, gpos, &gentry);
			    if (code)
				fprintf(stderr,
					"Error setting group count on %s: %s\n",
					name, afs_error_message(code));
			}
			code = CreateEntry(0, u->name, &uid, 1 /*idflag */ ,
					   1 /*gflag */ ,
					   SYSADMINID /*oid */ ,
					   SYSADMINID /*cid */ );
		    }
		    if (code)
			fprintf(stderr, "Error while creating %s: %s\n",
				u->name, afs_error_message(code));
		    continue;
		}
		/* Add user to group */
		if (id == ANYUSERID || id == AUTHUSERID || uid == ANONYMOUSID) {
		    code = PRPERM;
		} else if ((upos = FindByID(0, uid))
			   && (gpos = FindByID(0, id))) {
		    code = pr_ReadEntry(0, 0, upos, &uentry);
		    if (!code)
			code = pr_ReadEntry(0, 0, gpos, &gentry);
		    if (!code)
			code = AddToEntry(0, &gentry, gpos, uid);
		    if (!code)
			code = AddToEntry(0, &uentry, upos, id);
		} else
		    code = PRNOENT;

		if (code)
		    fprintf(stderr, "Error while adding %s to %s: %s\n", mem,
			    name, afs_error_message(code));
	    } else {
		code = sscanf(buffer, "%s %d/%d %d %d %d", name, &flags, &quota, &id,
			      &oid, &cid);
		if (code != 6) {
		    fprintf(stderr,
			    "Insufficient data provided for user/group\n");
		    exit(1);
		}

		seenGroup = 1;

		if (FindByID(0, id))
		    code = PRIDEXIST;
		else
		    code = CreateEntry(0, name, &id, 1 /*idflag */ ,
				       flags & PRGRP, oid, cid);
		if (code == PRBADNAM) {
		    u = malloc(sizeof(struct usr_list));
		    u->next = usr_head;
		    u->uid = id;
		    strcpy(u->name, name);
		    usr_head = u;
		} else if (code) {
		    fprintf(stderr, "Error while creating %s: %s\n", name,
			    afs_error_message(code));
		} else if ((flags & PRACCESS)
			   || (flags & (PRGRP | PRQUOTA)) ==
			   (PRGRP | PRQUOTA)) {
		    gpos = FindByID(0, id);
		    code = pr_ReadEntry(0, 0, gpos, &gentry);
		    if (!code) {
			gentry.flags = flags;
			gentry.ngroups = quota;
			code = pr_WriteEntry(0, 0, gpos, &gentry);
		    }
		    if (code)
			fprintf(stderr,
				"Error while setting flags on %s: %s\n", name,
				afs_error_message(code));
		}
	    }
	}
	for (u = usr_head; u; u = u->next)
	    if (u->uid)
		fprintf(stderr, "Error while creating %s: %s\n", u->name,
			afs_error_message(PRBADNAM));
    } else {
	for (i = 0; i < HASHSIZE; i++) {
	    upos = nflag ? ntohl(prh.nameHash[i]) : ntohl(prh.idHash[i]);
	    while (upos) {
		long newpos;
		newpos = display_entry(upos);
		if (newpos == upos) {
		    fprintf(stderr, "pt_util: hash error in %s chain %d\n",
			    nflag ? "name":"id", i);
		    exit(1);
		} else
		    upos = newpos;
	    }
	}
	if (flags & DO_GRP)
	    display_groups();
    }

    lseek(dbase_fd, 0, L_SET);	/* rewind to beginning of file */
    if (read(dbase_fd, buffer, HDRSIZE) < 0) {
	fprintf(stderr, "pt_util: error reading %s: %s\n", pfile,
		strerror(errno));
	exit(1);
    }
    uh = (struct ubik_hdr *)buffer;

    uh->version.epoch = ntohl(uh->version.epoch);
    uh->version.counter = ntohl(uh->version.counter);

    if ((uh->version.epoch != uv.epoch)
	|| (uh->version.counter != uv.counter)) {
	fprintf(stderr,
		"pt_util: Ubik Version number changed during execution.\n");
	fprintf(stderr, "Old Version = %d.%d, new version = %d.%d\n",
		uv.epoch, uv.counter, uh->version.epoch, uh->version.counter);
    }
    close(dbase_fd);
    exit(0);
}
Esempio n. 30
0
int
CommandProc(struct cmd_syndesc *as, void *arock)
{
    char name[MAXKTCNAMELEN] = "";
    char instance[MAXKTCNAMELEN] = "";
    char cell[MAXKTCREALMLEN] = "";
    char realm[MAXKTCREALMLEN] = "";
    afs_int32 serverList[MAXSERVERS];
    char *lcell;		/* local cellname */
    int code;
    int i;

    struct ubik_client *conn = 0;
    struct ktc_encryptionKey key;
    struct ktc_encryptionKey mitkey;
    struct ktc_encryptionKey newkey;
    struct ktc_encryptionKey newmitkey;

    struct ktc_token token;

    struct passwd pwent;
    struct passwd *pw = &pwent;

    int insist;			/* insist on good password quality */
    int lexplicit = 0;		/* servers specified explicitly */
    int local;			/* explicit cell is same a local cell */
    int foundPassword = 0;	/*Not yet, anyway */
    int foundNewPassword = 0;	/*Not yet, anyway */
    int foundExplicitCell = 0;	/*Not yet, anyway */
#ifdef DEFAULT_MITV4_STRINGTOKEY
    int dess2k = 1;
#elif DEFAULT_AFS_STRINGTOKEY
    int dess2k = 0;
#else
    int dess2k = -1;
#endif

    /* blow away command line arguments */
    for (i = 1; i < zero_argc; i++)
	memset(zero_argv[i], 0, strlen(zero_argv[i]));
    zero_argc = 0;

    /* first determine quiet flag based on -pipe switch */
    Pipe = (as->parms[aPIPE].items ? 1 : 0);

#if TIMEOUT
    signal(SIGALRM, timedout);
    alarm(30);
#endif

    code = ka_Init(0);
    if (code || !(lcell = ka_LocalCell())) {
#ifndef AFS_FREELANCE_CLIENT
	if (!Pipe)
	    afs_com_err(rn, code, "Can't get local cell name!");
	exit(1);
#endif
    }

    code = rx_Init(0);
    if (code) {
	if (!Pipe)
	    afs_com_err(rn, code, "Failed to initialize Rx");
	exit(1);
    }

    strcpy(instance, "");

    /* Parse our arguments. */

    if (as->parms[aCELL].items) {
	/*
	 * cell name explicitly mentioned; take it in if no other cell name
	 * has already been specified and if the name actually appears.  If
	 * the given cell name differs from our own, we don't do a lookup.
	 */
	foundExplicitCell = 1;
	strncpy(realm, as->parms[aCELL].items->data, sizeof(realm));
    }

    if (as->parms[aSERVERS].items) {
	/* explicit server list */
	int i;
	struct cmd_item *ip;
	char *ap[MAXSERVERS + 2];

	for (ip = as->parms[aSERVERS].items, i = 2; ip; ip = ip->next, i++)
	    ap[i] = ip->data;
	ap[0] = "";
	ap[1] = "-servers";
	code = ubik_ParseClientList(i, ap, serverList);
	if (code) {
	    if (!Pipe)
		afs_com_err(rn, code, "could not parse server list");
	    return code;
	}
	lexplicit = 1;
    }

    if (as->parms[aPRINCIPAL].items) {
	ka_ParseLoginName(as->parms[aPRINCIPAL].items->data, name, instance,
			  cell);
	if (strlen(instance) > 0)
	    if (!Pipe)
		fprintf(stderr,
			"Non-null instance (%s) may cause strange behavior.\n",
			instance);
	if (strlen(cell) > 0) {
	    if (foundExplicitCell) {
		if (!Pipe)
		    fprintf(stderr,
			    "%s: May not specify an explicit cell twice.\n",
			    rn);
		return -1;
	    }
	    foundExplicitCell = 1;
	    strncpy(realm, cell, sizeof(realm));
	}
	pw->pw_name = name;
    } else {
	/* No explicit name provided: use Unix uid. */
#ifdef AFS_NT40_ENV
	userNameLen = 128;
	if (GetUserName(userName, &userNameLen) == 0) {
	    if (!Pipe) {
		fprintf(stderr,
			"Can't figure out your name in local cell %s from your user id.\n",
			lcell);
		fprintf(stderr, "Try providing the user name.\n");
	    }
	    exit(1);
	}
	pw->pw_name = userName;
#else
	pw = getpwuid(getuid());
	if (pw == 0) {
	    if (!Pipe) {
		fprintf(stderr,
			"Can't figure out your name in local cell %s from your user id.\n",
			lcell);
		fprintf(stderr, "Try providing the user name.\n");
	    }
	    exit(1);
	}
#endif
    }

    if (as->parms[aPASSWORD].items) {
	/*
	 * Current argument is the desired password string.  Remember it in
	 * our local buffer, and zero out the argument string - anyone can
	 * see it there with ps!
	 */
	foundPassword = 1;
	strncpy(passwd, as->parms[aPASSWORD].items->data, sizeof(passwd));
	memset(as->parms[aPASSWORD].items->data, 0,
	       strlen(as->parms[aPASSWORD].items->data));
    }

    if (as->parms[aNEWPASSWORD].items) {
	/*
	 * Current argument is the new password string.  Remember it in
	 * our local buffer, and zero out the argument string - anyone can
	 * see it there with ps!
	 */
	foundNewPassword = 1;
	strncpy(npasswd, as->parms[aNEWPASSWORD].items->data,
		sizeof(npasswd));
	memset(as->parms[aNEWPASSWORD].items->data, 0,
	       strlen(as->parms[aNEWPASSWORD].items->data));
    }
#ifdef AFS_FREELANCE_CLIENT
    if (!foundExplicitCell && !lcell) {
	if (!Pipe)
	    afs_com_err(rn, code, "no cell name provided");
	exit(1);
    }
#else
    if (!foundExplicitCell)
	strcpy(realm, lcell);
#endif /* freelance */

    if ((code = ka_CellToRealm(realm, realm, &local))) {
	if (!Pipe)
	    afs_com_err(rn, code, "Can't convert cell to realm");
	exit(1);
    }
    lcstring(cell, realm, sizeof(cell));

    ka_PrintUserID("Changing password for '", pw->pw_name, instance, "'");
    printf(" in cell '%s'.\n", cell);

    /* Get the password if it wasn't provided. */
    if (!foundPassword) {
	if (Pipe)
	    getpipepass(passwd, sizeof(passwd));
	else {
	    code = read_pass(passwd, sizeof(passwd), "Old password: "******"reading password");
		exit(1);
	    }
	}
    }
    ka_StringToKey(passwd, realm, &key);
    des_string_to_key(passwd, ktc_to_cblockptr(&mitkey));
    give_to_child(passwd);

    /* Get new password if it wasn't provided. */
    insist = 0;
    if (!foundNewPassword) {
	if (Pipe)
	    getpipepass(npasswd, sizeof(npasswd));
	else {
	    do {
		code =
		    read_pass(npasswd, sizeof(npasswd),
			      "New password (RETURN to abort): ", 0);
		if (code || (strlen(npasswd) == 0)) {
		    if (code)
			code = KAREADPW;
		    goto no_change;

		}
	    } while (password_bad(npasswd));

	    code =
		read_pass(verify, sizeof(verify), "Retype new password: "******"Mismatch - ");
		goto no_change;
	    }
	    memset(verify, 0, sizeof(verify));
	}
    }
    if ((code = password_bad(npasswd))) {	/* assmt here! */
	goto no_change_no_msg;
    }
#if TRUNCATEPASSWORD
    if (strlen(npasswd) > 8) {
	npasswd[8] = 0;
	fprintf(stderr,
		"%s: password too long, only the first 8 chars will be used.\n",
		rn);
    } else
	npasswd[8] = 0;		/* in case the password was exactly 8 chars long */
#endif
    ka_StringToKey(npasswd, realm, &newkey);
    des_string_to_key(npasswd, ktc_to_cblockptr(&newmitkey));
    memset(npasswd, 0, sizeof(npasswd));

    if (lexplicit)
	ka_ExplicitCell(realm, serverList);

    /* Get an connection to kaserver's admin service in desired cell.  Set the
     * lifetime above the time uncertainty so that badly skewed clocks are
     * reported when the ticket is decrypted.  Then give us 10 seconds to
     * actually get our work done if the clocks are skewed by only 14:59.
     * NOTE: Kerberos lifetime encoding will round this up to next 5 minute
     * interval, namely 20 minutes. */

#define ADMIN_LIFETIME (KTC_TIME_UNCERTAINTY+1)

    code =
	ka_GetAdminToken(pw->pw_name, instance, realm, &key, ADMIN_LIFETIME,
			 &token, /*!new */ 0);
    if (code == KABADREQUEST) {
	code =
	    ka_GetAdminToken(pw->pw_name, instance, realm, &mitkey,
			     ADMIN_LIFETIME, &token, /*!new */ 0);
	if ((code == KABADREQUEST) && (strlen(passwd) > 8)) {
	    /* try with only the first 8 characters incase they set their password
	     * with an old style passwd program. */
	    char pass8[9];
	    strncpy(pass8, passwd, 8);
	    pass8[8] = 0;
	    ka_StringToKey(pass8, realm, &key);
	    memset(pass8, 0, sizeof(pass8));
	    memset(passwd, 0, sizeof(passwd));
	    code = ka_GetAdminToken(pw->pw_name, instance, realm, &key, ADMIN_LIFETIME, &token,	/*!new */
				    0);
#ifdef notdef
	    /* the folks in testing really *hate* this message */
	    if (code == 0) {
		fprintf(stderr,
			"Warning: only the first 8 characters of your old password were significant.\n");
	    }
#endif
	    if (code == 0) {
		if (dess2k == -1)
		    dess2k = 0;
	    }
	} else {
	    if (dess2k == -1)
		dess2k = 1;
	}
    } else {
	if (dess2k == -1)
	    dess2k = 0;
    }

    memset(&mitkey, 0, sizeof(mitkey));
    memset(&key, 0, sizeof(key));
    if (code == KAUBIKCALL)
	afs_com_err(rn, code, "(Authentication Server unavailable, try later)");
    else if (code) {
	if (code == KABADREQUEST)
	    fprintf(stderr, "%s: Incorrect old password.\n", rn);
	else
	    afs_com_err(rn, code, "so couldn't change password");
    } else {
	code =
	    ka_AuthServerConn(realm, KA_MAINTENANCE_SERVICE, &token, &conn);
	if (code)
	    afs_com_err(rn, code, "contacting Admin Server");
	else {
	    if (dess2k == 1)
		code =
		    ka_ChangePassword(pw->pw_name, instance, conn, 0,
				      &newmitkey);
	    else
		code =
		    ka_ChangePassword(pw->pw_name, instance, conn, 0,
				      &newkey);
	    memset(&newkey, 0, sizeof(newkey));
	    memset(&newmitkey, 0, sizeof(newmitkey));
	    if (code) {
		char *reason;
		reason = (char *)afs_error_message(code);
		fprintf(stderr, "%s: Password was not changed because %s\n",
			rn, reason);
	    } else
		printf("Password changed.\n\n");
	}
    }
    memset(&newkey, 0, sizeof(newkey));
    memset(&newmitkey, 0, sizeof(newmitkey));

    /* Might need to close down the ubik_Client connection */
    if (conn) {
	ubik_ClientDestroy(conn);
	conn = 0;
    }
    rx_Finalize();
    terminate_child();
    exit(code);

  no_change:			/* yuck, yuck, yuck */
    if (code)
	afs_com_err(rn, code, "getting new password");
  no_change_no_msg:
    memset(&key, 0, sizeof(key));
    memset(npasswd, 0, sizeof(npasswd));
    printf("Password for '%s' in cell '%s' unchanged.\n\n", pw->pw_name,
	   cell);
    terminate_child();
    exit(code ? code : 1);
}