/**
 * Setup the counters using the current config
 */
static void proc_perf_setup(void)
{
	int i;
	proc_perf_l2_control_t l2control;

	proc_perf_counter_control[0] = 0;
	proc_perf_counter_control[1] = 0;
	proc_perf_l2counter_control[0] = 0;
	proc_perf_l2counter_control[1] = 0;
	proc_perf_l2counter_control[2] = 0;
	proc_perf_l2counter_control[3] = 0;

	/* Cleanup junk on end of param strings */
	clean_string(counter0, sizeof(counter0));
	clean_string(counter1, sizeof(counter1));
	clean_string(l2counter0, sizeof(l2counter0));
	clean_string(l2counter1, sizeof(l2counter1));
	clean_string(l2counter2, sizeof(l2counter2));
	clean_string(l2counter3, sizeof(l2counter3));

	/* Set the core counters to match the string parameters */
	for (i = 0; i < PROC_PERF_CORE_MAX; i++) {
		if (proc_perf_label[i]) {
			if (strcmp(proc_perf_label[i], counter0) == 0)
				proc_perf_counter_control[0] = i;
			if (strcmp(proc_perf_label[i], counter1) == 0)
				proc_perf_counter_control[1] = i;
		}
	}

	/* Set the L2 counters to match the string parameters */
	for (i = 0; i < PROC_PERF_L2_MAX; i++) {
		if (proc_perf_l2label[i]) {
			if (strcmp(proc_perf_l2label[i], l2counter0) == 0)
				proc_perf_l2counter_control[0] = i;
			if (strcmp(proc_perf_l2label[i], l2counter1) == 0)
				proc_perf_l2counter_control[1] = i;
			if (strcmp(proc_perf_l2label[i], l2counter2) == 0)
				proc_perf_l2counter_control[2] = i;
			if (strcmp(proc_perf_l2label[i], l2counter3) == 0)
				proc_perf_l2counter_control[3] = i;
		}
	}

	/* Update strings to match final config */
	strcpy(counter0, proc_perf_label[proc_perf_counter_control[0]]);
	strcpy(counter1, proc_perf_label[proc_perf_counter_control[1]]);
	strcpy(l2counter0, proc_perf_l2label[proc_perf_l2counter_control[0]]);
	strcpy(l2counter1, proc_perf_l2label[proc_perf_l2counter_control[1]]);
	strcpy(l2counter2, proc_perf_l2label[proc_perf_l2counter_control[2]]);
	strcpy(l2counter3, proc_perf_l2label[proc_perf_l2counter_control[3]]);

	on_each_cpu(proc_perf_setup_counters, NULL, 1, 1);

	l2control.u64 = 0;
	l2control.s.cnt3ena = 1;
	l2control.s.cnt3clr = 1;
	l2control.s.cnt3sel = proc_perf_l2counter_control[3];
	l2control.s.cnt2ena = 1;
	l2control.s.cnt2clr = 1;
	l2control.s.cnt2sel = proc_perf_l2counter_control[2];
	l2control.s.cnt1ena = 1;
	l2control.s.cnt1clr = 1;
	l2control.s.cnt1sel = proc_perf_l2counter_control[1];
	l2control.s.cnt0ena = 1;
	l2control.s.cnt0clr = 1;
	l2control.s.cnt0sel = proc_perf_l2counter_control[0];

	octeon_write_csr(OCTEON_L2C_PFCTL, l2control.u64);
	octeon_write_csr(OCTEON_L2C_PFC0, 0);
	octeon_write_csr(OCTEON_L2C_PFC1, 0);
	octeon_write_csr(OCTEON_L2C_PFC2, 0);
	octeon_write_csr(OCTEON_L2C_PFC3, 0);
}
Exemple #2
0
void pcmfin(int nth,int isubred)
{
        unsigned int   substrismin;
        int             newatom, i, ibondcount, ibonded, ibondorder,
                        icoord, imetcount, ioffset, ispin, iprint,
                        isubmap[MAXSS], j, numbonds, niatom;
        int            newat, newtype, ifile, isMetal, biotype, itype;
        long int       mask;
        char           ianame[3];
        float          ddcount, xtmp, ytmp, ztmp;
        FILE           *pcminfile;

        imetcount = 0;
        isMetal = FALSE;
        ddcount = 0;
        substrismin = False;
        fxtor.nfxtor = 0;
        pcmfile.nocaps = False;
        numbonds = 0;
        ibondcount = 0;
	newatom = 0;
	newtype = 0;

        for (i = 0; i < MAXSS; i++) 
        {
                isubmap[i] = 0;
        }

       ioffset = 0;

        pcminfile = fopen_path(Openbox.path,Openbox.fname,"r");
         
        if (pcminfile == NULL)
        {
                message_alert("Error Opening PCM file","PCM Setup");
                fprintf(pcmoutfile,"PCMFIN error opening file %d %s\n",nth,Openbox.fname);
                return;
        }
        
        if (default_intype != MMX)
            read_atomtypes(default_intype);

        ifile = 0;
        if (nth != 1)
        {
                while ( FetchRecord(pcminfile,pcmfile.string) )
                {
                        if (strncasecmp(pcmfile.string,"{PCM",4) == 0)
                        {
                                ifile++;
                                if (ifile == nth)
                                        break;
                        }
                }
        }else
        {
                FetchRecord(pcminfile,pcmfile.string);
        }

/*  finished scaning to starting structure  now read file */
        if (isubred == 0)
        {
                sscanf(pcmfile.string, "{PCM %60c", Struct_Title);
                clean_string(Struct_Title);
        } else
        {
                if (natom < 1 )
                {
                        sscanf(pcmfile.string, "{PCM %60c", Struct_Title);
                        clean_string(Struct_Title);
                }   
        }
L_30:
        FetchRecord(pcminfile,pcmfile.string);
        *(pcmfile.string + strlen(pcmfile.string) ) = '\0';
        if (feof(pcminfile))
                goto L_170;
        pcmfile.head = 1;
        NL;
L_40:
        if (strcmp(pcmfile.token, "NA") == 0) 
        {
                gettoken();
                if (pcmfile.head == 1000)
                        goto L_30;
                niatom = atoi(pcmfile.token);
                if (niatom + ioffset > MAXATOM) 
                {
                        natom = ioffset;
                        fclose(pcminfile);
                        message_alert(" Maximum number of atoms exceeded in PCMFIN","PCM Setup");
                        fprintf(pcmoutfile," unable to continue reading, more than Max atoms %d\n",MAXATOM);
                        return;
                }
                niatom += ioffset;
                NL;
                goto L_30;
        } else if (strcmp(pcmfile.token,"ATOMTYPES") == 0)
        {
            gettoken();
            if (pcmfile.head == 1000)
               goto L_30;
            default_intype = atoi(pcmfile.token);
            read_atomtypes(default_intype);
            NL;
            goto L_30;
        }  else if (strcmp(pcmfile.token, "NT") == 0)  /* This is for Amino Acids */
        {
                NL;
                i = atoi(pcmfile.token);                /* i is atom number of N terminus */
                mask = 1L << NTERM;                         /* use bit 0 of substr 1 for N terminus*/
                atom[i+ioffset].flags |= mask;

                NL;
                if (strcmp(pcmfile.token, "CT") == 0)
                {
                        NL;
                        i = atoi(pcmfile.token);        /* i is atom number of C terminus  */
                        mask = 1L << CNTERM;                /* use bit 1 of substr 1 for C terminus */
                        atom[i+ioffset].flags |= mask;
                }
        }  else if (strcmp(pcmfile.token, "5PRIME") == 0)  /* This is for Nucleic Acids */
        {
                NL;
                i = atoi(pcmfile.token);                    /* i is atom number of 5prime terminus */
                mask = 1L << P5;                        
                atom[i+ioffset].flags |= mask;
        }else if (strcmp(pcmfile.token, "3PRIME") == 0)  /* This is for Nucleic Acids */
        {
                NL;
                i = atoi(pcmfile.token);        /* i is atom number of C terminus  */
                mask = 1L << P3;                /* use bit 1 of substr 1 for C terminus */
                atom[i+ioffset].flags |= mask;
        }  else if (strcmp(pcmfile.token, "FG") == 0)  /* This is for functional groups */
        {
                NL;
                i = atoi(pcmfile.token);                /* i is atom number of connect point */
                mask = 1L << DUMMY;                         /* use bit 0 of substr 1 for connect*/
                atom[i+ioffset].flags |= mask;

        }  else if (strcmp(pcmfile.token, "OT") == 0)   /*  This is for Sugars  */
        {
                NL;
                i = atoi(pcmfile.token);                /* i is atom number of O terminus */
                mask = 1L << NTERM;                                 /* use bit 0 of substr 1 for O terminus*/
                atom[i+ioffset].flags |= mask;

                NL;
                if (strcmp(pcmfile.token, "CT") == 0)
                {
                        NL;
                        i = atoi(pcmfile.token);        /* i is atom number of H terminus  */
                        mask = 1L << CNTERM;                         /* use bit 1 of substr 1 for H terminus */
                        atom[i+ioffset].flags |= mask;
                }

                NL;
                if (strcmp(pcmfile.token, "OTWO") == 0)
                {
                        NL;
                        i = atoi(pcmfile.token);        /* i is atom number of H terminus  */
                        oh2 = i+ioffset;
                }

                NL;
                if (strcmp(pcmfile.token, "OTHR") == 0)
                {
                        NL;
                        i = atoi(pcmfile.token);        /* i is atom number of H terminus  */
                        oh3 = i+ioffset;
                }

                NL;
                if (strcmp(pcmfile.token, "OSIX") == 0)
                {
                        NL;
                        i = atoi(pcmfile.token);        /* i is atom number of H terminus  */
                        oh6 = i+ioffset;
                }
        } else if (strcmp(pcmfile.token,"START") == 0) /* flag for polybuild */
        {
                NL;
                i = atoi(pcmfile.token);
                mask = 1L << DUMMY;
                atom[i+ioffset].flags |= mask;
                NL;   // END
                NL;
                i = atoi(pcmfile.token);
                mask = 1L << DUMMY;
                atom[i+ioffset].flags |= mask;
        } else if  (strcmp(pcmfile.token,"NMOL") == 0)
        {
            NL;
            NL;
            NL;
            NL;
            NL;
            NL;
            NL;
            goto L_30;
        } else if (strcmp(pcmfile.token, "OPT") == 0)
        {
            NL;  // para
            NL;
            optimize_data.param_avail = atoi(pcmfile.token);                   
            NL; // conv
            NL;
            optimize_data.converge = atoi(pcmfile.token);                   
            NL;  // ie
            NL;
            optimize_data.initial_energy = atof(pcmfile.token);                   
            NL;  // fe
            NL;
            optimize_data.final_energy = atof(pcmfile.token);                   
            NL;   // iH
            NL;
            optimize_data.initial_heat = atof(pcmfile.token);
            NL; // fH             
            NL;
            optimize_data.final_heat = atof(pcmfile.token);                   
            goto L_30;
        }  else if (strcmp(pcmfile.token, "SS") == 0)
        {
                goto L_30;
        }  else if (strcmp(pcmfile.token, "AT") == 0) 
        {
                NL;
                newat = atoi(pcmfile.token);   // atom serial number
                if (newat + ioffset > MAXATOM) 
                {
                        message_alert(" Maximum number of atoms exceeded in PCMFIN at atom read","PCM Setup");
                        fprintf(pcmoutfile,"atom read %d %d %d\n",newat,ioffset,natom);
                        natom = ioffset + newat - 1;
                        fclose(pcminfile);
                        exit(0);
                }
                newat += ioffset;
                NL;
                if (isdigit(*pcmfile.token)) 
                {
                        newtype = atoi(pcmfile.token);
                }       else   // character string for metal atom
                {
                        strcpy(ianame,pcmfile.token);
                        isMetal = TRUE;
                        i = strlen(ianame);
                        if ( i == 2) 
                            ianame[1] = tolower(ianame[1]);
                }
                NL;
                xtmp = atof(pcmfile.token);
                NL;
                ytmp = (atof(pcmfile.token));
                NL;
                ztmp = atof(pcmfile.token);
                NL;
                if (isMetal == FALSE)
                {
                    itype = newtype;
                    get_atomname(newtype,ianame);
                    if (default_intype == MM3)
                       itype = mm3_mmxtype(newtype);
                    else if (default_intype == MMFF94)
                       itype = mmff_mmxtype(newtype);
                       
                    newatom = make_atom(newtype, xtmp, ytmp, ztmp,ianame);
                    if (default_intype == MM3)
                        set_atomtype(newatom, itype,newtype,0,0,0);
                    else if (default_intype == MMFF94)
                        set_atomtype(newatom, itype,0,newtype,0,0);
                }else if (isMetal == TRUE)
                {
                    newatom = make_atom(0, xtmp, ytmp, ztmp,ianame);
                    isMetal = FALSE;
                }

L_90:
                if (strcmp(pcmfile.token, "B") == 0) 
                {
                        /* Reading bonds now */
                        NL;
                        j = 0;
        L_100:
                        j += 1;
                        if (pcmfile.state == NUMERIC) 
                        {
                                ibonded = atoi(pcmfile.token);
                                ibonded += ioffset;
                        } else 
                        {
                                goto L_90;
                        }
                        NL;
                        if (pcmfile.state == NUMERIC) 
                        {
                                ibondorder = atoi(pcmfile.token);
                        } else 
                        {
                                fprintf(stdout, "missing a bondorder, assuming 1\n");
                                goto L_40;
                        }
                        if (newatom < ibonded)
                                make_bond(newatom, ibonded, ibondorder);
                        if (ibondorder == 9)
                        {
                                atom[newatom].flags |= (1L << METCOORD_MASK);
                                atom[ibonded].flags |= (1L << METCOORD_MASK);
                        }       
                        NL;
                        goto L_100;
                }else if ( strcmp(pcmfile.token, "P")== 0)
                {
                        atom[newatom].flags |= (1L << PI_MASK);
                        NL;
                        goto L_90;
                }else if (strcmp(pcmfile.token, "D") == 0)   // biomolecule marking
                {
                        NL;
                        biotype = atoi(pcmfile.token);
                        atom[newatom].biotype =  biotype;                       
                        NL;
                        goto L_90;
                }else if (strcmp(pcmfile.token,"M")==0)
                {
                        NL;
                        icoord = atoi(pcmfile.token);
                        if (icoord == 0)
                        {
                                atom[newatom].flags |= (1L << SATMET_MASK);
                        } else if (icoord == 2)
                        {
                                atom[newatom].flags |= (1L << GT18e_MASK);
                        } else{
                                atom[newatom].flags |= (1L << GT18e_MASK);
                                atom[newatom].flags |= (1L << SATMET_MASK);
                        }
                        NL;
                        if (pcmfile.state != 1)
                                goto L_90;
                        ispin = atoi(pcmfile.token);
                        if (ispin == 0)
                        {
                                atom[newatom].flags |= (1L << LOWSPIN_MASK);
                        } else if (ispin == 1) 
                        {
                                atom[newatom].flags |= (1L << SQPLAN_MASK);
                        } else 
                        {
                                atom[newatom].flags |= (1L << LOWSPIN_MASK);
                                atom[newatom].flags |= (1L << SQPLAN_MASK);
                        }
                        NL;
                        goto L_90;
                }else if (strcmp(pcmfile.token,"S")== 0)
                {
                        NL;
                        if (pcmfile.state == NUMERIC)
                        {
                                j = atoi(pcmfile.token);
                                mask = (1L << j);
                                NL;
                                goto L_90;
                        } else
                        {
                                goto L_90;
                        }
                }else if (strcmp(pcmfile.token,"H")== 0)
                {
                        atom[newatom].flags |= (1L << HBOND_MASK);
                        NL;
                        goto L_90;
                }else if (strcmp(pcmfile.token,"C")==0)
                {
                        NL;
                        atom[newatom].charge = atof(pcmfile.token);
                        NL;
                        goto L_90;
                } else if (strcmp(pcmfile.token,"ML") == 0)
                {
                    NL;
                    j = atoi(pcmfile.token);
                    atom[newatom].molecule = j;
                    goto L_90;
                }else if (strcmp(pcmfile.token,"R")== 0)
                {
                        NL;
                        atom[newatom].radius = atof(pcmfile.token);
                        NL;
                        goto L_90;
                }               
        } else if (strncasecmp(pcmfile.token, "}",1) == 0) 
        {
                goto L_170;             /* end of structure */
        }  else if (strcmp(pcmfile.token, "FL") == 0) 
        {
                NL;
L_120:          if (strcmp(pcmfile.token, "PRINT") == 0) 
                {
                        iprint = 1;
                        NL;
                        if (pcmfile.state == ALPHABETIC)
                                goto L_120;
                        iprint = atoi(pcmfile.token);
                        NL;
                        goto L_120;
                } else if (strcmp(pcmfile.token, "DIELC") == 0) 
                {
                        NL;
                        if (pcmfile.state != 1)
                                goto L_120;
//                        units.dielec = atof(pcmfile.token);
                        NL;
                        goto L_120;
                } else if (strcmp(pcmfile.token, "UV") == 0) 
                {
                        NL;             
                        if (pcmfile.state != 1)
                                goto L_120;
                        pistuf.iuv = atoi(pcmfile.token);
                        NL;
                        goto L_120;
                } else if (strcmp(pcmfile.token, "PIPR") == 0) 
                {
                        NL;             
                        if (pcmfile.state != 1)
                                goto L_120;
                        pistuf.jprint = atoi(pcmfile.token);
                        NL;
                        goto L_120;
                } else if (strcmp(pcmfile.token, "PIPL") == 0) 
                {
                        NL;             
                        if (pcmfile.state != 1)
                                goto L_120;
                        pistuf.nplane = atoi(pcmfile.token);
                        NL;
                        goto L_120;
                } else if (strcmp(pcmfile.token, "EINT") == 0) 
                {
                        NL;             
                        if (pcmfile.state != 1)
                                goto L_120;
                        minim_values.ndc = atoi(pcmfile.token);
                        NL;
                        goto L_120;
                }
        }  else if (strcmp(pcmfile.token, "CO") == 0) 
        {
        } else if (strcmp(pcmfile.token, "FBND") == 0)
        {
                NL;
                ts_bondorder.fbnd[0] = atof(pcmfile.token);
                NL;
                ts_bondorder.fbnd[1] = atof(pcmfile.token);
                NL;
                ts_bondorder.fbnd[2] = atof(pcmfile.token);
                NL;
                ts_bondorder.fbnd[3] = atof(pcmfile.token);
                NL;
                ts_bondorder.fbnd[4] = atof(pcmfile.token);
                NL;
                ts_bondorder.fbnd[5] = atof(pcmfile.token);
                NL;
                ts_bondorder.fbnd[6] = atof(pcmfile.token);
                NL;
                ts_bondorder.fbnd[7] = atof(pcmfile.token);
                NL;
                ts_bondorder.fbnd[8] = atof(pcmfile.token);
                NL;
                ts_bondorder.fbnd[9] = atof(pcmfile.token);
                NL;
                ts_bondorder.fbnd[10] = atof(pcmfile.token);
                NL;
                ts_bondorder.fbnd[11] = atof(pcmfile.token);
                NL;
                ts_bondorder.fbnd[12] = atof(pcmfile.token);
                NL;
                ts_bondorder.fbnd[13] = atof(pcmfile.token);
                NL;
                ts_bondorder.fbnd[14] = atof(pcmfile.token);
        }  else if (strcmp(pcmfile.token, "FIX") == 0) 
        {
                NL;
                if (strcmp(pcmfile.token, "DIS") == 0) 
                {
                        NL;
                        fixdis.ifxstr[fixdis.nfxstr][0] = atoi(pcmfile.token);
                        NL;
                        fixdis.ifxstr[fixdis.nfxstr][1] = atoi(pcmfile.token);
                        NL;
L_1223:                 if (strcmp(pcmfile.token, "R") == 0) 
                        {
                                NL;
                                fixdis.fxstrd[fixdis.nfxstr] = atof(pcmfile.token);
                                NL;
                                goto L_1223;
                        } else if (strcmp(pcmfile.token, "K") == 0) 
                        {
                                NL;
                                fixdis.fxstrc[fixdis.nfxstr] = atof(pcmfile.token);
                                fixdis.nfxstr +=1;
                                NL;
                                goto L_1223;
                        }
                }
        }  else if (strcmp(pcmfile.token, "DD") == 0) 
        {
                if (isubred == 1)
                        goto L_30;

                NL;
                
                if (pcmfile.state == NUMERIC)
                {
                    fxtor.iatom[fxtor.nfxtor][0] = atoi(pcmfile.token);
                    NL;
                    fxtor.iatom[fxtor.nfxtor][1] = atoi(pcmfile.token);
                    NL;
                    fxtor.iatom[fxtor.nfxtor][2] = atoi(pcmfile.token);
                    NL;
                    fxtor.iatom[fxtor.nfxtor][3] = atoi(pcmfile.token);
                    NL;
L_150:              if (strcmp(pcmfile.token, "FROM") == 0)
                    {
                       NL;
                       fxtor.start_ang[fxtor.nfxtor] = atoi(pcmfile.token);
                       fxtor.curr_ang[fxtor.nfxtor] = fxtor.start_ang[fxtor.nfxtor];
                       NL;
                       goto L_150;
                    } else if (strcmp(pcmfile.token, "TO") == 0)
                    {
                       NL;
                       fxtor.final_ang[fxtor.nfxtor] = atoi(pcmfile.token);
                       NL;
                       goto L_150;
                    } else if (strcmp(pcmfile.token, "BY") == 0)
                    {
                       NL;
                       fxtor.step[fxtor.nfxtor] = atoi(pcmfile.token);
                       fxtor.nfxtor++;
                       NL;
                       goto L_150;                       
                    }
                }
        } 
        goto L_30;
L_170:
        fclose(pcminfile);
        for (i=1; i <= natom; i++)
        {
                if (atom[i].mmx_type == 5)
                {
                        flags.noh = True;
                        break;
                }
        }
        if (default_intype != MMX)
           read_atomtypes(MMX);
        return;
} 
int
main(int argc, char *argv[])
{
	int ch, ret, mode = MODE_LOGIN;
	FILE *f = NULL;
	char *username, *password = NULL;
	char response[1024];

	setpriority(PRIO_PROCESS, 0, 0);
	openlog(NULL, LOG_ODELAY, LOG_AUTH);

	while ((ch = getopt(argc, argv, "dv:s:")) != -1) {
		switch (ch) {
		case 'd':
			f = stdout;
			break;
		case 'v':
			break;
		case 's':
			if (!strcmp(optarg, "login"))
				mode = MODE_LOGIN;
			else if (!strcmp(optarg, "response"))
				mode = MODE_RESPONSE;
			else if (!strcmp(optarg, "challenge"))
				mode = MODE_CHALLENGE;
			else {
				syslog(LOG_ERR, "%s: invalid service", optarg);
				exit(EXIT_FAILURE);
			}
			break;
		default:
			syslog(LOG_ERR, "usage error1");
			exit(EXIT_FAILURE);
		}
	}
	argc -= optind;
	argv += optind;
	if (argc != 2 && argc != 1) {
		syslog(LOG_ERR, "usage error2");
		exit(EXIT_FAILURE);
	}
	username = argv[0];
	/* passed by sshd(8) for non-existing users */
	if (!strcmp(username, "NOUSER"))
		exit(EXIT_FAILURE);
	if (!clean_string(username)) {
		syslog(LOG_ERR, "clean_string username");
		exit(EXIT_FAILURE);
	}

	if (f == NULL && (f = fdopen(3, "r+")) == NULL) {
		syslog(LOG_ERR, "user %s: fdopen: %m", username);
		exit(EXIT_FAILURE);
	}

	switch (mode) {
		case MODE_LOGIN:
			if ((password = getpass("Password:"******"user %s: getpass: %m",
				    username);
				exit(EXIT_FAILURE);
			}
			break;
		case MODE_CHALLENGE:
			/* see login.conf(5) section CHALLENGES */
			fprintf(f, "%s\n", BI_SILENT);
			exit(EXIT_SUCCESS);
			break;
		case MODE_RESPONSE: {
			/* see login.conf(5) section RESPONSES */
			/* this happens e.g. when called from sshd(8) */
			int count;
			mode = 0;
			count = -1;
			while (++count < sizeof(response) &&
			    read(3, &response[count], (size_t)1) ==
			    (ssize_t)1) {
				if (response[count] == '\0' && ++mode == 2)
					break;
				if (response[count] == '\0' && mode == 1) {
					password = response + count + 1;
				}
			}
			if (mode < 2) {
				syslog(LOG_ERR, "user %s: protocol error "
				    "on back channel", username);
				exit(EXIT_FAILURE);
			}
			break;
		}
	}

	ret = yubikey_login(username, password);
	memset(password, 0, strlen(password));
	if (ret == AUTH_OK) {
		syslog(LOG_INFO, "user %s: authorize", username);
		fprintf(f, "%s\n", BI_AUTH);
	} else {
		syslog(LOG_INFO, "user %s: reject", username);
		fprintf(f, "%s\n", BI_REJECT);
	}
	closelog();
	return (EXIT_SUCCESS);
}
Exemple #4
0
/** \brief Nutzer mit Name, (ggf. Kürzel) und Passwort in die DB einfügen
 *
 * \param pers person*  Personen-Struktur
 * \return void
 * Eine Person in die DB einfügen, falls diese noch nicht existiert.
 * Das Passwort wird mithilfe von crypt() verschlüsselt
 */
void insert_user(person * pers){
	MYSQL *my=NULL;
	char * query=NULL;

	if(pers == NULL){
		print_exit_failure("Programm falsch.\n Wörk!");
	}

	if(email_exists(pers->email)){
		print_exit_failure("Benutzer Existiert schon!");
	}

	my=mysql_init(NULL);
	if(my == NULL){
		print_exit_failure("MYSQL init failure\n Wörk!");
	}

	if(mysql_real_connect(my, "localhost", SQL_ALTERNATE_USER, SQL_ALTERNATE_PASS, SQL_BASE, 0, NULL, 0) == NULL){
		print_exit_failure("MYSQL-connection error!");
	}

	char * salt=NULL;
	salt_generate(&salt);

    //Verhindern, dass ein bereits vorhandenes Salt zweimal verwendet wird (falls zwei Nutzer identische Passwörter wählen)
	while(salt_exists(&salt)){
		salt_generate(&salt);
	}
	char * arg=NULL;
	asprintf(&arg, "$6$%s$", salt);

	char * encr=crypt(pers->password, arg);
	char * store_pw=NULL;
	asprintf(&store_pw, "%s%s", salt, encr+strlen(arg));
	free(arg);
	free(pers->password);

	//pers->password=encr+strlen(arg);

	clean_string(pers->first_name);
	clean_string(pers->email);
	clean_string(pers->name);


	//Ist es eine Lehrer oder ein Schüler?
	if(!pers->isTeacher){
		if(asprintf(&query, "INSERT INTO Benutzer (vorname, name, email, passwort, kurse) \
					VALUES('%s', '%s', '%s', '%s', 'n/a')",
					pers->first_name, pers->name, pers->email, store_pw) == -1)
		{
			print_exit_failure("Es konnte kein Speicher angefordert werden (insert_user)");
		}
	}else{
		clean_string(pers->acronym);
		if(asprintf(&query, "INSERT INTO Benutzer (vorname, name, email, passwort, kurse, kuerzel) \
					VALUES('%s', '%s', '%s', '%s', 'n/a', '%s')",
					pers->first_name, pers->name, pers->email, store_pw, pers->acronym) == -1)
		{
			print_exit_failure("Es konnte kein Speicher angefordert werden (insert_user)");
		}
	}
	#ifdef DEBUG
	fprintf(stderr, "\nInsert dat:\n%s\n", query);
	#endif // DEBUG
	if(mysql_query(my, query)){
		#ifdef DEBUG
		fprintf(stderr, "sql_query:\n%s\nfailed\n", query);
		#endif // DEBUG
		print_exit_failure("mysql_query failed (insert)");
	}
	free(query);
	mysql_close(my);
}
Exemple #5
0
/* extract_link_data -- given a label, parse the link data and return */
link_data * extract_link_data(char *label, scratch_pad *scratch) {
	char *temp;
	link_data *d;
	node *ref = scratch->links;
	bool debug = 0;

	if (debug)
		fprintf(stderr, "try to extract link for '%s'\n",label);
	
	if ((label == NULL) || (strlen(label) == 0))
		return NULL;
	
	temp = clean_string(label);
	
	/* look for label string as is */
	while (ref != NULL) {
		if (ref->key == KEY_COUNTER) {
			ref = ref->next;
			
			continue;
		}
		if (strcmp(ref->link_data->label, temp) == 0) {
			if (debug)
				fprintf(stderr,"a:matched %s to %s\n",ref->link_data->label, label);
			/* matched */
			d = ref->link_data;
			d = mk_link_data(d->label, d->source, d->title, d->attr);
			free(temp);
			return d;
		} else {
			if (debug)
				fprintf(stderr,"a:did not match %s to %s\n",ref->link_data->label, label);
		}
		ref = ref->next;
	}
	free(temp);
	
	/* No match.  Check for label()version */
	
	if (scratch->extensions & EXT_COMPATIBILITY) {
		/* not in compat mode */
		return NULL;
	}
	temp = label_from_string(label);
	
	ref = scratch->links;
	
	while (ref != NULL) {
		if (ref->key == KEY_COUNTER) {
			ref = ref->next;
			
			continue;
		}
		if (strcmp(ref->link_data->label, temp) == 0) {
			if (debug)
				fprintf(stderr,"b:matched %s to %s\n",ref->link_data->label, label);
			/* matched */
			d = ref->link_data;
			d = mk_link_data(d->label, d->source, d->title, d->attr);
			free(temp);
			return d;
		} else {
			if (debug)
				fprintf(stderr,"b:did not match %s to %s\n",ref->link_data->label, label);
		}
		ref = ref->next;
	}
	free(temp);

	if (debug)
		fprintf(stderr, "finish extract\n");
	return NULL;
}
Exemple #6
0
/* note_number_for_label -- given a label to match, determine number to be used*/
int note_number_for_label(char *text, scratch_pad *scratch) {
	node *n = NULL;
	char *clean;
	char *label;
#ifdef DEBUG_ON
	fprintf(stderr, "find note number for: %s\n",text);
#endif

	if ((text == NULL) || (strlen(text) == 0))
		return 0;	/* Nothing to find */
	
	clean = clean_string(text);
	label = label_from_string(clean);
	
	/* have we used this note already? */
	
	/* look for label string as is */
	n = node_matching_label(clean, scratch->used_notes);
	
	/* if not, look in reserve queue */
	if (n == NULL) {
		n = node_matching_label(clean, scratch->notes);
		
		if (n != NULL) {
			/* move to used queue */
			move_note_to_used(n, scratch);
#ifdef DEBUG_ON
	fprintf(stderr, "note has not already been used for: %s\n",text);
#endif
		}
	} else {
#ifdef DEBUG_ON
	fprintf(stderr, "note has already been used for: %s\n",text);
#endif
	}
	
	/* Check label version */
	if (n == NULL)
		n = node_matching_label(label, scratch->used_notes);
	
	if (n == NULL) {
		n = node_matching_label(label, scratch->notes);
		
		if (n != NULL) {
			/* move to used queue */
			move_note_to_used(n, scratch);
#ifdef DEBUG_ON
	fprintf(stderr, "note has not already been used for: %s\n",label);
#endif
		}
	} else {
#ifdef DEBUG_ON
	fprintf(stderr, "note has already been used for: %s\n",label);
#endif

	}
	
	/* CAN recursively drill down to start counter at 0 and ++ */
	/* if found, move to used queue and return the number  */
	
	free(label);
	free(clean);
	if (n != NULL) {
#ifdef DEBUG_ON
	fprintf(stderr, "note number is: %d\n",count_node_from_end(n));
#endif
		return count_node_from_end(n);
	}
	else 
		return 0;
}
Exemple #7
0
int main(int argc, char *argv[])
{
	int starting_line = 1;	/* line to start editing at */
	char command[MAXPATHLEN + 50];	/* emacs command buffer */
	char fullpath[MAXPATHLEN + 1];	/* full pathname to file */
	char *eval_form = NULL;	/* form to evaluate with `-eval' */
	char *eval_function = NULL;	/* function to evaluate with `-f' */
	char *load_library = NULL;	/* library to load */
	int quick = 0;		/* quick edit, don't wait for user to
				   finish */
	int batch = 0;		/* batch mode */
	int view = 0;		/* view only. */
	int nofiles = 0;
	int errflg = 0;		/* option error */
	int s;			/* socket / msqid to server */
	int connect_type;	/* CONN_UNIX, CONN_INTERNET, or
				 * CONN_IPC */
	int suppress_windows_system = 0;
	char *display = NULL;
#ifdef INTERNET_DOMAIN_SOCKETS
	char *hostarg = NULL;	/* remote hostname */
	char *remotearg;
	char thishost[HOSTNAMSZ];	/* this hostname */
	char remotepath[MAXPATHLEN + 1];	/* remote pathname */
	int rflg = 0;		/* pathname given on cmdline */
	char *portarg;
	unsigned short port = 0;	/* port to server */
#endif				/* INTERNET_DOMAIN_SOCKETS */
	char *path;		/* used indiscriminately */
#ifdef SYSV_IPC
	struct msgbuf *msgp;	/* message */
#endif				/* SYSV_IPC */
	char *tty = NULL;
	char buffer[GSERV_BUFSZ + 1];	/* buffer to read pid */
	char result[GSERV_BUFSZ + 1];
	int i;
	int sz;
	size_t msz;

#ifdef INTERNET_DOMAIN_SOCKETS
	memset(remotepath, 0, sizeof(remotepath));
#endif				/* INTERNET_DOMAIN_SOCKETS */

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

#ifdef USE_TMPDIR
	tmpdir = getenv("TMPDIR");
#endif
	if (!tmpdir)
		tmpdir = "/tmp";

	display = getenv("DISPLAY");
	if (display)
		display = my_strdup(display);
	else
		suppress_windows_system = 1;

	for (i = 1; argv[i] && !errflg; i++) {
		if (*argv[i] != '-')
			break;
		else if (*argv[i] == '-'
			 && (*(argv[i] + 1) == '\0'
			     || (*(argv[i] + 1) == '-'
				 && *(argv[i] + 2) == '\0'))) {
			/* `-' or `--' */
			++i;
			break;
		}

		if (!strcmp(argv[i], "-batch") || !strcmp(argv[i], "--batch"))
			batch = 1;
		else if (!strcmp(argv[i], "-eval")
			 || !strcmp(argv[i], "--eval")) {
			if (!argv[++i]) {
				fprintf(stderr,
					"%s: `-eval' must be followed by an argument\n",
					progname);
				exit(1);
			}
			eval_form = argv[i];
		} else if (!strcmp(argv[i], "-display")
			   || !strcmp(argv[i], "--display")) {
			suppress_windows_system = 0;
			if (!argv[++i]) {
				fprintf(stderr,
					"%s: `-display' must be followed by an argument\n",
					progname);
				exit(1);
			}
			if (display)
				free(display);
			/* no need to strdup. */
			display = argv[i];
		} else if (!strcmp(argv[i], "-nw"))
			suppress_windows_system = 1;
		else {
			/* Iterate over one-letter options. */
			char *p;
			int over = 0;
			for (p = argv[i] + 1; *p && !over; p++) {
				switch (*p) {
				case 'q':
					quick = 1;
					break;
				case 'v':
					view = 1;
					break;
				case 'f':
					GET_ARGUMENT(eval_function, "-f");
					break;
				case 'l':
					GET_ARGUMENT(load_library, "-l");
					break;
#ifdef INTERNET_DOMAIN_SOCKETS
				case 'h':
					GET_ARGUMENT(hostarg, "-h");
					break;
				case 'p':
					GET_ARGUMENT(portarg, "-p");
					port = atoi(portarg);
					break;
				case 'r':
					GET_ARGUMENT(remotearg, "-r");
					xstrncpy(remotepath, remotearg, sizeof(remotepath));
					remotepath[sizeof(remotepath)-1]='\0';
					rflg = 1;
					break;
#endif				/* INTERNET_DOMAIN_SOCKETS */
				default:
					errflg = 1;
				}
			}	/* for */
		}		/* else */
	}			/* for */

	if (errflg) {
		fprintf(stderr,
#ifdef INTERNET_DOMAIN_SOCKETS
			"Usage: %s [-nw] [-display display] [-q] [-v] [-l library]\n"
			"       [-batch] [-f function] [-eval form]\n"
			"       [-h host] [-p port] [-r remote-path] [[+line] file] ...\n",
#else				/* !INTERNET_DOMAIN_SOCKETS */
			"Usage: %s [-nw] [-q] [-v] [-l library] [-f function] [-eval form] "
			"[[+line] path] ...\n",
#endif				/* !INTERNET_DOMAIN_SOCKETS */
			progname);
		exit(1);
	}
	if (batch && argv[i]) {
		fprintf(stderr, "%s: Cannot specify `-batch' with file names\n",
			progname);
		exit(1);
	}
#if defined(INTERNET_DOMAIN_SOCKETS)
	if (suppress_windows_system && hostarg) {
		fprintf(stderr, "%s: Remote editing is available only on X\n",
			progname);
		exit(1);
	}
#endif
	*result = '\0';
	if (eval_function || eval_form || load_library) {
#if defined(INTERNET_DOMAIN_SOCKETS)
		connect_type = make_connection(hostarg, port, &s);
#else
		connect_type = make_connection(NULL, 0, &s);
#endif
		SNPRINTF(sz, command, sizeof(command),
			 "(gnuserv-eval%s '(progn ", quick ? "-quickly" : "");
		send_string(s, command);
		if (load_library) {
			send_string(s, "(load-library ");
			send_string(s, clean_string(load_library));
			send_string(s, ") ");
		}
		if (eval_form) {
			send_string(s, eval_form);
		}
		if (eval_function) {
			send_string(s, "(");
			send_string(s, eval_function);
			send_string(s, ")");
		}
		send_string(s, "))");
		/* disconnect already sends EOT_STR */
#ifdef SYSV_IPC
		if (connect_type == (int)CONN_IPC)
			disconnect_from_ipc_server(s, msgp, batch && !quick);
#else				/* !SYSV_IPC */
		if (connect_type != (int)CONN_IPC)
			disconnect_from_server(s, batch && !quick);
#endif				/* !SYSV_IPC */
	} /* eval_function || eval_form || load_library */
	else if (batch) {
		/* no sexp on the command line, so read it from stdin */
		int nb;

#if defined(INTERNET_DOMAIN_SOCKETS)
		connect_type = make_connection(hostarg, port, &s);
#else
		connect_type = make_connection(NULL, 0, &s);
#endif
		SNPRINTF(sz, command, sizeof(command),
			 "(gnuserv-eval%s '(progn ", quick ? "-quickly" : "");
		send_string(s, command);

		while ((nb = read(fileno(stdin), buffer, GSERV_BUFSZ - 1)) > 0) {
			buffer[nb] = '\0';
			send_string(s, buffer);
		}
		send_string(s, "))");
		/* disconnect already sends EOT_STR */
#ifdef SYSV_IPC
		if (connect_type == (int)CONN_IPC)
			disconnect_from_ipc_server(s, msgp, batch && !quick);
#else				/* !SYSV_IPC */
		if (connect_type != (int)CONN_IPC)
			disconnect_from_server(s, batch && !quick);
#endif				/* !SYSV_IPC */
	}

	if (!batch) {
		if (suppress_windows_system) {
			tty = ttyname(0);
			if (!tty) {
				fprintf(stderr, "%s: Not connected to a tty",
					progname);
				exit(1);
			}
#if defined(INTERNET_DOMAIN_SOCKETS)
			connect_type = make_connection(hostarg, port, &s);
#else
			connect_type = make_connection(NULL, 0, &s);
#endif
			send_string(s, "(gnuserv-eval '(emacs-pid))");
			send_string(s, EOT_STR);

			if (read_line(s, buffer) == 0) {
				fprintf(stderr,
					"%s: Could not establish Emacs process id\n",
					progname);
				exit(1);
			}
			/* Don't do disconnect_from_server because we have already read
			   data, and disconnect doesn't do anything else. */
#ifdef SYSV_IPC
			if (connect_type == (int)CONN_IPC)
				disconnect_from_ipc_server(s, msgp, FALSE);
#endif				/* !SYSV_IPC */

			emacs_pid = (pid_t) atol(buffer);
			initialize_signals();
		}
		/* suppress_windows_system */
#if defined(INTERNET_DOMAIN_SOCKETS)
		connect_type = make_connection(hostarg, port, &s);
#else
		connect_type = make_connection(NULL, 0, &s);
#endif

#ifdef INTERNET_DOMAIN_SOCKETS
		if (connect_type == (int)CONN_INTERNET) {
			char *ptr;
			gethostname(thishost, HOSTNAMSZ);
			if (!rflg) {	/* attempt to generate a path
					 * to this machine */
				if ((ptr = getenv("GNU_NODE")) != NULL) {
					/* user specified a path */
					xstrncpy(remotepath, ptr, sizeof(remotepath)-1);
					remotepath[sizeof(remotepath)-1]='\0';
				}
			}
#if 0				/* This is really bogus... re-enable it if you must have it! */
#if defined (hp9000s300) || defined (hp9000s800)
			else if (strcmp(thishost, hostarg)) {	/* try /net/thishost */
				strcpy(remotepath, "/net/");	/* (this fails using internet
								   addresses) */
				strcat(remotepath, thishost);
			}
#endif
#endif
		} else {	/* same machines, no need for path */
			remotepath[0] = '\0';	/* default is the empty path */
		}
#endif				/* INTERNET_DOMAIN_SOCKETS */

#ifdef SYSV_IPC
		if ((msgp = (struct msgbuf *)
		     malloc(sizeof *msgp + GSERV_BUFSZ)) == NULL) {
			fprintf(stderr,
				"%s: not enough memory for message buffer\n",
				progname);
			exit(1);
		}
		/* if */
		msgp->mtext[0] = '\0';	/* ready for later strcats */
#endif				/* SYSV_IPC */

		if (suppress_windows_system) {
			char *term = getenv("TERM");
			pid_t pid = getpid();

			if (!term) {
				fprintf(stderr, "%s: unknown terminal type\n",
					progname);
				exit(1);
			}
			SNPRINTF(sz, command, sizeof(command),
				 "(gnuserv-edit-files '(tty %s %s %d) '(",
				 clean_string(tty), clean_string(term),
				 (int)pid);
		} else {	/* !suppress_windows_system */

			if (0) ;
#ifdef HAVE_X_WINDOWS
			else if (display) {
				SNPRINTF(sz, command, sizeof(command),
					 "(gnuserv-edit-files '(x %s) '(",
					 clean_string(display));
			}
#endif
		}		/* !suppress_windows_system */
		send_string(s, command);

		if (!argv[i])
			nofiles = 1;

		for (; argv[i]; i++) {
			if (i < argc - 1 && *argv[i] == '+') {
				starting_line = atoi(argv[i++]);
			} else {
				starting_line = 1;
			}
			/* If the last argument is +something, treat it as a
			   file. */
			if (i == argc) {
				starting_line = 1;
				--i;
			}
			filename_expand(fullpath, argv[i], sizeof(fullpath));
#ifdef INTERNET_DOMAIN_SOCKETS
			msz = strlen(remotepath) + strlen(fullpath) + 1;
			path = (char*)malloc(msz);
			SNPRINTF(sz, path, msz, "%s%s", remotepath, fullpath);
#else  /* !INTERNET_DOMAIN_SOCKETS */
			path = my_strdup(fullpath);
#endif	/* INTERNET_DOMAIN_SOCKETS */
			SNPRINTF(sz, command, sizeof(command),
				"(%d . %s)", starting_line, clean_string(path));
			send_string(s, command);
			free(path);
		}

		SNPRINTF(sz, command, sizeof(command), ")%s%s",
			 (quick || (nofiles && !suppress_windows_system))
			 ? " 'quick"
			 : "",
			 view ? " 'view" : "");
		send_string(s, command);
		send_string(s, ")");

#ifdef SYSV_IPC
		if (connect_type == (int)CONN_IPC)
			disconnect_from_ipc_server(s, msgp, FALSE);
#else				/* !SYSV_IPC */
		if (connect_type != (int)CONN_IPC)
			disconnect_from_server(s, FALSE);
#endif				/* !SYSV_IPC */
	}

	/* not batch */
	return 0;

}
Exemple #8
0
/*VARARGS1*/
int
exec(int type, ...)
{
	va_list			args;

	int			i;
	int			procuid;
	int			procgid;
	int			ret;
	int			fr_flg;

	char			*cp;
	char			*infile;
	char			*outfile;
	char			*errfile;
	char			*sep;

	char			**listp;
	char			**file_list;
	char			*printerName;
	char			*printerNameToShow;
	static char		nameBuf[100];
	char			*clean_title;

	PSTATUS			*printer;

	RSTATUS			*request;

	FSTATUS			*form;

	EXEC			*ep;

	PWSTATUS		*pwheel;
	time_t			now;
	struct passwd		*pwp;
#ifdef LP_USE_PAPI_ATTR
	struct stat		tmpBuf;
	char 			tmpName[BUFSIZ];
	char			*path = NULL;
#endif
	char *av[ARG_MAX];
	char **envp = NULL;
	int ac = 0;
	char	*mail_zonename = NULL;
	char	*slabel = NULL;

	syslog(LOG_DEBUG, "exec(%s)", _exec_name(type));

	memset(av, 0, sizeof (*av));

	va_start (args, type);

	switch (type) {

	case EX_INTERF:
		printer = va_arg(args, PSTATUS *);
		request = printer->request;
		ep = printer->exec;
		break;
		
	case EX_FAULT_MESSAGE:
		printer = va_arg(args, PSTATUS *);
		request = va_arg(args, RSTATUS *);
		if (! ( printer->status & (PS_FORM_FAULT | PS_SHOW_FAULT))) {
			return(0);
		}
		ep = printer->fault_exec;
		printerName = (printer->printer && printer->printer->name 
				  ? printer->printer->name : "??");
			snprintf(nameBuf, sizeof (nameBuf),
				"%s (on %s)\n", printerName, Local_System);

		printerNameToShow = nameBuf;

		(void) time(&now);
		(void) strftime(time_buf, sizeof (time_buf),
			NULL, localtime(&now));
		break;

	case EX_SLOWF:
		request = va_arg(args, RSTATUS *);
		ep = request->exec;
		break;

	case EX_NOTIFY:
		request = va_arg(args, RSTATUS *);
		if (request->request->actions & ACT_NOTIFY) {
			errno = EINVAL;
			return (-1);
		}
		ep = request->exec;
		break;

	case EX_ALERT:
		printer = va_arg(args, PSTATUS *);
		if (!(printer->printer->fault_alert.shcmd)) {
			errno = EINVAL;
			return(-1);
		}
		ep = printer->alert->exec;
		break;

	case EX_PALERT:
		pwheel = va_arg(args, PWSTATUS *);
		ep = pwheel->alert->exec;
		break;

	case EX_FORM_MESSAGE:
		(void) time(&now);
		(void) strftime(time_buf, sizeof (time_buf),
			NULL, localtime(&now));

		/*FALLTHRU*/
	case EX_FALERT:
		form = va_arg(args, FSTATUS *);
		ep = form->alert->exec;
		break;

	default:
		errno = EINVAL;
		return(-1);

	}
	va_end (args);

	if (!ep || (ep->pid > 0)) {
		errno = EBUSY;
		return(-1);
	}

	ep->flags = 0;

	key = ep->key = getkey();

	switch ((ep->pid = Fork1(ep))) {

	case -1:
		relock ();
		return(-1);

	case 0:
		/*
		 * We want to be able to tell our parent how we died.
		 */
		lp_alloc_fail_handler = child_mallocfail;
		break;

	default:
		switch(type) {

		case EX_INTERF:
			request->request->outcome |= RS_PRINTING;
			break;

		case EX_NOTIFY:
			request->request->outcome |= RS_NOTIFYING;
			break;

		case EX_SLOWF:
			request->request->outcome |= RS_FILTERING;
			request->request->outcome &= ~RS_REFILTER;
			break;

		}
		return(0);

	}

	for (i = 0; i < NSIG; i++)
		(void)signal (i, SIG_DFL);
	(void)signal (SIGALRM, SIG_IGN);
	(void)signal (SIGTERM, sigtrap);

	closelog();
	for (i = 0; i < OpenMax; i++)
		if (i != ChildMd->writefd)
			Close (i);
	openlog("lpsched", LOG_PID|LOG_NDELAY|LOG_NOWAIT, LOG_LPR);

	setpgrp();

	/* Set a default path */
	addenv (&envp, "PATH", "/usr/lib/lp/bin:/usr/bin:/bin:/usr/sbin:/sbin");
	/* copy locale related variables */
	addenv (&envp, "TZ", getenv("TZ"));
	addenv (&envp, "LANG", getenv("LANG"));
	addenv (&envp, "LC_ALL", getenv("LC_ALL"));
	addenv (&envp, "LC_COLLATE", getenv("LC_COLLATE"));
	addenv (&envp, "LC_CTYPE", getenv("LC_CTYPE"));
	addenv (&envp, "LC_MESSAGES", getenv("LC_MESSAGES"));
	addenv (&envp, "LC_MONETARY", getenv("LC_MONETARY"));
	addenv (&envp, "LC_NUMERIC", getenv("LC_NUMERIC"));
	addenv (&envp, "LC_TIME", getenv("LC_TIME"));

	sprintf ((cp = BIGGEST_NUMBER_S), "%ld", key);
	addenv (&envp, "SPOOLER_KEY", cp);

#if	defined(DEBUG)
	addenv (&envp, "LPDEBUG", (debug? "1" : "0"));
#endif

	/*
	 * Open the standard input, standard output, and standard error.
	 */
	switch (type) {
		
	case EX_SLOWF:
	case EX_INTERF:
		/*
		 * stdin:  /dev/null
		 * stdout: /dev/null (EX_SLOWF), printer port (EX_INTERF)
		 * stderr: req#
		 */
		infile = 0;
		outfile = 0;
		errfile = makereqerr(request);
		break;

	case EX_NOTIFY:
		/*
		 * stdin:  req#
		 * stdout: /dev/null
		 * stderr: /dev/null
		 */
		infile = makereqerr(request);
		outfile = 0;
		errfile = 0;

		break;

	case EX_ALERT:
	case EX_FALERT:
	case EX_PALERT:
	case EX_FAULT_MESSAGE:
	case EX_FORM_MESSAGE:
		/*
		 * stdin:  /dev/null
		 * stdout: /dev/null
		 * stderr: /dev/null
		 */
		infile = 0;
		outfile = 0;
		errfile = 0;
		break;

	}

	if (infile) {
		if (Open(infile, O_RDONLY) == -1)
			Done (EXEC_EXIT_NOPEN, errno);
	} else {
		if (Open("/dev/null", O_RDONLY) == -1)
			Done (EXEC_EXIT_NOPEN, errno);
	}

	if (outfile) {
		if (Open(outfile, O_CREAT|O_TRUNC|O_WRONLY, 0600) == -1)
			Done (EXEC_EXIT_NOPEN, errno);
	} else {
		/*
		 * If EX_INTERF, this is still needed to cause the
		 * standard error channel to be #2.
		 */
		if (Open("/dev/null", O_WRONLY) == -1)
			Done (EXEC_EXIT_NOPEN, errno);
	}

	if (errfile) {
		if (Open(errfile, O_CREAT|O_TRUNC|O_WRONLY, 0600) == -1)
			Done (EXEC_EXIT_NOPEN, errno);
	} else {
		if (Open("/dev/null", O_WRONLY) == -1)
			Done (EXEC_EXIT_NOPEN, errno);
	}

	switch (type) {

	case EX_INTERF:
		/*
		 * Opening a ``port'' can be dangerous to our health:
		 *
		 *	- Hangups can occur if the line is dropped.
		 *	- The printer may send an interrupt.
		 *	- A FIFO may be closed, generating SIGPIPE.
		 *
		 * We catch these so we can complain nicely.
		 */
		trap_fault_signals ();

		(void)Close (1);

		if (strchr (request->request->user, '@'))
		{
			procuid = Lp_Uid;
			procgid = Lp_Gid;
		}
		else
		{
			procuid = request->secure->uid;
			procgid = request->secure->gid;
		}
		if (printer->printer->dial_info)
		{
			ret = open_dialup(request->printer_type,
				printer->printer);
			if (ret == 0)
				do_undial = 1;
		}
		else
		{
			ret = open_direct(request->printer_type,
				printer->printer);
			do_undial = 0;
			/* this is a URI */
			if (is_printer_uri(printer->printer->device) == 0)
				addenv(&envp, "DEVICE_URI",
					 printer->printer->device);
		}
				addenv(&envp, "DEVICE_URI",
					 printer->printer->device);
		if (ret != 0)
			Done (ret, errno);
			
		if (!(request->request->outcome & RS_FILTERED))
			file_list = request->request->file_list;

		else {
			register int		count	= 0;
			register char *		num	= BIGGEST_REQID_S;
			register char *		prefix;

			prefix = makestr(
				Lp_Temp,
				"/F",
				getreqno(request->secure->req_id),
				"-",
				(char *)0
			);

			file_list = (char **)Malloc(
				(lenlist(request->request->file_list) + 1)
			      * sizeof(char *)
			);

			for (
				listp = request->request->file_list;
				*listp;
				listp++
			) {
				sprintf (num, "%d", count + 1);
				file_list[count] = makestr(
					prefix,
					num,
					(char *)0
				);
				count++;
			}
			file_list[count] = 0;
		}

#ifdef LP_USE_PAPI_ATTR
		/*
		 * Check if the PAPI job attribute file exists, if it does
		 * pass the file's pathname to the printer interface script
		 * in an environment variable. This file is created when
		 * print jobs are submitted via the PAPI interface.
		 */
		snprintf(tmpName, sizeof (tmpName), "%s-%s",
			getreqno(request->secure->req_id), LP_PAPIATTRNAME);
		path = makepath(Lp_Temp, tmpName, (char *)0);
		if ((path != NULL) && (stat(path, &tmpBuf) == 0))
		{
			/*
			 * IPP job attribute file exists for this job so
			 * set the environment variable
			 */
			addenv(&envp, "ATTRPATH", path);
		}
		Free(path);

		/*
		 * now set environment variable for the printer's PostScript
		 * Printer Description (PPD) file, this is used by the filter
		 * when forming the print data for this printer.
		 */
		if ((request->printer != NULL) &&
		    (request->printer->printer != NULL) &&
		    (request->printer->printer->name != NULL))
		{
			snprintf(tmpName, sizeof (tmpName), "%s.ppd",
				request->printer->printer->name);
			path = makepath(ETCDIR, "ppd", tmpName, (char *)0);
			if ((path != NULL) && (stat(path, &tmpBuf) == 0))
			{
				addenv(&envp, "PPD", path);
			}
			Free(path);
		}
#endif

		if (request->printer_type)
			addenv(&envp, "TERM", request->printer_type);

		if (!(printer->printer->daisy)) {
			register char *	chset = 0;
			register char *	csp;

			if (
				request->form
			     && request->form->form->chset
			     && request->form->form->mandatory
			     && !STREQU(NAME_ANY, request->form->form->chset)
			)
				chset = request->form->form->chset;

			else if (
				request->request->charset
			     && !STREQU(NAME_ANY, request->request->charset)
			)
				chset = request->request->charset;

			if (chset) {
				csp = search_cslist(
					chset,
					printer->printer->char_sets
				);

				/*
				 * The "strtok()" below wrecks the string
				 * for future use, but this is a child
				 * process where it won't be needed again.
				 */
				addenv (&envp, "CHARSET",
					(csp? strtok(csp, "=") : chset)
				);
			}
		}

		if (request->fast)
			addenv(&envp, "FILTER", request->fast);

		/*
		 * Add the sensitivity label to the environment for
		 * banner page and header/footer processing
		 */

		if (is_system_labeled() && request->secure->slabel != NULL)
			addenv(&envp, "SLABEL", request->secure->slabel);

		/*
		 * Add the system name to the user name (ala system!user)
		 * unless it is already there. RFS users may have trouble
		 * here, sorry!
		 */
		cp = strchr(request->secure->user, '@');

		allTraysWithForm(printer, request->form); 

		/*
		 * Fix for 4137389
		 * Remove double quotes from title string.
		 */
		fr_flg = 1;
		clean_title = strdup(NB(request->request->title));
		if (clean_title == NULL) {
			/*
			 * strdup failed. We're probably hosed
			 * but try setting clean_title
			 * to original title and continuing.
			 */
			clean_title = NB(request->request->title);
			fr_flg = 0;
		} else if (strcmp(clean_title, "") != 0) {
			char *ct_p;

			for (ct_p = clean_title; *ct_p != NULL; ct_p++) {
				if (*ct_p == '"')
					*ct_p = ' ';
			}
		}

		av[ac++] = arg_string(TRUSTED, "%s/%s", Lp_A_Interfaces,
					printer->printer->name);
		av[ac++] = arg_string(TRUSTED, "%s", request->secure->req_id);
		av[ac++] = arg_string(UNTRUSTED, "%s", request->request->user);
		av[ac++] = arg_string(TRUSTED, "%s", clean_title);
		av[ac++] = arg_string(TRUSTED, "%d", request->copies);

		if (fr_flg)
			free (clean_title);

		sep = "";

		/*
		 * Do the administrator defined key=value pair options
		 */

		argbuf[0] = '\0';
				
		if (printer->printer->options) {
			char **tmp = printer->printer->options;
			while(*tmp != NULL) {
				STRLCAT(argbuf, sep, sizeof (argbuf));
				sep = " ";
				STRLCAT(argbuf, *tmp++, sizeof (argbuf));
			}
		}

		/*
		 * Do the administrator defined ``stty'' stuff before
		 * the user's -o options, to allow the user to override.
		 */
		if (printer->printer->stty) {
			STRLCAT (argbuf, sep, sizeof (argbuf));
			sep = " ";
			STRLCAT (argbuf, "stty='", sizeof (argbuf));
			STRLCAT (argbuf, printer->printer->stty,
			    sizeof (argbuf));
			STRLCAT (argbuf, "'", sizeof (argbuf));
		}

		/*
		 * Do all of the user's options except the cpi/lpi/etc.
		 * stuff, which is done separately.
		 */
		if (request->request->options) {
			listp = dashos(request->request->options);
			while (*listp) {
				if (
					!STRNEQU(*listp, "cpi=", 4)
				     && !STRNEQU(*listp, "lpi=", 4)
				     && !STRNEQU(*listp, "width=", 6)
				     && !STRNEQU(*listp, "length=", 7)
				) {
					STRLCAT (argbuf, sep, sizeof (argbuf));
					sep = " ";
					STRLCAT (argbuf, *listp,
					    sizeof (argbuf));
				}
				listp++;
			}
		}

		/*
		 * The "pickfilter()" routine (from "validate()")
		 * stored the cpi/lpi/etc. stuff that should be
		 * used for this request. It chose form over user,
		 * and user over printer.
		 */
		if (request->cpi) {
			STRLCAT (argbuf, sep, sizeof (argbuf));
			sep = " ";
			STRLCAT (argbuf, "cpi=", sizeof (argbuf));
			STRLCAT (argbuf, request->cpi, sizeof (argbuf));
		}
		if (request->lpi) {
			STRLCAT (argbuf, sep, sizeof (argbuf));
			sep = " ";
			STRLCAT (argbuf, "lpi=", sizeof (argbuf));
			STRLCAT (argbuf, request->lpi, sizeof (argbuf));
		}
		if (request->pwid) {
			STRLCAT (argbuf, sep, sizeof (argbuf));
			sep = " ";
			STRLCAT (argbuf, "width=", sizeof (argbuf));
			STRLCAT (argbuf, request->pwid, sizeof (argbuf));
		}
		if (request->plen) {
			STRLCAT (argbuf, sep, sizeof (argbuf));
			sep = " ";
			STRLCAT (argbuf, "length=", sizeof (argbuf));
			STRLCAT (argbuf, request->plen, sizeof (argbuf));
		}

		/*
		 * Do the ``raw'' bit last, to ensure it gets
		 * done. If the user doesn't want this, then he or
		 * she can do the correct thing using -o stty=
		 * and leaving out the -r option.
		 */
		if (request->request->actions & ACT_RAW) {
			STRLCAT (argbuf, sep, sizeof (argbuf));
			sep = " ";
			STRLCAT (argbuf, "stty=-opost", sizeof (argbuf));
		}


		/* the "options" */
		av[ac++] = arg_string(UNTRUSTED, "%s", argbuf);

		for (listp = file_list; *listp; listp++)
			av[ac++] = arg_string(TRUSTED, "%s", *listp);

		(void)chfiles (file_list, procuid, procgid);

		break;


	case EX_SLOWF:
		if (request->slow)
			addenv(&envp, "FILTER", request->slow);

		if (strchr (request->request->user, '@'))
		{
			procuid = Lp_Uid;
			procgid = Lp_Gid;
		}
		else
		{
			procuid = request->secure->uid;
			procgid = request->secure->gid;
		}
		cp = _alloc_files(
			lenlist(request->request->file_list),
			getreqno(request->secure->req_id),
			procuid, procgid);

		av[ac++] = arg_string(TRUSTED, "%s", Lp_Slow_Filter);
		av[ac++] = arg_string(TRUSTED, "%s/%s", Lp_Temp, cp);
		for (listp = request->request->file_list; *listp; listp++)
			av[ac++] = arg_string(TRUSTED, "%s", *listp);

		(void)chfiles (request->request->file_list, procuid, procgid);

#ifdef LP_USE_PAPI_ATTR
		/*
		 * Check if the PAPI job attribute file exists, if it does
		 * pass the file's pathname to the slow-filters in an
		 * environment variable. Note: this file is created when
		 * print jobs are submitted via the PAPI interface.
		 */
		snprintf(tmpName, sizeof (tmpName), "%s-%s",
			getreqno(request->secure->req_id), LP_PAPIATTRNAME);
		path = makepath(Lp_Temp, tmpName, (char *)0);
		if ((path != NULL) && (stat(path, &tmpBuf) == 0))
		{
			/*
			 * IPP job attribute file exists for this job so
			 * set the environment variable
			 */
			addenv(&envp, "ATTRPATH", path);
		}
		Free(path);


		/*
		 * now set environment variable for the printer's PostScript
		 * Printer Description (PPD) file, this is used by the filter
		 * when forming the print data for this printer.
		 */
		if ((request->printer != NULL) &&
		    (request->printer->printer != NULL) &&
		    (request->printer->printer->name != NULL))
		{
			snprintf(tmpName, sizeof (tmpName), "%s.ppd",
				request->printer->printer->name);
			path = makepath(ETCDIR, "ppd", tmpName, (char *)0);
			if ((path != NULL) && (stat(path, &tmpBuf) == 0))
			{
				addenv(&envp, "PPD", path);
			}
			Free(path);
		}
#endif
		break;

	case EX_ALERT:
		procuid = Lp_Uid;
		procgid = Lp_Gid;
		(void)Chown (printer->alert->msgfile, procuid, procgid);

		av[ac++] = arg_string(TRUSTED, "%s/%s/%s", Lp_A_Printers,
				printer->printer->name, ALERTSHFILE);
		av[ac++] = arg_string(TRUSTED, "%s", printer->alert->msgfile);

		break;

	case EX_PALERT:
		procuid = Lp_Uid;
		procgid = Lp_Gid;
		(void)Chown (pwheel->alert->msgfile, procuid, procgid);

		av[ac++] = arg_string(TRUSTED, "%s/%s/%s", Lp_A_PrintWheels,
				pwheel->pwheel->name, ALERTSHFILE);
		av[ac++] = arg_string(TRUSTED, "%s", printer->alert->msgfile);

		break;

	case EX_FALERT:
		procuid = Lp_Uid;
		procgid = Lp_Gid;
		(void)Chown (form->alert->msgfile, procuid, procgid);

		av[ac++] = arg_string(TRUSTED, "%s/%s/%s", Lp_A_Forms,
				form->form->name, ALERTSHFILE);
		av[ac++] = arg_string(TRUSTED, "%s", printer->alert->msgfile);

		break;

	case EX_FORM_MESSAGE:
		procuid = Lp_Uid;
		procgid = Lp_Gid;

		av[ac++] = arg_string(TRUSTED, "%s/form", Lp_A_Faults);
		av[ac++] = arg_string(TRUSTED, "%s", form->form->name);
		av[ac++] = arg_string(TRUSTED, "%s", time_buf);
		av[ac++] = arg_string(TRUSTED, "%s/%s/%s", Lp_A_Forms,
				form->form->name, FORMMESSAGEFILE);

		break;

	case EX_FAULT_MESSAGE:
		procuid = Lp_Uid;
		procgid = Lp_Gid;

		av[ac++] = arg_string(TRUSTED, "%s/printer", Lp_A_Faults);
		av[ac++] = arg_string(TRUSTED, "%s", printerNameToShow);
		av[ac++] = arg_string(TRUSTED, "%s", time_buf);
		av[ac++] = arg_string(TRUSTED, "%s/%s/%s", Lp_A_Printers,
				printerName, FAULTMESSAGEFILE);

		break;

	case EX_NOTIFY:
		if (request->request->alert) {
			if (strchr(request->request->user, '@')) {
				procuid = Lp_Uid;
				procgid = Lp_Gid;
			} else {
				procuid = request->secure->uid;
				procgid = request->secure->gid;
			}
			av[ac++] = arg_string(TRUSTED, "%s",
					request->request->alert);
		} else {
			char *user = strdup(request->request->user);
			clean_string(user);
			slabel = request->secure->slabel;

			if (request->request->actions & ACT_WRITE) {
				av[ac++] = arg_string(TRUSTED, "%s", BINWRITE);
				snprintf(argbuf, sizeof (argbuf),
					"%s %s || %s %s",
					BINWRITE, user,
					BINMAIL, user
				);
				av[ac++] = arg_string(TRUSTED, "/bin/sh");
				av[ac++] = arg_string(TRUSTED, "-c");
				av[ac++] = arg_string(TRUSTED, "%s", argbuf);
			} else if ((getzoneid() == GLOBAL_ZONEID) &&
				   is_system_labeled() && (slabel != NULL)) {
				/*
				 * If in the global zone and the system is
				 * labeled, mail is handled via a local
				 * labeled zone that is the same label as
				 * the request.
				 */
				if ((mail_zonename =
				    get_labeled_zonename(slabel)) ==
				    (char *)-1) {
					/*
					 * Cannot find labeled zone, just
					 * return 0.
					 */
					return(0);
				}
			}
			if (mail_zonename == NULL) {
				procuid = Lp_Uid;
				procgid = Lp_Gid;
				av[ac++] = arg_string(TRUSTED, "%s", BINMAIL);
				av[ac++] = arg_string(UNTRUSTED, "%s", user);
			} else {
				procuid = getuid();
				procgid = getgid();
				av[ac++] = arg_string(TRUSTED, "%s",
				    "/usr/sbin/zlogin");
				av[ac++] = arg_string(TRUSTED, "%s",
				    mail_zonename);
				av[ac++] = arg_string(TRUSTED, "%s",
				    BINMAIL);
				av[ac++] = arg_string(UNTRUSTED, "%s",
				    user);
				Free(mail_zonename);
			}

			free(user);
		}
		break;
	}

	av[ac++] = NULL;

	Fork2 ();
	/* only the child returns */

	/*
	 * Correctly set up the supplemental group list
	 * for proper file access (before execl the interface program)
	 */

	pwp = getpwuid(procuid);
	if (pwp == NULL) {
		note("getpwuid(%d) call failed\n", procuid);
	} else if (initgroups(pwp->pw_name, procgid) < 0) {
		note("initgroups() call failed %d\n", errno);
	}
	
	setgid (procgid);
	setuid (procuid);

	/*
	 * The shell doesn't allow the "trap" builtin to set a trap
	 * for a signal ignored when the shell is started. Thus, don't
	 * turn off signals in the last child!
	 */

#ifdef DEBUG
	for (i = 0; av[i] != NULL; i++)
		note("exec(%s): av[%d] = %s", _exec_name(type), i, av[i]);
	for (i = 0; envp[i] != NULL; i++)
		note("exec(%s): envp[%d] = %s", _exec_name(type), i, envp[i]);
#endif

	execvpe(av[0], av, envp);
	Done (EXEC_EXIT_NEXEC, errno);
	/*NOTREACHED*/
	return (0);
}
Exemple #9
0
// Main function, the base TCP server
int main(int argc, char *argv[])
{
	//-------------------- SET UP VARIABLES -----------------------
	
	// Set up all required variables for sockets programming, starting with addrinfo "hints" struct and pointers to results list
	struct addrinfo hints, *result;

	// Integer variable used to set socket options
	int yes = 1;

	// Create command buffer, to send commands directly to the server
	char command[512] = { '\0' };

	// Define a generic indexer variable for loops
	int i = 0;

	// Set up SQLite statement struct
	sqlite3_stmt *stmt;

	// Create a buffer to store queries to process on the database
	char query[256] = { '\0' };

	//------------------ INITIALIZE SIGNAL HANDLERS ---------------

	// Install signal handlers for graceful shutdown
	// Install SIGHUP signal handler
	signal(SIGHUP, shutdown_handler);

	// Install SIGINT signal handler
	signal(SIGINT, shutdown_handler);

	// Install SIGTERM signal handler
	signal(SIGTERM, shutdown_handler);

	// Install signal handlers for statistics output
	// Install SIGUSR1 signal handler
	signal(SIGUSR1, stat_handler);

	// Install SIGUSR2 signal handler
	signal(SIGUSR2, stat_handler);

	//------------------ BEGIN SERVER INITIALIZATION --------------

	// Read in terminal on which server was started
	term = strdup(ttyname(1));

	// Print initialization message
	fprintf(stdout, "%s: %s %s - Justin Hill, Gordon Keesler, Matt Layher (CS5550 Spring 2012)\n", SERVER_NAME, INFO_MSG, SERVER_NAME);

	// Capture initial start time
	start_time = time(NULL);

	//------------------ PARSE COMMAND LINE ARGUMENTS -------------

	// Iterate through all argv command line arguments, parsing out necessary flags
	for(i = 1; i < argc; i++)
	{
		// '-d' or '--daemon' flag: daemonize the server, and run it in the background
		if(strcmp("-d", argv[i]) == 0 || strcmp("--daemon", argv[i]) == 0)
		{
			// Set daemon flag to true, so we may daemonize later
			daemonized = 1;
		}
		// '-h' or '--help' flag: print help and usage for this server, then exit
		else if(strcmp("-h", argv[i]) == 0 || strcmp("--help", argv[i]) == 0)
		{
			// Print usage message
			fprintf(stdout, "usage: %s [-d | --daemon] [-h | --help] [-l | --lock lock_file] [-p | --port port] [-q | --queue queue_length] [-t | --threads thread_count]\n\n", SERVER_NAME);

			// Print out all available flags
			fprintf(stdout, "%s flags:\n", SERVER_NAME);
			fprintf(stdout, "\t-d | --daemon:     daemonize - start server as a daemon, running it in the background\n");
			fprintf(stdout, "\t-h | --help:            help - print usage information and details about each flag the server accepts\n");
			fprintf(stdout, "\t-l | --lock:       lock_file - specify the location of the lock file utilized when the server is daemonized (default: %s)\n", LOCKFILE);
			fprintf(stdout, "\t-p | --port:            port - specify an alternative port number to run the server (default: %s)\n", DEFAULT_PORT);
			fprintf(stdout, "\t-q | --queue:   queue_length - specify the connection queue length for the incoming socket (default: %d)\n", QUEUE_LENGTH);
			fprintf(stdout, "\t-t | --threads: thread_count - specify the number of threads to generate (max number of clients) (default: %d)\n", NUM_THREADS);
			fprintf(stdout, "\n");

			// Print out all available console commands via the common console_help() function
			console_help();

			// Exit the server
			exit(0);
		}
		// '-l' or '--lock' flag: specify an alternate lock file location
		else if(strcmp("-l", argv[i]) == 0 || strcmp("--lock", argv[i]) == 0)
		{
			// Make sure that another argument exists, specifying the lockfile location
			if(argv[i+1] != NULL)
			{
				// Set lock file location as specified on the command line
				lock_location = argv[i+1];
				i++;
			}
			else
			{
				// Print error and use default location if no lockfile was specified after the flag
				fprintf(stderr, "%s: %s no lockfile location specified, defaulting to %s\n", SERVER_NAME, ERROR_MSG, LOCKFILE);
			}
		}
		// '-p' or '--port' flag: specifies an alternative port number to run the server
		else if(strcmp("-p", argv[i]) == 0 || strcmp("--port", argv[i]) == 0)
		{
			// Make sure that another argument exists, specifying the port number
			if(argv[i+1] != NULL)
			{
				// Ensure this port is a valid integer
				if(validate_int(argv[i+1]))
				{
					// Set this port to be used if it's within the valid range, else use the default
					if(atoi(argv[i+1]) >= 0 && atoi(argv[i+1]) <= MAX_PORT)
					{
						port = argv[i+1];
						i++;
					}
					else
						fprintf(stderr, "%s: %s port lies outside valid range (0-%d), defaulting to %s\n", SERVER_NAME, ERROR_MSG, MAX_PORT, DEFAULT_PORT);
				}
				else
				{
					// Print error and use default port if an invalid port number was specified
					fprintf(stderr, "%s: %s invalid port number specified, defaulting to %s\n", SERVER_NAME, ERROR_MSG, DEFAULT_PORT);
				}
			}
			else
			{
				// Print error and use default port if no port number was specified after the flag
				fprintf(stderr, "%s: %s no port number specified after flag, defaulting to %s\n", SERVER_NAME, ERROR_MSG, DEFAULT_PORT);
			}
		}
		// '-q' or '--queue' flag: specify the connection queue length
		else if(strcmp("-q", argv[i]) == 0 || strcmp("--queue", argv[i]) == 0)
		{
			// Make sure another argument exists, specifying the queue length
			if(argv[i+1] != NULL)	
			{
				// Ensure this is a valid integer for queue length
				if(validate_int(argv[i+1]))
				{
					// Set connection queue length to the number specified on the command line, if it's a number more than 0, else use the default
					if(atoi(argv[i+1]) >= 1)
					{
						queue_length = atoi(argv[i+1]);
						i++;
					}
					else
						fprintf(stderr, "%s: %s cannot use negative or zero queue length, defaulting to length %d\n", SERVER_NAME, ERROR_MSG, QUEUE_LENGTH);
				}
				else
				{
					// Print error and use default queue length if an invalid number was specified
					fprintf(stderr, "%s: %s invalid queue length specified, defaulting to length %d\n", SERVER_NAME, ERROR_MSG, QUEUE_LENGTH);
				}
			}
			else
			{
				// Print error and use default queue length if no length was specified after the flag
				fprintf(stderr, "%s: %s no queue length specified after flag, default to length %d\n", SERVER_NAME, ERROR_MSG, QUEUE_LENGTH);
			}
		}
		// '-t' or '--threads' flag: specify the number of threads to generate in the thread pool
		else if(strcmp("-t", argv[i]) == 0 || strcmp("--threads", argv[i]) == 0)
		{
			// Make sure next argument exists, specifying the number of threads
			if(argv[i+1] != NULL)
			{
				// Ensure this number is a valid integer
				if(validate_int(argv[i+1]))
				{
					// Set number of threads to the number specified on the command line, if it's a number more than 0, else use the default
					if(atoi(argv[i+1]) >= 1)
					{
						num_threads = atoi(argv[i+1]);
						i++;
					}
					else
						fprintf(stderr, "%s: %s cannot use negative or zero threads, defaulting to %d threads\n", SERVER_NAME, ERROR_MSG, NUM_THREADS);
				}
				else
				{
					// Print error and use default number of threads if an invalid number was specified
					fprintf(stderr, "%s: %s invalid number of threads specified, defaulting to %d threads\n", SERVER_NAME, ERROR_MSG, NUM_THREADS);
				}
			}
			else
			{
				// Print error and use default number of threads if no count was specified after the flag
				fprintf(stderr, "%s: %s no thread count specified after flag, defaulting to %d threads\n", SERVER_NAME, ERROR_MSG, NUM_THREADS);
			}
		}
		else
		{
			// Else, an invalid flag or parameter was specified; print an error and exit
			fprintf(stderr, "%s: %s unknown parameter '%s' specified, please run '%s -h' for help and usage\n", SERVER_NAME, ERROR_MSG, argv[i], SERVER_NAME);
			exit(-1);
		}
	}

	//------------------------ OPEN SQLITE DATABASE ----------------

	// Open database file, as specified in config header; check for success
	sqlite3_open(DB_FILE, &db);
	if(db == NULL)
	{
		// Print an error message and quit if database fails to open
		fprintf(stderr, "%s: %s sqlite: could not open database %s\n", SERVER_NAME, ERROR_MSG, DB_FILE);
		exit(-1);
	}

	// Create a query to truncate the files table in the database
	sprintf(query, "DELETE FROM files");

	// Prepare, evaluate, and finalize SQLite query
	sqlite3_prepare_v2(db, query, strlen(query) + 1, &stmt, NULL);
	if(sqlite3_step(stmt) != SQLITE_DONE)
	{
		// On query failure, print an error and exit
		fprintf(stderr, "%s: %s sqlite: could not truncate files table\n", SERVER_NAME, ERROR_MSG);
		exit(-1);
	}
	sqlite3_finalize(stmt);

	//------------------------ INITIALIZE TCP SERVER ---------------

	// Clear the hints struct using memset to nullify it
	memset(&hints, 0, sizeof(hints));

	// Set options for hints to use IPv4, a TCP connection, and the machine's current IP address
	hints.ai_family = AF_INET;          // IPv4
	hints.ai_socktype = SOCK_STREAM;    // Reliable TCP connection
	hints.ai_flags = AI_PASSIVE;        // Use my ip address

	// now populate our result addrinfo
	if((getaddrinfo(NULL, port, &hints, &result)) != 0)
	{ 
		// If getaddrinfo() fails, print an error and quit the program, since setup cannot continue.
		fprintf(stderr, "%s: %s getaddrinfo() call failed\n", SERVER_NAME, ERROR_MSG);
		exit(-1);
	}

	// Attempt to instantiate the local socket, using values set by getaddrinfo()
	if((loc_fd = socket(result->ai_family, result->ai_socktype, result->ai_protocol)) == -1)
	{
		// On socket creation failure, print an error and exit
		fprintf(stderr, "%s: %s local socket creation failed\n", SERVER_NAME, ERROR_MSG);
		exit(-1);
	}

	// Allow the system to free and re-bind the socket if it is already in use
	if(setsockopt(loc_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1)
	{
		// If setting a socket option fails, terminate the program after printing an error
		fprintf(stderr, "%s: %s failed to set socket option: SO_REUSEADDR\n", SERVER_NAME, ERROR_MSG);
		exit(-1);
	}

	// Attempt to bind the local socket
	if((bind(loc_fd, result->ai_addr, result->ai_addrlen)) == -1)
	{
		// If socket binding fails, it's typically one of two scenarios:
		// 1) Check if socket is on a privileged port, and permission is denied
		if(atoi(port) < PRIVILEGED_PORT)
			fprintf(stderr, "%s: %s failed to bind local socket (permission denied?)\n", SERVER_NAME, ERROR_MSG);
		// 2) Else, the socket is probably already bound
		else
			fprintf(stderr, "%s: %s failed to bind local socket (socket already in use?)\n", SERVER_NAME, ERROR_MSG);

		// Exit on failure
		exit(-1);
	}
	
	// Free the results struct, as it is no longer needed
	freeaddrinfo(result);

	// Begin listening on the local socket, and set connection queue length as defined above
	if((listen(loc_fd, queue_length)) == -1)
	{
		// Print error message if socket fails to begin listening
		fprintf(stderr, "%s: %s failed to begin listening on local socket\n", SERVER_NAME, ERROR_MSG);
	}
    
	//-------------------------- DAEMONIZATION ------------------

	// If server is being daemonized, do so now.
	if(daemonized == 1)
		daemonize();
	else
	{	
		// Initialize a thread pool, using number of threads as defined earlier
		threadpool = thpool_init(num_threads);

		// Initialize the network thread to handle all incoming connections
		pthread_create(&net_thread, NULL, &tcp_listen, NULL);
	
		// Print out server information and ready message
		fprintf(stdout, "%s: %s server initialized [PID: %d] [port: %s] [queue: %d] [threads: %d]\n", SERVER_NAME, OK_MSG, getpid(), port, queue_length, num_threads);

		// If server is not being daemonized, use the default console interface
		fprintf(stdout, "%s: %s type 'stop' or hit Ctrl+C (SIGINT) to stop server\n", SERVER_NAME, INFO_MSG);
	}

	//------------------------- CONSOLE COMMAND ---------------

	// Loop continuously until 'stop' is provided on the console
	while(1)
	{
		// Read in user input, clean it up
		fgets(command, sizeof(command), stdin);
		clean_string((char *)&command);

		// 'clear' - Clear the console
		if(strcmp(command, "clear") == 0)
			system("clear");
		// 'help' - Display the common console help menu
		else if(strcmp(command, "help") == 0)
			console_help();
		// 'stat' - Print out server statistics
		else if(strcmp(command, "stat") == 0)
			print_stats();
		// 'stop' - Stop the server, breaking this loop
		else if(strcmp(command, "stop") == 0)
			break;
		// Else, print console error stating command does not exist
		else
			fprintf(stderr, "%s: %s unknown console command '%s', type 'help' for console command help\n", SERVER_NAME, ERROR_MSG, command);
	}

	// Send SIGINT to the server so that it will gracefully terminate via signal handler
	kill(getpid(), SIGINT);
}
Exemple #10
0
int main(int argc, char ** argv){
	cgi datCGI;
	char * teach=NULL;
	char * acceptTOS=NULL;
	person reg_person;
	bool pw_short=false;

	init_person(&reg_person);
	init_CGI(&datCGI);

	get_CGI_data(&datCGI);
	if(datCGI.request_method == GET){
		print_exit_failure("Use POST!");
	}


	//Für die Namen: siehe HTML-Dokument mit entsprechenden <input>-Elementen
	extract_POST_data(&datCGI, "name_vor", &reg_person.first_name);
	remove_newline(reg_person.first_name);
	clean_string(reg_person.first_name);
	extract_POST_data(&datCGI, "name", &reg_person.name);
	remove_newline(reg_person.name);
	clean_string(reg_person.name);
	extract_POST_data(&datCGI, "email", &reg_person.email);
	remove_newline(reg_person.email);
	clean_string(reg_person.email);
	extract_POST_data(&datCGI, "pass", &reg_person.password);
	remove_newline(reg_person.password);
	extract_POST_data(&datCGI, "acronym", &reg_person.acronym);
	remove_newline(reg_person.acronym);
	clean_string(reg_person.acronym);
	extract_POST_data(&datCGI, "teach", &teach);
	remove_newline(teach);
	extract_POST_data(&datCGI, "acceptTOS", &acceptTOS);
	remove_newline(acceptTOS);
	//TODO: fehlerhaften Aufruf abfangen
	if(strcmp(teach, "true") == 0){
		reg_person.isTeacher=true;
		if(strlen(reg_person.acronym) != 3){
            print_html_error("Das K&uuml;rzel muss genau 3 Zeichen lang sein", "/registrierung.html");
            exit(EXIT_FAILURE);
		}
	}else{
		reg_person.isTeacher=false;
	}
	//Die E-Mail-Adresse muss genau EIN '@' beinhalten
	if((strchr(reg_person.email, '@') == strrchr(reg_person.email, '@')) && strchr(reg_person.email, '@')) {
		#ifdef DEBUG
		fprintf(stderr, "es scheint alles zu passen (EMAIL)\n");
		#endif // DEBUG

		if(strlen(reg_person.password)<8){
			pw_short=true;
		}

		insert_user(&reg_person);
	}


	//fprintf(stderr, "\nnow comes da htmlz\n");


	httpCacheControl("no-store, no-cache, must-revalidate, max-age=0");
	httpHeader(HTML);
	//printf("%s\n", datCGI.POST_data);

	print_html_head("Passwort erneut eingeben", "Verifikation");

	puts("<body>\n\
		<div id='login-form'>\n");
		printf("<p><span>Herzlich willkommen <span style='font-weight: bold;'>%s %s.</span><br>Bitte %s zum Anmelden %s Passwort ein</p>\n",
				reg_person.first_name, reg_person.name, reg_person.isTeacher ? "geben Sie" : "gib", reg_person.isTeacher ? "Ihr" : "dein" );
	printf("<form method='post' action='/cgi-bin/login.cgi' style='border-radius: 1em; padding: 1em;' autocomplete='off'>\n\
		<input type='hidden' name='email' value='%s' />\n\
		<input class='textIn' placeholder='Passwort' type='password' id='pass' name='pass' required>\n\
		<button class='submitButton' type='submit'>Anmelden*</button>\n\
		</form>\n",reg_person.email);
	puts("<small>* Cookies müssen aktiviert sein!</small>\n");
	if(pw_short){
		puts("<br><small style='color: yellow; background-color: red;'>Sie sollten wirklich ein l&auml;ngeres Passwort verwenden!!</small>\n");
	}
	puts("</div>\n</body>\n</html>\n");

	/*puts("Erhaltene Daten:\n");
	printf("CONTENT_LENGTH: %d\n", datCGI.content_length);
	printf("Name:           %s\nPassword:       %s\n", reg_person.name, reg_person.password);
	printf("Kuerzel:        %s\nTeach:          %s\n", reg_person.acronym, teach);
	printf("accepted TOS:   %s\n\n", acceptTOS);

	printf("Post Data:      %s\n", datCGI.POST_data);*/

	exit(0);
}
Exemple #11
0
char *exec_poll(host_t *current_host, char *command) {
    extern int errno;
    FILE *cmd_stdout;
    int cmd_fd;
    int return_value;
    int bytes_read;
    char logmessage[LOGSIZE];

    fd_set fds;
    int rescode, numfds;
    struct timeval timeout;

    char *result_string = (char *) malloc(BUFSIZE);

    /* establish timeout of 5 seconds for pipe response */
    timeout.tv_sec = 5;
    timeout.tv_usec = 0;

    cmd_fd = nft_popen((char *)clean_string(command), "r");

    if (set.verbose == POLLER_VERBOSITY_DEBUG) {
        snprintf(logmessage, LOGSIZE, "Host[%i] DEBUG: The POPEN returned the following File Descriptor %i\n", current_host->id, cmd_fd);
        cacti_log(logmessage);
    }

    if (cmd_fd >= 0) {
        /* Initialize File Descriptors to Review for Input/Output */
        FD_ZERO(&fds);
        FD_SET(cmd_fd,&fds);

        numfds = cmd_fd + 1;

        /* wait 5 seonds for pipe response */
        switch (select(numfds, &fds, NULL, NULL, &timeout)) {
        case -1:
            switch (errno) {
            case EBADF:
                snprintf(logmessage, LOGSIZE, "Host[%i] ERROR: One or more of the file descriptor sets specified a file descriptor that is not a valid open file descriptor.\n", current_host->id);
                cacti_log(logmessage);
                snprintf(result_string, 2, "%s", "U");
                break;
            case EINTR:
                snprintf(logmessage, LOGSIZE, "Host[%i] ERROR: The function was interrupted before any of the selected events occurred and before the timeout interval expired.\n", current_host->id);
                cacti_log(logmessage);
                snprintf(result_string, 2, "%s", "U");
                break;
            case EINVAL:
                snprintf(logmessage, LOGSIZE, "Host[%i] ERROR: Possible invalid timeout specified in select() statement.\n", current_host->id);
                cacti_log(logmessage);
                snprintf(result_string, 2, "%s", "U");
                break;
            default:
                snprintf(logmessage, LOGSIZE, "Host[%i] ERROR: The script/command select() failed\n", current_host->id);
                cacti_log(logmessage);
                snprintf(result_string, 2, "%s", "U");
                break;
            }
        case 0:
            snprintf(logmessage, LOGSIZE, "Host[%i] ERROR: The POPEN timed out\n", current_host->id);
            cacti_log(logmessage);
            snprintf(result_string, 2, "%s", "U");
            break;
        default:
            /* get only one line of output, we will ignore the rest */
            bytes_read = read(cmd_fd, result_string, BUFSIZE-1);
            if (bytes_read > 0) {
                result_string[bytes_read] = '\0';
                strip_string_crlf(result_string);
            } else {
                snprintf(logmessage, LOGSIZE, "Host[%i] ERROR: Empty result [%s]: '%s'\n", current_host->id, current_host->hostname, command);
                cacti_log(logmessage);
                snprintf(result_string, BUFSIZE, "%s", "U");
            }
        }

        /* close pipe */
        nft_pclose(cmd_fd);
    } else {
        snprintf(logmessage, LOGSIZE, "Host[%i] ERROR: Problem executing POPEN [%s]: '%s'\n", current_host->id, current_host->hostname, command);
        cacti_log(logmessage);
        snprintf(result_string, BUFSIZE, "%s", "U");
    }

    return result_string;
}
/*
 * m_links - LINKS message handler
 *      parv[0] = sender prefix
 *      parv[1] = servername mask
 * or
 *      parv[0] = sender prefix
 *      parv[1] = server to query 
 *      parv[2] = servername mask
 */
int m_links(struct Client *cptr, struct Client *sptr, int parc, char *parv[])
{
  const char*    mask = "";
  struct Client* acptr;
  struct ConfItem* aconf;
  char           clean_mask[2 * HOSTLEN + 4];
  char*          p;
  int            bogus_server = 0;
  static time_t  last_used = 0L;

  if (parc > 2)
    {
      if (!IsServer(sptr) && !HasUmode(sptr,UMODE_REMOTEINFO))
	{
	  if (SeesOperMessages(sptr))
	    sendto_one(sptr,":%s NOTICE %s :You have no S umode", me.name, parv[0]);
	  else
	    sendto_one(sptr, form_str(ERR_NOPRIVILEGES), me.name, parv[0]);
	  return 0;
	}

      if (hunt_server(cptr, sptr, ":%s LINKS %s :%s", 1, parc, parv)
          != HUNTED_ISME)
        return 0;
      mask = parv[2];
    }
  else if (parc == 2)
    mask = parv[1];

  assert(0 != mask);

  if(!NoFloodProtection(sptr))
    {
      /* reject non local requests */
      if(!MyClient(sptr))
        return 0;

      if(IsHoneypot(sptr) || (last_used + PACE_WAIT) > CurrentTime)
        {
          /* safe enough to give this on a local connect only */
          sendto_one(sptr,form_str(RPL_LOAD2HI),me.name,parv[0],"LINKS");
          return 0;
        }
      else
        {
          last_used = CurrentTime;
        }
    }

  /*
   * *sigh* Before the kiddies find this new and exciting way of 
   * annoying opers, lets clean up what is sent to all opers
   * -Dianora
   */

  {
    const char* s = mask;
    while (*s)
      {
	if (!IsServChar(*s)) {
	  bogus_server = 1;
	  break;
	}
	s++;
      }
  }

  if (bogus_server)
    {
      sendto_ops_flag(UMODE_SPY,
			  "BOGUS LINKS '%s' requested by %s (%s@%s) [%s]",
			  clean_string(clean_mask, (const unsigned char *) mask, 2 * HOSTLEN),
			  sptr->name, sptr->username,
			  sptr->host, sptr->user->server);
      return 0;
    }

  if (*mask)       /* only necessary if there is a mask */
    mask = collapse(clean_string(clean_mask, (const unsigned char *) mask, 2 * HOSTLEN));

  /* Here's a cute spacing hack for you -- asuffield */
  if (MyConnect(sptr))
    sendto_ops_flag(UMODE_SPY,
		    "LINKS %s%srequested by %s (%s@%s) [%s]",
		    mask, mask ? " " : "" , sptr->name, sptr->username,
		    sptr->host, sptr->user->server);

  for (aconf = ConfigItemList; aconf; aconf = aconf->next)
    {
      if (aconf->status != CONF_NOCONNECT_SERVER)
	continue;
      if ((aconf->flags & CONF_FLAGS_HIDDEN_SERVER) && !HasUmode(sptr, UMODE_AUSPEX))
	continue;
      acptr = find_server(aconf->name);
      if (!acptr)
	continue;
      if (!IsServer(acptr) && !IsMe(acptr))
        continue;
      if (*mask && !match(mask, acptr->name))
        continue;
      if (HasUmode(sptr,UMODE_AUSPEX))
         sendto_one(sptr, form_str(RPL_LINKS),
                    me.name, parv[0], acptr->name, acptr->serv->up,
                    HasUmode(sptr, UMODE_SEEROUTING) ? acptr->hopcount : 0,
		    acptr->info[0] ? acptr->info : "(Unknown Location)");
      else
        {
          if(acptr->info[0])
            {
              /* kludge, you didn't see this nor am I going to admit
               * that I coded this.
               */
              p = strchr(acptr->info,']');
              if(p)
                p += 2; /* skip the nasty [IP] part */
              else
                p = acptr->info;
            }
          else
	    {
	      static char unknown[] = "(Unknown Location)";
	      p = unknown;
	    }

#ifdef SERVERHIDE
          if (strlen(acptr->name) < 6 || strcmp(".quiet", (acptr->name)+(strlen(acptr->name)-6)) || strcmp(".local", (acptr->name)+(strlen(acptr->name)-6)) || HasUmode(sptr,UMODE_SEEROUTING))
            sendto_one(sptr, form_str(RPL_LINKS),
                      me.name, parv[0], acptr->name, HasUmode(sptr,UMODE_SEEROUTING) ? acptr->serv->up : NETWORK_NAME,
                       0, p);
#else
          sendto_one(sptr, form_str(RPL_LINKS),
                    me.name, parv[0], acptr->name, acptr->serv->up,
                    acptr->hopcount, p);
#endif
        }

    }
  
  sendto_one(sptr, form_str(RPL_ENDOFLINKS), me.name, parv[0],
             EmptyString(mask) ? "*" : mask);
  return 0;
}
Exemple #13
0
static void mo_links(struct Client *client_p, struct Client *source_p,
                    int parc, char *parv[])
{
  char*    mask = "";
  struct Client* target_p;
  char           clean_mask[2 * HOSTLEN + 4];
  char*          p;
  struct hook_links_data hd;
  
  dlink_node *ptr;

  if (parc > 2)
    {
      if (hunt_server(client_p, source_p, ":%s LINKS %s :%s", 1, parc, parv)
          != HUNTED_ISME)
        return;
      mask = parv[2];
    }
  else if (parc == 2)
    mask = parv[1];

  assert(0 != mask);

  if (*mask)       /* only necessary if there is a mask */
    mask = collapse(clean_string(clean_mask, (const unsigned char*) mask, 2 * HOSTLEN));

  hd.client_p = client_p;
  hd.source_p = source_p;
  hd.mask = mask;
  hd.parc = parc;
  hd.parv = parv;
  
  hook_call_event("doing_links", &hd);
  
  for (ptr = global_serv_list.head; ptr; ptr = ptr->next)
    {
      target_p = ptr->data;

      if (*mask && !match(mask, target_p->name))
        continue;
    
      if(target_p->info[0])
        {
          if( (p = strchr(target_p->info,']')) )
            p += 2; /* skip the nasty [IP] part */
          else
            p = target_p->info;
        } 
      else
        p = "(Unknown Location)";

     /* We just send the reply, as if theyre here theres either no SHIDE,
      * or theyre an oper..  
      */
      sendto_one(source_p, form_str(RPL_LINKS),
		      me.name, parv[0], target_p->name, target_p->serv->up,
                      target_p->hopcount, p);
    }
  
  sendto_one(source_p, form_str(RPL_ENDOFLINKS), me.name, parv[0],
             EmptyString(mask) ? "*" : mask);
}