Пример #1
0
static boolean minFreqFail(struct vcfRecord *record, double minFreq)
/* Return TRUE if record's INFO include AF (alternate allele frequencies) or AC+AN
 * (alternate allele counts and total count of observed alleles) and the minor allele
 * frequency < minFreq -- or rather, major allele frequency > (1 - minFreq) because
 * variants with > 2 alleles might have some significant minor frequencies along with
 * tiny minor frequencies). */
{
struct vcfFile *vcff = record->file;
boolean gotInfo = FALSE;
double refFreq = 1.0;
double maxAltFreq = 0.0;
int i;
const struct vcfInfoElement *afEl = vcfRecordFindInfo(record, "AF");
const struct vcfInfoDef *afDef = vcfInfoDefForKey(vcff, "AF");
if (afEl != NULL && afDef != NULL && afDef->type == vcfInfoFloat)
    {
    // If INFO includes alt allele freqs, use them directly.
    gotInfo = TRUE;
    for (i = 0;  i < afEl->count;  i++)
	{
	if (afEl->missingData[i])
	    continue;
	double altFreq = afEl->values[i].datFloat;
	refFreq -= altFreq;
	if (altFreq > maxAltFreq)
	    maxAltFreq = altFreq;
	}
    }
else
    {
    // Calculate alternate allele freqs from AC and AN:
    const struct vcfInfoElement *acEl = vcfRecordFindInfo(record, "AC");
    const struct vcfInfoDef *acDef = vcfInfoDefForKey(vcff, "AC");
    const struct vcfInfoElement *anEl = vcfRecordFindInfo(record, "AN");
    const struct vcfInfoDef *anDef = vcfInfoDefForKey(vcff, "AN");
    if (acEl != NULL && acDef != NULL && acDef->type == vcfInfoInteger &&
	anEl != NULL && anDef != NULL && anDef->type == vcfInfoInteger && anEl->count == 1 &&
	anEl->missingData[0] == FALSE)
	{
	gotInfo = TRUE;
	int totalCount = anEl->values[0].datInt;
	for (i = 0;  i < acEl->count;  i++)
	    {
	    if (acEl->missingData[i])
		continue;
	    int altCount = acEl->values[i].datInt;
	    double altFreq = (double)altCount / totalCount;
	    refFreq -= altFreq;
	    if (altFreq < maxAltFreq)
		maxAltFreq = altFreq;
	    }
	}
    else
        // Use MAF for alternate allele freqs from MAF:
        {
        const struct vcfInfoElement *mafEl = vcfRecordFindInfo(record, "MAF");
        const struct vcfInfoDef *mafDef = vcfInfoDefForKey(vcff, "MAF");
        if (mafEl != NULL && mafDef != NULL && mafDef->type == vcfInfoString
        && startsWith("Minor Allele Frequency",mafDef->description))
            {
            // If INFO includes alt allele freqs, use them directly.
            gotInfo = TRUE;

            if (mafEl->count >= 1 && !mafEl->missingData[mafEl->count-1])
                {
                char data[64];
                safecpy(data,sizeof(data),mafEl->values[mafEl->count-1].datString);
                maxAltFreq = atof(lastWordInLine(data));
                refFreq -= maxAltFreq;
                }
            }
        }
    }
if (gotInfo)
    {
    double majorAlFreq = max(refFreq, maxAltFreq);
    if (majorAlFreq > (1.0 - minFreq))
	return TRUE;
    }
return FALSE;
}
Пример #2
0
void doPastedIdentifiers(struct sqlConnection *conn)
/* Process submit in paste identifiers page. */
{
char *idText = trimSpaces(cartString(cart, hgtaPastedIdentifiers));
htmlOpen("Table Browser (Input Identifiers)");
if (isNotEmpty(idText))
    {
    /* Write terms to temp file, checking whether they have matches, and
     * save temp file name. */
    boolean saveIdText = (strlen(idText) < MAX_IDTEXT);
    char *idTextForLf = saveIdText ? cloneString(idText) : idText;
    struct lineFile *lf = lineFileOnString("idText", TRUE, idTextForLf);
    char *line, *word;
    struct tempName tn;
    FILE *f;
    int totalTerms = 0, foundTerms = 0;
    struct slName* missingTerms = NULL;
    struct dyString *exampleMissingIds = dyStringNew(256);
    char *actualDb = database;
    if (sameWord(curTable, WIKI_TRACK_TABLE))
	actualDb = wikiDbName();
    struct hTableInfo *hti = maybeGetHti(actualDb, curTable, conn);
    char *idField = getIdField(actualDb, curTrack, curTable, hti);
    if (idField == NULL)
	{
	warn("Sorry, I can't tell which field of table %s to treat as the "
	     "identifier field.", curTable);
	webNewSection("Table Browser");
	cartRemove(cart, hgtaIdentifierDb);
	cartRemove(cart, hgtaIdentifierTable);
	cartRemove(cart, hgtaIdentifierFile);
	mainPageAfterOpen(conn);
	htmlClose();
	return;
	}
    struct slName *allTerms = NULL, *term;
    while (lineFileNext(lf, &line, NULL))
	{
	while ((word = nextWord(&line)) != NULL)
	    {
	    term = slNameNew(word);
	    slAddHead(&allTerms, term);
	    totalTerms++;
	    }
	}
    slReverse(&allTerms);
    lineFileClose(&lf);
    char *extraWhere = NULL;
    int maxIdsInWhere = cartUsualInt(cart, "hgt_maxIdsInWhere", DEFAULT_MAX_IDS_IN_WHERE);
    if (totalTerms > 0 && totalTerms <= maxIdsInWhere)
	extraWhere = slNameToInExpression(idField, allTerms);

    struct lm *lm = lmInit(0);
    struct hash *matchHash = getAllPossibleIds(conn, lm, idField, extraWhere);
    trashDirFile(&tn, "hgtData", "identifiers", ".key");
    f = mustOpen(tn.forCgi, "w");
    for (term = allTerms;  term != NULL;  term = term->next)
	{
	struct slName *matchList = NULL, *match;
	if (matchHash == NULL)
	    {
	    matchList = slNameNew(term->name);
	    }
	else
	    {
	    /* Support multiple alias->id mappings: */
	    char upcased[1024];
	    safecpy(upcased, sizeof(upcased), term->name);
	    touppers(upcased);
	    struct hashEl *hel = hashLookup(matchHash, upcased);
	    if (hel != NULL)
		{
		matchList = slNameNew((char *)hel->val);
		while ((hel = hashLookupNext(hel)) != NULL)
		    {
		    match = slNameNew((char *)hel->val);
		    slAddHead(&matchList, match);
		    }
		}
	    }
	if (matchList != NULL)
	    {
	    foundTerms++;
	    for (match = matchList;  match != NULL;  match = match->next)
		{
		mustWrite(f, match->name, strlen(match->name));
		mustWrite(f, "\n", 1);
		}
	    }
	else 
	    {
	    slAddHead(&missingTerms, slNameNew(term->name));
	    }
	}
    slReverse(&missingTerms);
    carefulClose(&f);
    cartSetString(cart, hgtaIdentifierDb, database);
    cartSetString(cart, hgtaIdentifierTable, curTable);
    cartSetString(cart, hgtaIdentifierFile, tn.forCgi);
    if (saveIdText)
	freez(&idTextForLf);
    else
	cartRemove(cart, hgtaPastedIdentifiers);
    int missingCount = totalTerms - foundTerms;
    if (missingCount > 0)
	{
	char *xrefTable, *aliasField;
	getXrefInfo(conn, &xrefTable, NULL, &aliasField);
	boolean xrefIsSame = xrefTable && sameString(curTable, xrefTable);
	struct tempName tn;
	trashDirFile(&tn, "hgt/missingIds", cartSessionId(cart), ".tmp");
	FILE *f = mustOpen(tn.forCgi, "w");
	int exampleCount = 0;
	for (term = missingTerms;  term != NULL;  term = term->next)
	    {
	    if (exampleCount < 10)
		{
		++exampleCount;
		dyStringPrintf(exampleMissingIds, "%s\n", term->name);
		}
	    fprintf(f, "%s\n", term->name);
	    }
	carefulClose(&f);

	dyStringPrintf(exampleMissingIds, "\n<a href=%s>Complete list of missing identifiers<a>\n", tn.forHtml);

	warn("Note: %d of the %d given identifiers have no match in "
	     "table %s, field %s%s%s%s%s.  "
	     "Try the \"describe table schema\" button for more "
	     "information about the table and field.\n"
	     "%d %smissing identifier(s):\n"
	     "%s\n",
	     (totalTerms - foundTerms), totalTerms,
	     curTable, idField,
	     (xrefTable ? (xrefIsSame ? "" : " or in alias table ") : ""),
	     (xrefTable ? (xrefIsSame ? "" : xrefTable) : ""),
	     (xrefTable ? (xrefIsSame ? " or in field " : ", field ") : ""),
	     (xrefTable ? aliasField : ""),
	     exampleCount,
	     exampleCount < missingCount ? "example " : "",
	     exampleMissingIds->string
	    );
	webNewSection("Table Browser");
	}
    lmCleanup(&lm);
    hashFree(&matchHash);
    }
else
    {
    cartRemove(cart, hgtaIdentifierFile);
    }
mainPageAfterOpen(conn);
htmlClose();
}
Пример #3
0
void regChromiaMergeWindows(char *input, char *output)
/* regChromiaMergeWindows - Merge adjacent identically labeled windows in BED file generated 
 * by Chromia.. */
{
struct lineFile *lf = lineFileOpen(input, TRUE);
char *row[32];
int rowSize = 0;
FILE *f = mustOpen(output, "w");
char lastLabel[128];
lastLabel[0] = 0;
char lastChrom[128];
lastChrom[0] = 0;
int lastChromStart = 0, lastChromEnd = 0;
int regionStart = 0, regionEnd = 0;
double sumOfScores = 0.0;

for (;;)
    {
    /* Get next line chopped into words.  Break at end of file. Check to make sure
     * all lines have same number of words. */
    int thisRowSize = lineFileChop(lf, row);
    if (thisRowSize == 0)
        break;
    if (rowSize == 0)
        rowSize = thisRowSize;
    else if (rowSize != thisRowSize)
        {
	errAbort("First line of %s has %d words, but there are %d words in line %d",
		lf->fileName, rowSize, thisRowSize, lf->lineIx);
	}

    /* Convert row into local variables. */
    char *chrom = row[0];
    int chromStart = lineFileNeedNum(lf, row, 1);
    int chromEnd = lineFileNeedNum(lf, row, 2);
    char *label = row[labelColumn];
    double score = lineFileNeedDouble(lf, row, scoreColumn);
    
    /* Make sure file is sorted with no overlap.*/
    if (sameString(chrom, lastChrom))
        {
	int gapSize = chromStart - lastChromEnd;
	if (gapSize < 0)
	    {
	    if (chromStart < lastChromStart)
		errAbort("%s is not sorted. %s %d %d followed by %s %d %d line %d",
		    lf->fileName, lastChrom, lastChromStart, lastChromEnd,
		    chrom, chromStart, chromEnd, lf->lineIx);
	    else  
		errAbort("%s has overlaps. %s %d %d followed by %s %d %d line %d",
		    lf->fileName, lastChrom, lastChromStart, lastChromEnd,
		    chrom, chromStart, chromEnd, lf->lineIx);
	    }
	}

    /* Subtract noise threshold from score, and if not still positive just ignore line. */
    score -= inNoiseThreshold;
    if (score > 0)
	{
	/* See if we have entered a new region. */
	boolean newRegion = FALSE;
	if (sameString(chrom, lastChrom))
	    {
	    int gapSize = chromStart - lastChromEnd;
	    if (gapSize > maxGap)
		 newRegion = TRUE;
	    }
	else
	    newRegion = TRUE;
	if (!sameString(label, lastLabel))
	    newRegion = TRUE;
	    
	/* Got new region.  Output old region if any, and initialize new region. */
	if (newRegion)
	    {
	    if (regionStart != regionEnd)
		outputRegion(f, lastChrom, regionStart, regionEnd, lastLabel, sumOfScores);
	    regionStart = chromStart;
	    sumOfScores = 0;
	    }

	/* Update region. */
	regionEnd = chromEnd;
	sumOfScores += score;

	/* Keep track of this row so can compare it to next row. */
	safecpy(lastChrom, sizeof(lastChrom), chrom);
	safecpy(lastLabel, sizeof(lastLabel), label);
	lastChromStart = chromStart;
	lastChromEnd = chromEnd;
	}

    }
outputRegion(f, lastChrom, regionStart, regionEnd, lastLabel, sumOfScores);
carefulClose(&f);
lineFileClose(&lf);
}
Пример #4
0
Файл: vcf.c Проект: bh0085/kent
void vcfParseGenotypes(struct vcfRecord *record)
/* Translate record->genotypesUnparsedStrings[] into proper struct vcfGenotype[].
 * This destroys genotypesUnparsedStrings. */
{
if (record->genotypeUnparsedStrings == NULL)
    return;
struct vcfFile *vcff = record->file;
record->genotypes = vcfFileAlloc(vcff, vcff->genotypeCount * sizeof(struct vcfGenotype));
char format[VCF_MAX_FORMAT_LEN];
safecpy(format, sizeof(format), record->format);
char *formatWords[VCF_MAX_FORMAT];
int formatWordCount = chopByChar(format, ':', formatWords, ArraySize(formatWords));
if (formatWordCount >= VCF_MAX_FORMAT)
    {
    vcfFileErr(vcff, "The FORMAT column has at least %d words; "
	       "VCF_MAX_FORMAT may need to be increased in vcf.c!", VCF_MAX_FORMAT);
    formatWordCount = VCF_MAX_FORMAT;
    }
if (differentString(formatWords[0], vcfGtGenotype))
    vcfFileErr(vcff, "FORMAT column should begin with \"%s\" but begins with \"%s\"",
	       vcfGtGenotype, formatWords[0]);
int i;
// Store the pooled format word pointers and associated types for use in inner loop below.
enum vcfInfoType formatTypes[VCF_MAX_FORMAT];
for (i = 0;  i < formatWordCount;  i++)
    {
    formatTypes[i] = typeForGtFormat(vcff, formatWords[i]);
    formatWords[i] = vcfFilePooledStr(vcff, formatWords[i]);
    }
for (i = 0;  i < vcff->genotypeCount;  i++)
    {
    char *string = record->genotypeUnparsedStrings[i];
    struct vcfGenotype *gt = &(record->genotypes[i]);
    // Each genotype can have multiple :-separated info elements:
    char *gtWords[VCF_MAX_FORMAT];
    int gtWordCount = chopByChar(string, ':', gtWords, ArraySize(gtWords));
    if (gtWordCount != formatWordCount)
	vcfFileErr(vcff, "The FORMAT column has %d words but the genotype column for %s "
		   "has %d words", formatWordCount, vcff->genotypeIds[i], gtWordCount);
    if (gtWordCount > formatWordCount)
	gtWordCount = formatWordCount;
    gt->id = vcff->genotypeIds[i];
    gt->infoCount = gtWordCount;
    gt->infoElements = vcfFileAlloc(vcff, gtWordCount * sizeof(struct vcfInfoElement));
    int j;
    for (j = 0;  j < gtWordCount;  j++)
	{
	// Special parsing of genotype:
	if (sameString(formatWords[j], vcfGtGenotype))
	    {
	    char *genotype = gtWords[j];
	    char *sep = strchr(genotype, '|');
	    if (sep != NULL)
		gt->isPhased = TRUE;
	    else
		sep = strchr(genotype, '/');
	    gt->hapIxA = atoi(genotype);
	    if (sep == NULL)
		gt->isHaploid = TRUE;
	    else
		gt->hapIxB = atoi(sep+1);
	    }
	struct vcfInfoElement *el = &(gt->infoElements[j]);
	el->key = formatWords[j];
	el->count = parseInfoValue(record, formatWords[j], formatTypes[j], gtWords[j],
				   &(el->values));
	if (el->count >= VCF_MAX_INFO)
	    vcfFileErr(vcff, "A single element of the genotype column for \"%s\" "
		       "has at least %d values; "
		       "VCF_MAX_INFO may need to be increased in vcf.c!",
		       gt->id, VCF_MAX_INFO);
	}
    }
record->genotypeUnparsedStrings = NULL;
}
Пример #5
0
/*----------------------------------------------------------------------*/
int daf_service_install(char *daf_binary_path, char *argv0)
{

    char cmd[1024];
    char msg[1024];
    char daf_path[64];
    char daf_binary_to_install[64];
    char timestamp[16];
    char backup_inittab_filename[64];

    struct stat fileStat;
    char *pathname = "/etc/inittab";

    if (daf_binary_path == NULL)
    {
        if (get_current_executable_path(argv0, daf_binary_to_install, sizeof(daf_binary_to_install)) !=0)
        {
            print_msg_to_console("Problem trying to determine path of current executable\n");
            return(1);
        }
    }
    else
    {
        safecpy(daf_binary_to_install, daf_binary_path, sizeof(daf_binary_to_install));
    }

    // ensure that directories that are needed do actually exist and delelete existing profile
    // and start up script

    ensure_directory_path_exists(DAF_SERVICE_BINARY_DIR);
    ensure_directory_path_exists(DAF_SERVICE_LOG_DIR);
    delete_file(DAF_SERVICE_START_SCRIPT_PATH);
    delete_file(DAF_SERVICE_PROFILE_PATH);

    // are we trying to copy the same file onto itself, -if so then
    // do not do the copy as it it will fail
    if (strcmp(daf_binary_to_install, DAF_SERVICE_BINARY_PATH) == 0)
    {

        sprintf(msg, "Requested install image %s is identical to install destination: %s\n",
                daf_binary_to_install, DAF_SERVICE_BINARY_PATH);
        print_msg_to_console(msg);

    }
    else
    {

        if (copy_file(daf_binary_to_install, DAF_SERVICE_BINARY_PATH) != 0)
        {
            /* make sure the SETuid bit is on so that daf can assume root priviledges if it is run by a non root user */
            /* is this a security hole ?? <<<<<<<<<< */
            sprintf(msg, "Could not copy %s into installation directory at %s\n", daf_binary_to_install, DAF_SERVICE_BINARY_PATH);
            print_msg_to_console(msg);
            return(1);
        }
        else
        {
            if (chmod_file(DAF_SERVICE_BINARY_PATH, "u+s") != 0)
            {
                sprintf(msg, "Could not set setuid permission bit on %s\n", DAF_SERVICE_BINARY_PATH);
                print_msg_to_console(msg);
                return(1);
            }
        }

    }

    if (create_default_daf_service_profile() != 0)
    {
        print_msg_to_console("Could not install command profile into standard daf service directory\n");
        return(1);
    }
    else
    {
        print_msg_to_console("daf service command profile installed successfully\n");
    }


    if (create_daf_service_start_script() != 0)
    {
        print_msg_to_console("Could not install start script into standard daf service directory\n");
        return(1);
    }
    else
    {
        print_msg_to_console("daf service start script installed successfully\n");
    }

    //--------------------------------------------------------------------------
    //
    //--------------------------------------------------------------------------

    safecpy(daf_path, DAF_SERVICE_BINARY_PATH, sizeof(daf_path));

    if (is_daf_service_running())
    {
        print_msg_to_console("daf daemon is running - and will now be stopped\n");

        if (stop_daf_service_running() != 0)
        {
            print_msg_to_console("Problem trying to stop daf daemon\n");
        }
    }

    print_msg_to_console("Updating /etc/inittab entry\n");

#if defined AIX

    //--------------------------------------------------------------------------
    // remove any previous entry
    //--------------------------------------------------------------------------

    print_msg_to_console("Removing any previous daf service entry in /etc/inittab\n");
    safecpy(cmd, "cat /etc/inittab | grep \"daf:\"", sizeof(cmd));

    if (run_system_cmd(cmd, 1) == 0)
    {

        safecpy(cmd, "rmitab \"daf\"", sizeof(cmd));

        if (run_system_cmd_and_print_all_output(cmd) != 0)
        {
            safecpy(msg, "Removal of daf service entry in /etc/inittab failed: ", sizeof(msg));
            safecat(msg, cmd, sizeof(msg));
            safecat(msg, "\n", sizeof(msg));
            print_msg_to_console(msg);
            return(1);
        }
    }

    //--------------------------------------------------------------------------
    // Add daf daemon to /etc/inittab
    //--------------------------------------------------------------------------

    safecpy(backup_inittab_filename, "/etc/inittab.", sizeof(backup_inittab_filename));
    get_current_time_as_timestamp(timestamp, sizeof(timestamp), '.');
    safecat(backup_inittab_filename, timestamp, sizeof(backup_inittab_filename));
    sprintf(msg, "Backing up /etc/inittab in %s\n", backup_inittab_filename);
    print_msg_to_console(msg);

    if (copy_file("/etc/inittab", backup_inittab_filename) != 0)
    {
        safecpy(msg, "Backup of inittab failed: ", sizeof(msg));
        safecat(msg, "Could not copy /etc/inittab to %s", backup_inittabl_filename, sizeof(msg));
        print_msg_to_console(msg);
        return(1);
    }

    print_msg_to_console("Adding daf service entry to /etc/inittab\n");

    safecpy(cmd, "mkitab \"daf:2:once:", sizeof(cmd));
    safecat(cmd, DAF_SERVICE_INVOCATION, sizeof(cmd));
    safecat(cmd, " >/dev/null 2>&1", sizeof(cmd));
    safecat(cmd, "\"", sizeof(cmd));

    if (run_system_cmd_and_print_all_output(cmd) != 0)
    {
        safecpy(msg, "Update of inittab failed: ", sizeof(msg));
        safecat(msg, cmd, sizeof(msg));
        safecat(msg, "\n", sizeof(msg));
        print_msg_to_console(msg);
        return(1);
    }

#elif defined LINUX || defined SOLARIS || defined HPUX

    //--------------------------------------------------------------------------
    // Add daf daemon to /etc/inittab
    // First check to see if /etc/inittab exists - if it does not this may be
    // Debian or Ubuntu in which case we must create an empty file
    // (Debian/Ubuntu use the Startup mechanism instead of /etc/inittab but
    // still support the old /etc/inittab file it is present
    // see for instance:  http://upstart.ubuntu.com/cookbook/
    //--------------------------------------------------------------------------

    if (!does_file_exist("/etc/inittab"))
    {
        sprintf(msg, "/etc/inittab did not exist - assuming Debian/Ubuntu - so creating /etc/init entry\n");
        print_msg_to_console(msg);
        create_etc_init_conf();
        return(0);
    }

    if (stat(pathname, &fileStat) < 0)
    {

        sprintf(msg, "stat(%s) failed - it seems %s is missing !!!!!!!!!!!!!!!!!!!!! \n", pathname, pathname );
        print_msg_to_console(msg);
        return(1);
    }

    // Later versions of Redhat etc do not use /etc/inittab (but will still honour it if exists - so if the file is empty,
    // we just put a single comment line into so that later code that updates the /etc/inittab file will work
    if (fileStat.st_size == 0)
    {

        if (run_system_cmd("cat '* just a comment' >>/etc/inittab", 0) != 0)
        {
            safecpy(msg, "cat \"* just a comment\" >>/etc/inittab failed\n", sizeof(msg));
            print_msg_to_console(msg);
            return(1);
        }
    }

    //--------------------------------------------------------------------------
    // remove any previous entry, making sure we backup /etc/inittab
    //--------------------------------------------------------------------------

    safecpy(backup_inittab_filename, "/etc/inittab.", sizeof(backup_inittab_filename));
    get_current_time_as_timestamp(timestamp, sizeof(timestamp), '.');
    safecat(backup_inittab_filename, timestamp, sizeof(backup_inittab_filename));
    sprintf(msg, "Backing up /etc/inittab in %s\n", backup_inittab_filename);
    print_msg_to_console(msg);
    print_msg_to_console("Removing any previous daf service entry in /etc/inittab\n");

    if (copy_file("/etc/inittab", backup_inittab_filename) != 0)
    {
        snprintf(msg, sizeof(msg), "Copy of /etc/inittab to %s failed\n", backup_inittab_filename);
        print_msg_to_console(msg);
        return(1);
    }

    safecpy(cmd, "cat ", sizeof(cmd));
    safecat(cmd, backup_inittab_filename, sizeof(cmd));
    safecat(cmd, " | grep -v \""DAF_SERVICE_INVOCATION"\" > /etc/inittab", sizeof(cmd));

    if (run_system_cmd(cmd, 0) != 0)
    {
        safecpy(msg, "Removal of previous daf service in inittab failed: ", sizeof(msg));
        safecat(msg, cmd, sizeof(msg));
        safecat(msg, "\n", sizeof(msg));
        print_msg_to_console(msg);
        return(1);
    }

    safecpy(cmd, "cat ", sizeof(cmd));
    safecat(cmd, backup_inittab_filename, sizeof(cmd));
    safecat(cmd, " | grep -v \""DAF_SERVICE_INVOCATION"\" > /etc/inittab", sizeof(cmd));

    if (run_system_cmd(cmd, 0) != 0)
    {
        safecpy(msg, "Removal of previous daf service in inittab failed: ", sizeof(msg));
        safecat(msg, cmd, sizeof(msg));
        safecat(msg, "\n", sizeof(msg));
        print_msg_to_console(msg);
        return(1);
    }

    //--------------------------------------------------------------------------
    // Add daf daemon to /etc/inittab
    //--------------------------------------------------------------------------

    print_msg_to_console("Adding daf service entry to /etc/inittab\n");

    safecpy(cmd, "echo \"daf:345:once:", sizeof(msg));
    safecat(cmd, DAF_SERVICE_INVOCATION, sizeof(cmd));
    safecat(cmd, " \" 2>/dev/null >>/etc/inittab", sizeof(cmd));

    if (run_system_cmd(cmd, 0) != 0)
    {
        safecpy(msg, "Adding daf service entry to /etc/inittab: ", sizeof(msg));
        safecat(msg, cmd, sizeof(msg));
        safecat(msg, "\n", sizeof(msg));
        print_msg_to_console(msg);
        return(1);
    }

#endif

    print_msg_to_console("/etc/inittab entry updated successfully\n");

    return(0);

}
Пример #6
0
/*----------------------------------------------------------------------*/
int daf_service_delete(void)
{

    char cmd[1024];
    char msg[1024];
    char timestamp[16];
    char backup_inittab_filename[64];

#if defined AIX

    print_msg_to_console("Updating /etc/inittab entry\n");

    //--------------------------------------------------------------------------
    // remove any previous entry
    //--------------------------------------------------------------------------

    safecpy(backup_inittab_filename, "/etc/inittab.", sizeof(backup_inittab_filename));
    get_current_time_as_timestamp(timestamp, sizeof(timestamp), '.');
    safecat(backup_inittab_filename, timestamp, sizeof(backup_inittab_filename));
    sprintf(msg, "Backing up /etc/inittab in %s\n", backup_inittab_filename);
    print_msg_to_console(msg);

    if (copy_file("/etc/inittab", backup_inittab_filename) != 0)
    {
        safecpy(msg, "Backup of inittab failed: ", sizeof(msg));
        safecat(msg, cmd, sizeof(msg));
        safecat(msg, "\n", sizeof(msg));
        print_msg_to_console(msg);
        return(1);
    }

    print_msg_to_console("  Removing any previous daf service entry in /etc/inittab\n");
    safecpy(cmd, "cat /etc/inittab | grep \"daf:\"", sizeof(cmd));

    if (run_system_cmd(cmd, 1) == 0)
    {

        safecpy(cmd, "rmitab \"daf\"", sizeof(cmd));

        if (run_system_cmd_and_print_all_output(cmd) != 0)
        {
            safecpy(msg, "Removal of daf service entry in /etc/inittab failed: ", sizeof(msg));
            safecat(msg, cmd, sizeof(msg));
            safecat(msg, "\n", sizeof(msg));
            print_msg_to_console(msg);
            return(1);
        }

    }
    else
    {
        safecpy(msg, "No daf entry found in /etc/inittab so none was removed\n", sizeof(msg));
        print_msg_to_console(msg);
    }

    print_msg_to_console("/etc/inittab entry updated successfully\n");

#elif defined LINUX || defined SOLARIS || defined HPUX

    //--------------------------------------------------------------------------
    // remove any previous entry
    //--------------------------------------------------------------------------

    // This could be Debian/Ubuntu and could be before we have installed DAF so there might not
    // be a /etc/inittab file existing yet - check for this

    if (! does_file_exist("/etc/inittab"))
    {

        if (does_file_exist(DAF_DEBIAN_ETC_INIT_CONF_PATH))
        {
            safecpy(cmd, "rm " DAF_DEBIAN_ETC_INIT_CONF_PATH, sizeof(cmd));

            if (run_system_cmd(cmd, 1) != 0)
            {
                safecpy(msg, "Removal of " DAF_DEBIAN_ETC_INIT_CONF_PATH " failed\n", sizeof(msg));
                print_msg_to_console(msg);
                return(1);
            }
        }

        print_msg_to_console(DAF_DEBIAN_ETC_INIT_CONF_PATH " removed\n");

    }
    else
    {

        print_msg_to_console("Updating /etc/inittab entry\n");

        safecpy(backup_inittab_filename, "/etc/inittab.", sizeof(backup_inittab_filename));
        get_current_time_as_timestamp(timestamp, sizeof(timestamp), '.');
        safecat(backup_inittab_filename, timestamp, sizeof(backup_inittab_filename));
        sprintf(msg, "Backing up /etc/inittab in %s\n", backup_inittab_filename);
        print_msg_to_console(msg);

        if (copy_file ("/etc/inittab", backup_inittab_filename) != 0)
        {
            safecpy(msg, "Backup of inittab failed: ", sizeof(msg));
            safecat(msg, cmd, sizeof(msg));
            safecat(msg, "\n", sizeof(msg));
            print_msg_to_console(msg);
            return(1);
        }

        print_msg_to_console("  Removing any previous daf service entry in /etc/inittab\n");
        safecpy(cmd, "cat ", sizeof(cmd));
        safecat(cmd, backup_inittab_filename, sizeof(cmd));
        safecat(cmd, " | grep -v \""DAF_SERVICE_INVOCATION"\" > /etc/inittab", sizeof(cmd));

        if (run_system_cmd(cmd, 0) != 0)
        {
            safecpy(msg, "Removal of previous daf service in inittab failed: ", sizeof(msg));
            safecat(msg, cmd, sizeof(msg));
            safecat(msg, "\n", sizeof(msg));
            print_msg_to_console(msg);
            return(1);
        }

        print_msg_to_console("/etc/inittab entry updated successfully\n");
    }


#endif

    if (is_daf_service_running())
    {
        print_msg_to_console("daf daemon is running - and will now be stopped\n");

        if (stop_daf_service_running() != 0)
        {
            print_msg_to_console("Problem trying to stop daf daemon\n");
        }
    }

    return(0);

}
Пример #7
0
int clear_cmd_array(char *errmsg, int max_msg_length)
{

#undef  SUBNAME
#define SUBNAME "clear_cmd_array"

    char                  msg[MAX_MSG_LEN];
    char                  agent_log_pathname[MAX_PATHNAME_LEN];
    shm_daf_t   *p;
    int                   i;
    char                  thishostname[MAX_HOSTNAME_LEN];

    if (errmsg != NULL)
    {
        errmsg[0] = 0;
    }

    if ((p = query_shared_segment_process_pointer()) == NULL)
    {
        sprintf(msg, "%s: query_shared_segement_process_pointer() returned p = NULL - continuing", SUBNAME);

        if (errmsg != NULL)
        {
            safecpy(errmsg, msg, max_msg_length);
        }

        return(1);
    }

    /* what about stale processes see above <<<<<<<<<<<<<<<<<<< */

    get_short_hostname(thishostname, sizeof(thishostname));



    // -------------------------------------------------------------
    // -------------------------------------------------------------

    for (i=0; i<DAF_MAX_COMMANDS; i++)
    {

        if (p->service_cmd_log_object.cmd_array[i].state == CMD_COMPLETED )
        {
            safecpy(p->service_cmd_log_object.cmd_array[i].cmdstring,   "", sizeof(p->service_cmd_log_object.cmd_array[i].cmdstring));
            safecpy(p->service_cmd_log_object.cmd_array[i].identstring, "", sizeof(p->service_cmd_log_object.cmd_array[i].identstring));
            safecpy(p->service_cmd_log_object.cmd_array[i].agent_log_pathname, agent_log_pathname,
                    sizeof(p->service_cmd_log_object.cmd_array[i].agent_log_pathname));
            p->service_cmd_log_object.cmd_array[i].state       = CMD_FREE;
            p->service_cmd_log_object.cmd_array[i].status      = 0;
            p->service_cmd_log_object.cmd_array[i].start_time  = 0;
            p->service_cmd_log_object.cmd_array[i].end_time    = 0;
            p->service_cmd_log_object.cmd_array[i].tag         = 0;
            p->service_cmd_log_object.cmd_array[i].pid         = 0;
            p->service_cmd_log_object.cmd_array[i].workqueueID = 0;
        }

    }

    return(0);

}
Пример #8
0
void
mschap(Ticketreq *tr)
{

	char *secret, *hkey;
	char sbuf[SECRETLEN], hbuf[DESKEYLEN];
	uchar chal[CHALLEN];
	uchar hash[MShashlen];
	uchar hash2[MShashlen];
	uchar resp[MSresplen];
	OMSchapreply reply;
	int dupe, lmok, ntok;
	DigestState *s;
	uchar digest[SHA1dlen];

	/*
	 *  Create a challenge and send it.
	 */
	randombytes((uchar*)chal, sizeof(chal));
	write(1, chal, sizeof(chal));

	/*
	 *  get chap reply
	 */
	if(readn(0, &reply, sizeof(reply)) < 0)
		exits(0);

	safecpy(tr->uid, reply.uid, sizeof(tr->uid));
	/*
	 * lookup
	 */
	secret = findsecret(KEYDB, tr->uid, sbuf);
	hkey = findkey(KEYDB, tr->hostid, hbuf);
	if(hkey == 0 || secret == 0){
		replyerror("mschap-fail bad response %s/%s(%s)",
			tr->uid, tr->hostid, raddr);
		logfail(tr->uid);
		exits(0);
	}

	lmhash(hash, secret);
	mschalresp(resp, hash, chal);
	lmok = memcmp(resp, reply.LMresp, MSresplen) == 0;
	nthash(hash, secret);
	mschalresp(resp, hash, chal);
	ntok = memcmp(resp, reply.NTresp, MSresplen) == 0;
	dupe = memcmp(reply.LMresp, reply.NTresp, MSresplen) == 0;

	/*
	 * It is valid to send the same response in both the LM and NTLM 
	 * fields provided one of them is correct, if neither matches,
	 * or the two fields are different and either fails to match, 
	 * the whole sha-bang fails.
	 *
	 * This is an improvement in security as it allows clients who
	 * wish to do NTLM auth (which is insecure) not to send
	 * LM tokens (which is very insecure).
	 *
	 * Windows servers supports clients doing this also though
	 * windows clients don't seem to use the feature.
	 */
	if((!ntok && !lmok) || ((!ntok || !lmok) && !dupe)){
		replyerror("mschap-fail bad response %s/%s(%s) %d,%d,%d",
			tr->uid, tr->hostid, raddr, dupe, lmok, ntok);
		logfail(tr->uid);
		exits(0);
	}

	succeed(tr->uid);

	/*
	 *  reply with ticket & authenticator
	 */
	if(tickauthreply(tr, hkey) < 0)
		exits(0);

	if(debug)
		replyerror("mschap-ok %s/%s(%s) %ux",
			tr->uid, tr->hostid, raddr);

	nthash(hash, secret);
	md4(hash, 16, hash2, 0);
	s = sha1(hash2, 16, 0, 0);
	sha1(hash2, 16, 0, s);
	sha1(chal, 8, digest, s);

	if(write(1, digest, 16) < 0)
		exits(0);
}
Пример #9
0
static void wikiTrackLoadItems(struct track *tg)
/* Load the items from the wikiTrack table */
{
struct bed *bed;
struct sqlConnection *wikiConn = wikiConnect();
struct sqlResult *sr;
char **row;
int rowOffset;
char where[256];
struct linkedFeatures *lfList = NULL, *lf;
int scoreMin = 0;
int scoreMax = 99999;

safef(where, ArraySize(where), "db='%s'", database);

sr = hRangeQuery(wikiConn, tg->table, chromName, winStart, winEnd, where, &rowOffset);
while ((row = sqlNextRow(sr)) != NULL)
    {
    struct wikiTrack *item = wikiTrackLoad(row);
    AllocVar(bed);
    bed->chrom = cloneString(item->chrom);
    bed->chromStart = item->chromStart;
    bed->chromEnd = item->chromEnd;
    bed->name = cloneString(item->name);
    bed->score = item->score;
    safecpy(bed->strand, sizeof(bed->strand), item->strand);
    bed->thickStart = item->chromStart;
    bed->thickEnd = item->chromEnd;
    bed->itemRgb = hexToDecimal(item->color);
    bed8To12(bed);
    lf = lfFromBedExtra(bed, scoreMin, scoreMax);
    lf->extra = (void *)USE_ITEM_RGB;	/* signal for coloring */
    lf->filterColor=bed->itemRgb;

    /* overload itemAttr fields to be able to pass id to hgc click box */
    struct itemAttr *id;
    AllocVar(id);
    id->chromStart = item->id;
    lf->itemAttr = id;
    slAddHead(&lfList, lf);
    wikiTrackFree(&item);
    }
sqlFreeResult(&sr);
wikiDisconnect(&wikiConn);

slSort(&lfList, linkedFeaturesCmp);

/* read-only option 2012-06-25 */
if ((! wikiTrackReadOnly()) && wikiTrackEnabled(database, NULL))
    {
    // add special item to allow creation of new entries
    AllocVar(bed);
    bed->chrom = chromName;
    bed->chromStart = winStart;
    bed->chromEnd = winEnd;
    bed->name = cloneString("Make new entry");
    bed->score = 100;
    bed->strand[0] = ' ';  /* no barbs when strand is unknown */
    bed->thickStart = winStart;
    bed->thickEnd = winEnd;
    bed->itemRgb = 0xcc0000;
    bed8To12(bed);
    lf = lfFromBedExtra(bed, scoreMin, scoreMax);
    lf->extra = (void *)USE_ITEM_RGB;	/* signal for coloring */
    lf->filterColor=bed->itemRgb;
    slAddHead(&lfList, lf);
    }

tg->items = lfList;
}	/*	static void wikiTrackLoadItems(struct track *tg)	*/
Пример #10
0
int initialise_shared_segment(char *statusmsg,
                              char *errmsg,
                              int  max_msg_length)
{

#undef  SUBNAME
#define SUBNAME "initialise_shared_segment"

    key_t              key;
    int                shmid;
    struct             shmid_ds shm_buf;
    size_t             current_size_shm;
    size_t             size_shm;
    size_t             full_size_shm;
    int                just_created = 0;
    char               msg[MAX_MSG_LEN]    = "";
    shm_daf_t *p;

    memset(&shm_buf, 0, sizeof(shm_buf));
    errmsg[0]    = 0;
    statusmsg[0] = 0;

    /* ------------------------------------------------------------- */
    /* make the key:                                                 */
    /* ------------------------------------------------------------- */

    if ((key = ftok("/tmp", 'S' )) == -1)
    {
        sprintf(msg, "%s: Could not create key for shared memory acess error=%d %s", SUBNAME, errno, strerror(errno));
        safecpy(errmsg, msg, max_msg_length);
        return(1);
    }

    /* --------------------------------------------------------------------------------- */
    /* we are actually going to create the memory size somewhat larger than needed       */
    // to allow for future expansion.
    /* --------------------------------------------------------------------------------- */

    full_size_shm = SIZE_shm_daf_BYTES;
    size_shm      = sizeof(shm_daf_t);

    if (size_shm > full_size_shm)
    {
        sprintf(msg, "%s: internal error size_shm > full_size_shm (%d > %d)\n",
                SUBNAME, (int)size_shm, (int)full_size_shm);
        safecpy(errmsg, msg, max_msg_length);
        return(1);

    }

    /* --------------------------------------------------------------------------------- */
    /* See if we can connect to an existing shared memory segment                        */
    /* we try to connect to a segment and use a size of zero                             */
    /* - this should work if any size segment with the right                             */
    /* key exists, and if we can connect we can find out the real                        */
    /* size from shmctl                                                                  */
    /* --------------------------------------------------------------------------------- */

    if ((shmid = shmget(key, 0, 0644 )) == -1)
    {

        /* ------------------------------------------------------------------------------ */
        /* cannot connect - no segment present , so create a new one                      */
        /* ------------------------------------------------------------------------------ */

        if ((shmid = shmget(key, full_size_shm, 0644 | IPC_CREAT)) == -1)
        {
            sprintf(msg, "%s: errno = %d (%s): Could not create a shared memory block of size " SIZE_TSPEC,
                    SUBNAME, errno, strerror(errno), (int)full_size_shm);
            safecpy(errmsg, msg, max_msg_length);
            return(1);
        }
        else
        {
            just_created = TRUE;
            sprintf(msg, "%s: created shared memory block - id %d, size " SIZE_TSPEC,
                    SUBNAME, shmid, (int)full_size_shm);
            safecpy(errmsg, msg, max_msg_length);
        }

    }
    else
    {

        /* ------------------------------------------------------------------------------ */
        /* date structure exists already - is it the right size?                          */
        /* ------------------------------------------------------------------------------ */

        if (shmctl(shmid, IPC_STAT, &shm_buf))
        {

            sprintf(msg, "%s: INTERNAL_ERROR: could not run shmctl with IPC_STAT errno=%d (%s)",
                    SUBNAME, errno, strerror(errno));
            safecpy(errmsg, msg, max_msg_length);
            return(1);

        }
        else
        {

            current_size_shm = shm_buf.shm_segsz;

            if (current_size_shm != full_size_shm)
            {

                /* ------------------------------------------------------------------------------ */
                /* data structure exists but is wrong size, I thought it would                    */
                /* be possible to dynamicallyo resize it and                                      */
                /* treat it as a newly initialised data structure however that                    */
                /* does not seem to work so treat this is an error for the time                   */
                /* being                                                                          */
                /* ------------------------------------------------------------------------------ */

                if (shmctl(shmid, IPC_STAT, &shm_buf))
                {
                    shm_buf.shm_segsz = full_size_shm;
                    sprintf(msg, "%s: INTERNAL_ERROR: could not run shmctl with SHM_SIZE (currrent_shm_size = "
                            SIZE_TSPEC ", full_size_shm = " SIZE_TSPEC ",  errno=%d (%s)",
                            SUBNAME, (int) current_size_shm, (int)full_size_shm, errno, strerror(errno));
                    safecpy(errmsg, msg, max_msg_length);
                    return(1);
                }

                sprintf(msg, "%s: INTERNAL_ERROR: shared memory size not as expected - currrent_shm_size = "
                        SIZE_TSPEC ", desired full_size_shm = " SIZE_TSPEC "\n",
                        SUBNAME, (int) current_size_shm, (int) full_size_shm);
                safecpy(errmsg, msg, max_msg_length);
                return(1);
            }

        }
    }

    /* ------------------------------------------------------------------------------ */
    /* attach to the segment to get a pointer to it and if it is                      */
    /* a newly created segment, then initialise it to all 0s.  If                     */
    /* it is an existing segment, then check the shm_version                          */
    /* number                                                                         */
    /* ------------------------------------------------------------------------------ */

    p_shm = shmat(shmid, (void *)0, 0);

    if (p_shm == (char *)(-1))
    {
        sprintf(msg, "%s: Could not attach to shared memory block id=%d, error= %d %s", SUBNAME, shmid, errno, strerror(errno));
        safecpy(errmsg, msg, max_msg_length);
        return(1);
    }
    else
    {
        p = (shm_daf_t *)(p_shm);

        if (just_created)
        {
            initialise_shared_segment_values(NULL, 0);
        }
        else
        {
            if (p->shm_version != DAF_SHM_VERSION)
            {
                sprintf(msg, "%s: Wrong value (%d) for shm_version in shared memory at %p- should be %d - ",
                        SUBNAME, p->shm_version, p, DAF_SHM_VERSION);
                /* <<<<<<<< what to do here ??? */
                safecpy(errmsg, msg, max_msg_length);
                return(1);
            }
        }
    }

    if (just_created)
    {
        sprintf(statusmsg, "%s: A new shared memory segment was created at %p", SUBNAME, p_shm);
    }
    else
    {
        sprintf(statusmsg, "%s: An existing shared memory segment was used at %p", SUBNAME, p_shm);
    }

    return(0);

}
Пример #11
0
boolean lineFileNext(struct lineFile *lf, char **retStart, int *retSize)
/* Fetch next line from file. */
{
char *buf = lf->buf;
int bytesInBuf = lf->bytesInBuf;
int endIx = lf->lineEnd;
boolean gotLf = FALSE;
int newStart;

if (lf->reuse)
    {
    lf->reuse = FALSE;
    if (retSize != NULL)
	*retSize = lf->lineEnd - lf->lineStart;
    *retStart = buf + lf->lineStart;
    if (lf->metaOutput && *retStart[0] == '#')
        metaDataAdd(lf, *retStart);
    return TRUE;
    }

#ifdef USE_TABIX
if (lf->tabix != NULL && lf->tabixIter != NULL)
    {
    // Just use line-oriented ti_read:
    int lineSize = 0;
    const char *line = ti_read(lf->tabix, lf->tabixIter, &lineSize);
    if (line == NULL)
	return FALSE;
    lf->bufOffsetInFile = -1;
    lf->bytesInBuf = lineSize;
    lf->lineIx = -1;
    lf->lineStart = 0;
    lf->lineEnd = lineSize;
    if (lineSize > lf->bufSize)
	// shouldn't be!  but just in case:
	lineFileExpandBuf(lf, lineSize * 2);
    safecpy(lf->buf, lf->bufSize, line);
    *retStart = lf->buf;
    if (retSize != NULL)
	*retSize = lineSize;
    return TRUE;
    }
#endif // USE_TABIX

determineNlType(lf, buf+endIx, bytesInBuf);

/* Find next end of line in buffer. */
switch(lf->nlType)
    {
    case nlt_unix:
    case nlt_dos:
	for (endIx = lf->lineEnd; endIx < bytesInBuf; ++endIx)
	    {
	    if (buf[endIx] == '\n')
		{
		gotLf = TRUE;
		endIx += 1;
		break;
		}
	    }
	break;
    case nlt_mac:
	for (endIx = lf->lineEnd; endIx < bytesInBuf; ++endIx)
	    {
	    if (buf[endIx] == '\r')
		{
		gotLf = TRUE;
		endIx += 1;
		break;
		}
	    }
	break;
    case nlt_undet:
	break;
    }

/* If not in buffer read in a new buffer's worth. */
while (!gotLf)
    {
    int oldEnd = lf->lineEnd;
    int sizeLeft = bytesInBuf - oldEnd;
    int bufSize = lf->bufSize;
    int readSize = bufSize - sizeLeft;

    if (oldEnd > 0 && sizeLeft > 0)
	{
	memmove(buf, buf+oldEnd, sizeLeft);
	}
    lf->bufOffsetInFile += oldEnd;
    if (lf->fd >= 0)
	readSize = lineFileLongNetRead(lf->fd, buf+sizeLeft, readSize);
#ifdef USE_TABIX
    else if (lf->tabix != NULL && readSize > 0)
	{
	readSize = ti_bgzf_read(lf->tabix->fp, buf+sizeLeft, readSize);
	if (readSize < 1)
	    return FALSE;
	}
#endif // USE_TABIX
    else
        readSize = 0;

    if ((readSize == 0) && (endIx > oldEnd))
	{
	endIx = sizeLeft;
	buf[endIx] = 0;
	lf->bytesInBuf = newStart = lf->lineStart = 0;
	lf->lineEnd = endIx;
	++lf->lineIx;
	if (retSize != NULL)
	    *retSize = endIx - newStart;
	*retStart = buf + newStart;
        if (*retStart[0] == '#')
            metaDataAdd(lf, *retStart);
	return TRUE;
	}
    else if (readSize <= 0)
	{
	lf->bytesInBuf = lf->lineStart = lf->lineEnd = 0;
	return FALSE;
	}
    bytesInBuf = lf->bytesInBuf = readSize + sizeLeft;
    lf->lineEnd = 0;

    determineNlType(lf, buf+endIx, bytesInBuf);

    /* Look for next end of line.  */
    switch(lf->nlType)
	{
    	case nlt_unix:
	case nlt_dos:
	    for (endIx = sizeLeft; endIx <bytesInBuf; ++endIx)
		{
		if (buf[endIx] == '\n')
		    {
		    endIx += 1;
		    gotLf = TRUE;
		    break;
		    }
		}
	    break;
	case nlt_mac:
	    for (endIx = sizeLeft; endIx <bytesInBuf; ++endIx)
		{
		if (buf[endIx] == '\r')
		    {
		    endIx += 1;
		    gotLf = TRUE;
		    break;
		    }
		}
	    break;
	case nlt_undet:
	    break;
	}
    if (!gotLf && bytesInBuf == lf->bufSize)
        {
	if (bufSize >= 512*1024*1024)
	    {
	    errAbort("Line too long (more than %d chars) line %d of %s",
		lf->bufSize, lf->lineIx+1, lf->fileName);
	    }
	else
	    {
	    lineFileExpandBuf(lf, bufSize*2);
	    buf = lf->buf;
	    }
	}
    }

if (lf->zTerm)
    {
    buf[endIx-1] = 0;
    if ((lf->nlType == nlt_dos) && (buf[endIx-2]=='\r'))
	{
	buf[endIx-2] = 0;
	}
    }

lf->lineStart = newStart = lf->lineEnd;
lf->lineEnd = endIx;
++lf->lineIx;
if (retSize != NULL)
    *retSize = endIx - newStart;
*retStart = buf + newStart;
if (*retStart[0] == '#')
    metaDataAdd(lf, *retStart);
return TRUE;
}
void refreshNamedSessionCustomTracks(char *centralDbName)
/* refreshNamedSessionCustomTracks -- cron robot for keeping alive custom 
 * tracks that are referenced by saved sessions. */
{
struct sqlConnection *conn = hConnectCentral();
struct slPair *updateList = NULL, *update;
char *actualDbName = sqlGetDatabase(conn);
int liveCount=0, expiredCount=0;

setUdcCacheDir();  /* programs that use udc must call this to initialize cache dir location */

if (!sameString(centralDbName, actualDbName))
    errAbort("Central database specified in hg.conf file is %s but %s "
	     "was specified on the command line.",
	     actualDbName, centralDbName);
else
    verbose(2, "Got connection to %s\n", centralDbName);

long long threshold = 0;
int atime = optionInt("atime", 0);
if (atime > 0)
    {
    time_t now = time(NULL);
    threshold = now - ((long long)atime * 24 * 60 * 60);
    }

if (sqlTableExists(conn, savedSessionTable))
    {
    struct sessionInfo *sessionList = NULL, *si;
    struct sqlResult *sr = NULL;
    char **row = NULL;
    char query[512];
    safef(query, sizeof(query),
	  "select userName,sessionName,UNIX_TIMESTAMP(lastUse),contents from %s "
	  "order by userName,sessionName", savedSessionTable);
    sr = sqlGetResult(conn, query);
    // Slurp results into memory instead of processing row by row,
    // reducing the chance of lost connection.
    while ((row = sqlNextRow(sr)) != NULL)
	{
	if (atime > 0)
	    {
	    long long lastUse = atoll(row[2]);
	    if (lastUse < threshold)
		{
		verbose(2, "User %s session %s is older than %d days, skipping.\n",
			row[0], row[1], atime);
		continue;
		}
	    }
	AllocVar(si);
	safecpy(si->userName, sizeof(si->userName), row[0]);
	safecpy(si->sessionName, sizeof(si->sessionName), row[1]);
	si->contents = cloneString(row[3]);
	slAddHead(&sessionList, si);
	}
    sqlFreeResult(&sr);
    for (si = sessionList;  si != NULL;  si = si->next)
	{
	char *updateIfAny = scanSettingsForCT(si->userName, si->sessionName, si->contents,
					      &liveCount, &expiredCount);
	if (updateIfAny)
	    {
	    AllocVar(update);
	    update->name = updateIfAny;
	    slAddHead(&updateList, update);
	    }
	}
    }

/* Now that we're done reading from savedSessionTable, we can modify it: */
if (optionExists("hardcore"))
    {
    for (update = updateList;  update != NULL;  update = update->next)
	sqlUpdate(conn, update->name);
    }
hDisconnectCentral(&conn);
verbose(1, "Found %d live and %d expired custom tracks in %s.\n",
	liveCount, expiredCount, centralDbName);
}
Пример #13
0
int main (int argc, char ** argv) {
	char 			ip[256] = { 0, };
	char			oip[256] = { 0, };
	char			err[1024];
	int				opt;
	bool			verbose = false;
	short			input;

#ifdef HAVE_GETOPT_LONG
	while ( (opt = getopt_long (argc, argv, "hv", long_options, (int *) 0)) != EOF ) {
#else
	while ( (opt = getopt (argc, argv, "hv")) != EOF ) {
#endif
		switch (opt) {
			case 'v' :
				verbose = true;
				break;
			default:
				usage (PNAME);
		}
	}

	if ( argc - optind < 1 || argc == 1 ) {
		usage (PNAME);
		return 1;
	}

	safecpy (ip, argv[optind], 256);
	input = (strchr (ip, '.') != NULL) ? IPv4 : LONGIP;

#ifdef _WIN32
	{
		WORD wVerReq = MAKEWORD (2, 2); // WinSock 2.2 요청
		WSADATA wsaData;
		int nErrStatus;

		if ( (nErrStatus = WSAStartup (wVerReq, &wsaData)) != 0 ) {
			fprintf (stderr, "ERROR: Failed initialize WSAStart\n");
			return 1;
		}
	}
#endif

	strcpy (oip, ip);
	if ( valid_ip_address (ip, err) ) {
		fprintf (stderr, "ERROR: %s -> %s\n", oip, err);
		IPCALC_WSACleanup;
		return 1;
	}

	if ( verbose )
		printf ("IPv4   : ");
	if ( verbose || input == LONGIP )
		printf ("%s\n", ip);

	if ( verbose )
		printf ("LONGIP : ");
	if ( verbose || input == IPv4 )
		printf ("%lu\n", ip2long (ip));

	IPCALC_WSACleanup;

	return 0;
}
Пример #14
0
static void
setoption(char *opt) {
	if (strncasecmp(opt, "all", 4) == 0) {
		show_settings(ISC_TRUE, ISC_FALSE);
	} else if (strncasecmp(opt, "class=", 6) == 0) {
		if (testclass(&opt[6]))
			safecpy(defclass, &opt[6], sizeof(defclass));
	} else if (strncasecmp(opt, "cl=", 3) == 0) {
		if (testclass(&opt[3]))
			safecpy(defclass, &opt[3], sizeof(defclass));
	} else if (strncasecmp(opt, "type=", 5) == 0) {
		if (testtype(&opt[5]))
			safecpy(deftype, &opt[5], sizeof(deftype));
	} else if (strncasecmp(opt, "ty=", 3) == 0) {
		if (testtype(&opt[3]))
			safecpy(deftype, &opt[3], sizeof(deftype));
	} else if (strncasecmp(opt, "querytype=", 10) == 0) {
		if (testtype(&opt[10]))
			safecpy(deftype, &opt[10], sizeof(deftype));
	} else if (strncasecmp(opt, "query=", 6) == 0) {
		if (testtype(&opt[6]))
			safecpy(deftype, &opt[6], sizeof(deftype));
	} else if (strncasecmp(opt, "qu=", 3) == 0) {
		if (testtype(&opt[3]))
			safecpy(deftype, &opt[3], sizeof(deftype));
	} else if (strncasecmp(opt, "q=", 2) == 0) {
		if (testtype(&opt[2]))
			safecpy(deftype, &opt[2], sizeof(deftype));
	} else if (strncasecmp(opt, "domain=", 7) == 0) {
		safecpy(domainopt, &opt[7], sizeof(domainopt));
		set_search_domain(domainopt);
		usesearch = ISC_TRUE;
	} else if (strncasecmp(opt, "do=", 3) == 0) {
		safecpy(domainopt, &opt[3], sizeof(domainopt));
		set_search_domain(domainopt);
		usesearch = ISC_TRUE;
	} else if (strncasecmp(opt, "port=", 5) == 0) {
		set_port(&opt[5]);
	} else if (strncasecmp(opt, "po=", 3) == 0) {
		set_port(&opt[3]);
	} else if (strncasecmp(opt, "timeout=", 8) == 0) {
		set_timeout(&opt[8]);
	} else if (strncasecmp(opt, "t=", 2) == 0) {
		set_timeout(&opt[2]);
 	} else if (strncasecmp(opt, "rec", 3) == 0) {
		recurse = ISC_TRUE;
	} else if (strncasecmp(opt, "norec", 5) == 0) {
		recurse = ISC_FALSE;
	} else if (strncasecmp(opt, "retry=", 6) == 0) {
		set_tries(&opt[6]);
	} else if (strncasecmp(opt, "ret=", 4) == 0) {
		set_tries(&opt[4]);
 	} else if (strncasecmp(opt, "def", 3) == 0) {
		usesearch = ISC_TRUE;
	} else if (strncasecmp(opt, "nodef", 5) == 0) {
		usesearch = ISC_FALSE;
 	} else if (strncasecmp(opt, "vc", 3) == 0) {
		tcpmode = ISC_TRUE;
	} else if (strncasecmp(opt, "novc", 5) == 0) {
		tcpmode = ISC_FALSE;
 	} else if (strncasecmp(opt, "deb", 3) == 0) {
		short_form = ISC_FALSE;
		showsearch = ISC_TRUE;
	} else if (strncasecmp(opt, "nodeb", 5) == 0) {
		short_form = ISC_TRUE;
		showsearch = ISC_FALSE;
 	} else if (strncasecmp(opt, "d2", 2) == 0) {
		debugging = ISC_TRUE;
	} else if (strncasecmp(opt, "nod2", 4) == 0) {
		debugging = ISC_FALSE;
	} else if (strncasecmp(opt, "search", 3) == 0) {
		usesearch = ISC_TRUE;
	} else if (strncasecmp(opt, "nosearch", 5) == 0) {
		usesearch = ISC_FALSE;
	} else if (strncasecmp(opt, "sil", 3) == 0) {
		/* deprecation_msg = ISC_FALSE; */
	} else if (strncasecmp(opt, "fail", 3) == 0) {
		nofail=ISC_FALSE;
	} else if (strncasecmp(opt, "nofail", 3) == 0) {
		nofail=ISC_TRUE;
	} else {
		printf("*** Invalid option: %s\n", opt);	
	}
}
Пример #15
0
/*----------------------------------------------------------------------*/
int get_current_executable_path(char *executable, char *path, int max_path_length)
{

    char cwdpath[64];
#if defined AIX
    char cmd[256];
    char msg[1024];
#elif defined LINUX
    char cmd[256];
    char msg[1024];
#elif defined SOLARIS
    const char *pexecpath;
#elif defined HPUX
    char *pexecpath;
#elif defined WIN32

#endif

    if (strlen(executable) == 0 )
    {
        safecpy(path, "notknown", max_path_length);
        return(1);
    }

    if (executable[0] == '/')
    {
        safecpy(path, executable, max_path_length);
        return(0);
    }

    if (strlen(executable) > 1)
    {
        if ((executable[0] == '.') && (executable[1] == '/'))
        {
            getcwd(cwdpath, sizeof(cwdpath));
            safecpy(path, cwdpath, max_path_length);
            safecat(path, &executable[1], max_path_length);
            return(0);
        }
    }

#if defined AIX

    sprintf(cmd, "which %s", executable);

    if (run_system_cmd_and_capture_single_line_output(cmd, path , max_path_length))
    {
        sprintf(msg, "command to find path of current executable: %s failed\n", cmd);
        print_msg_to_console(msg);
        return(1);
    }

#elif defined LINUX

    //  readlink("/proc/self/exe", path, max_path_length);

    sprintf(cmd, "which %s", executable);

    if (run_system_cmd_and_capture_single_line_output(cmd, path , max_path_length))
    {
        sprintf(msg, "command to find path of current executable: %s failed\n", cmd);
        print_msg_to_console(msg);
        return(1);
    }

#elif defined SOLARIS

    getcwd(cwdpath, sizeof(cwdpath));
    pexecpath = getexecname();

    safecpy(path, pexecpath, max_path_length);

    if (path[0] != '/')
    {
        safecpy(path, cwdpath, max_path_length);
        safecat(path, pexecpath, max_path_length);
    }

#elif defined HPUX

    pexecpath = pathfind(getenv("PATH"), executable, "x");
    safecpy(path, pexecpath, max_path_length);

#elif defined WIN32 || defined NETWARE

    safecpy(path, "not done yet", max_path_length);

#endif

    chomp(path);
    return(0);

}
Пример #16
0
static void
addlookup(char *opt) {
	dig_lookup_t *lookup;
	isc_result_t result;
	isc_textregion_t tr;
	dns_rdatatype_t rdtype;
	dns_rdataclass_t rdclass;
	char store[MXNAME];

	debug("addlookup()");
	tr.base = deftype;
	tr.length = strlen(deftype);
	result = dns_rdatatype_fromtext(&rdtype, &tr);
	if (result != ISC_R_SUCCESS) {
		printf("unknown query type: %s\n", deftype);
		rdclass = dns_rdatatype_a;
	}
	tr.base = defclass;
	tr.length = strlen(defclass);
	result = dns_rdataclass_fromtext(&rdclass, &tr);
	if (result != ISC_R_SUCCESS) {
		printf("unknown query class: %s\n", defclass);
		rdclass = dns_rdataclass_in;
	}
	lookup = make_empty_lookup();
	if (get_reverse(store, sizeof(store), opt, lookup->ip6_int, ISC_TRUE)
	    == ISC_R_SUCCESS) {
		safecpy(lookup->textname, store, sizeof(lookup->textname));
		lookup->rdtype = dns_rdatatype_ptr;
		lookup->rdtypeset = ISC_TRUE;
	} else {
		safecpy(lookup->textname, opt, sizeof(lookup->textname));
		lookup->rdtype = rdtype;
		lookup->rdtypeset = ISC_TRUE;
	}
	lookup->rdclass = rdclass;
	lookup->rdclassset = ISC_TRUE;
	lookup->trace = ISC_FALSE;
	lookup->trace_root = lookup->trace;
	lookup->ns_search_only = ISC_FALSE;
	lookup->identify = identify;
	lookup->recurse = recurse;
	lookup->aaonly = aaonly;
	lookup->retries = tries;
	lookup->udpsize = 0;
	lookup->comments = comments;
	lookup->tcp_mode = tcpmode;
	lookup->stats = stats;
	lookup->section_question = section_question;
	lookup->section_answer = section_answer;
	lookup->section_authority = section_authority;
	lookup->section_additional = section_additional;
	lookup->new_search = ISC_TRUE;
	if (nofail)
		lookup->servfail_stops = ISC_FALSE;
	ISC_LIST_INIT(lookup->q);
	ISC_LINK_INIT(lookup, link);
	ISC_LIST_APPEND(lookup_list, lookup, link);
	lookup->origin = NULL;
	ISC_LIST_INIT(lookup->my_server_list);
	debug("looking up %s", lookup->textname);
}
Пример #17
0
void
changepasswd(Ticketreq *tr)
{
	Ticket t;
	char tbuf[TICKETLEN+1];
	char prbuf[PASSREQLEN];
	Passwordreq pr;
	char okey[DESKEYLEN], nkey[DESKEYLEN];
	char *err;

	if(findkey(KEYDB, tr->uid, okey) == 0){
		/* make one up so caller doesn't know it was wrong */
		mkkey(okey);
		syslog(0, AUTHLOG, "cp-fail uid %s", raddr);
	}

	/* send back a ticket with a new key */
	memmove(t.chal, tr->chal, CHALLEN);
	mkkey(t.key);
	tbuf[0] = AuthOK;
	t.num = AuthTp;
	safecpy(t.cuid, tr->uid, sizeof(t.cuid));
	safecpy(t.suid, tr->uid, sizeof(t.suid));
	convT2M(&t, tbuf+1, okey);
	write(1, tbuf, sizeof(tbuf));

	/* loop trying passwords out */
	for(;;){
		if(readn(0, prbuf, PASSREQLEN) < 0)
			exits(0);
		convM2PR(prbuf, &pr, t.key);
		if(pr.num != AuthPass){
			replyerror("protocol botch1: %s", raddr);
			exits(0);
		}
		passtokey(nkey, pr.old);
		if(memcmp(nkey, okey, DESKEYLEN)){
			replyerror("protocol botch2: %s", raddr);
			continue;
		}
		if(*pr.new){
			err = okpasswd(pr.new);
			if(err){
				replyerror("%s %s", err, raddr);
				continue;
			}
			passtokey(nkey, pr.new);
		}
		if(pr.changesecret && setsecret(KEYDB, tr->uid, pr.secret) == 0){
			replyerror("can't write secret %s", raddr);
			continue;
		}
		if(*pr.new && setkey(KEYDB, tr->uid, nkey) == 0){
			replyerror("can't write key %s", raddr);
			continue;
		}
		break;
	}

	prbuf[0] = AuthOK;
	write(1, prbuf, 1);
	succeed(tr->uid);
	return;
}