Beispiel #1
0
static void m2i_rename(path_t *path, cbmdirent_t *dent, uint8_t *newname) {
  uint16_t offset;
  uint8_t *ptr;

  set_busy_led(1);
  /* Locate entry in the M2I file */
  offset = dent->pvt.m2i.offset;
  if (load_entry(path->part, offset)) {
    update_leds();
    return;
  }

  /* Re-load the entry because load_entry modifies it */
  /* Assume this never fails because load_entry was successful */
  image_read(path->part, offset, ops_scratch, M2I_ENTRY_LEN);

  /* Copy the new filename */
  ptr = ops_scratch + M2I_CBMNAME_OFFSET;
  memset(ptr, ' ', CBM_NAME_LENGTH);
  while (*newname)
    *ptr++ = *newname++;

  /* Write new entry */
  image_write(path->part, offset, ops_scratch, M2I_ENTRY_LEN, 1);

  update_leds();
}
void restart() {
	/* Perform some initialization to restart a program */
#ifdef USE_RAMDISK
	/* Read the file with name `argv[1]' into ramdisk. */
	init_ramdisk();
#endif

	/* Read the entry code into memory. */
	load_entry();

	/* Set the initial instruction pointer. */
	cpu.eip = ENTRY_START;
	cpu.ebp = 0;
	cpu.esp = 0x80000000;
	cpu.eflags_cf = false; 
	cpu.eflags_pf = false;
	cpu.eflags_zf = false;
	cpu.eflags_sf = false;
	cpu.eflags_if = false;
	cpu.eflags_df = false;
	cpu.eflags_of = false;

	/* Initialize DRAM. */
	init_ddr3();
}
Beispiel #3
0
void
TimeLog::load()
{
    if (!m_is_loaded)
    {
        clear_cache();
        if (file_exists_at(m_filepath))
        {
            ifstream infile(m_filepath.c_str());
            enable_exceptions(infile);
            string line;
            size_t line_number = 1;
            while (infile.peek() != EOF)
            {
                getline(infile, line);
                load_entry(line, line_number);
                ++line_number;
            }
            if (!m_entries.empty() && (m_entries.back().time_point > now()))
            {
                throw runtime_error
                (   "The final entry in the time log is future-dated. "
                    "Future dated entries are not supported."
                );
            }
        }
        m_is_loaded = true;
    }
    return;
}
Beispiel #4
0
/*
 * Load the database with data from the provided file.
 *
 * Reads the file and loads each entry.
 * Entries are delimited by /EOS lines.
 *
 * Returns 0 on succes, -1 on failure.
 */
static int
load_from_file(sam_db_context_t *con, FILE *file) {
	int offset = 0;
	while (fread(load_buf + offset, 1, LOAD_BUF_LEN - offset, file) > 0) {
		char *start = load_buf;
		char *end = strstr(load_buf, "/EOS\n");
		if (end == NULL) {
			fprintf(stderr, "Entry >%d bytes, exiting.",
			    LOAD_BUF_LEN);
			return (-1);
		}
		*end = '\0';
		while (end != NULL) {
			offset = end - start;
			if (load_entry(con, start) < 0) {
				return (-1);
			}
			start = end + 5; // Move past /EOS\n
			end = strstr(start, "/EOS\n");
			if (end != NULL) {
				*end = '\0';
			}
		}
		offset = LOAD_BUF_LEN - (start - load_buf);
		memmove(load_buf, start, offset);
	}

	return (0);
}
Beispiel #5
0
void load_config(const char * const config_name) {
	FILE *config_file = NULL;

	/* update sscanf line below with max name length (%s) if changing sizes */
	uint line_size = 128;
	char line[line_size];
	uint line_number;

	char name[line_size];
	double value;

	if ((config_file = fopen(config_name, "r")) == NULL) {
		fprintf(stderr, "Config file %s not found.  Exiting.\n", config_name);
		exit(FILE_ERR);
	}

	for (line_number = 1; fgets(line, line_size, config_file) != NULL; line_number++) {
		line[line_size - 1] = '\0';

		/* ignore comments and blank lines */
		if (line[0] == '#' || line[0] == '\n')
			continue;

		/* read lines with entries (name value) */
		//printf("%s\n", line);
		if (sscanf(line, "\t%127s %lf", name, &value) == 2) {
			name[line_size - 1] = '\0';
			printf("%s    %f    %d\n", name, value, line_number);
			load_entry(name, value, line_number);
		} else
			fprintf(stderr, "Config file parsing error on line %u:  %s\n", line_number, line);
	}
	fclose(config_file);
}
Beispiel #6
0
static void load_entries(std::istream & is, const setup::version & version,
                  info::entry_types entry_types, size_t count,
                  std::vector<Entry> & entries, info::entry_types::enum_type entry_type,
                  Arg arg = Arg()) {
	
	entries.clear();
	if(entry_types & entry_type) {
		entries.resize(count);
		for(size_t i = 0; i < count; i++) {
			Entry & entry = entries[i];
			load_entry(is, version, entry, arg);
		}
	} else {
		for(size_t i = 0; i < count; i++) {
			Entry entry;
			load_entry(is, version, entry, arg);
		}
	}
}
Beispiel #7
0
static const struct hash_table_entry *fetch_entry(struct metadata_table *table,
		long long cstart)
{
	struct hash_table_entry **hash_table = table->hash_table;
	const int hash = calculate_hash(cstart);
	struct hash_table_entry *entry = hash_table[hash];
	while (entry && entry->cstart != cstart) {
		entry = entry->next;
	}
	if (!entry) {
		entry = load_entry(table->pdata, cstart);
		hash_table[hash] = entry;
	}
	return entry;
}
Beispiel #8
0
static uint8_t m2i_delete(path_t *path, cbmdirent_t *dent) {
  uint16_t offset;

  offset = dent->pvt.m2i.offset;// find_entry
  if (load_entry(path->part, offset))
    return 255;

  /* Ignore the result, we'll have to delete the entry anyway */
  ustrcpy(dent->name, ops_scratch + M2I_FATNAME_OFFSET);
  fat_delete(path, dent);

  ops_scratch[0] = '-';
  if (image_write(path->part, offset, ops_scratch, 1, 1))
    return 0;
  else
    return 1;
}
Beispiel #9
0
/**
 * open_existing - open an existing file
 * @path      : path handle
 * @dent      : pointer to cbmdirent struct with name of the file
 * @type      : type of the file (not checked)
 * @buf       : buffer to be used
 * @appendflag: Flags if the file should be opened for appending
 *
 * This function searches the file name in an M2I file and opens it
 * either in read or append mode according to appendflag by calling
 * the appropiate fat_* functions.
 */
static void open_existing(path_t *path, cbmdirent_t *dent, uint8_t type, buffer_t *buf, uint8_t appendflag) {
  if (load_entry(path->part, dent->pvt.m2i.offset)) {
    set_error(ERROR_FILE_NOT_FOUND);
    return;
  }

  if (parsetype()) {
    set_error(ERROR_FILE_NOT_FOUND);
    return;
  }

  ustrcpy(dent->pvt.fat.realname, ops_scratch + M2I_FATNAME_OFFSET);

  if (appendflag)
    fat_open_write(path, dent, type, buf, 1);
  else
    fat_open_read(path, dent, buf);
}
Beispiel #10
0
int main( int argc, char** argv, char** envp )
{
    const char* filename = "crontab";
    const char* username = "******";

    //Retreive Crontab File
    FILE *file = fopen( filename, "r" );

    if ( file == NULL )
    {
        error_handler( strerror( errno ) );

        return EXIT_FAILURE;
    }

    //Retreive Password Entry
    struct passwd *pw = getpwnam( username );

    if ( pw == NULL )
    {
        error_handler( strerror( errno ) );

        return EXIT_FAILURE;
    }

    //Read Entry
    entry *e = load_entry( file, &error_handler, pw, envp );

    if ( e == NULL )
    {
        error_handler( "No entry found!" );

        return EXIT_FAILURE;
    }

    print_entry( e );

    //Clean-up
    fclose( file );
    free_entry( e );

    return EXIT_SUCCESS;
}
Beispiel #11
0
void restart() {
	/* Perform some initialization to restart a program */
#ifdef USE_RAMDISK
	/* Read the file with name `argv[1]' into ramdisk. */
	init_ramdisk();
#endif

	/* Read the entry code into memory. */
	load_entry();

	/* Set the initial instruction pointer. */
	cpu.eip = ENTRY_START;
	
	/* Set the initial flag register */
	cpu.EFLAGS.val = 0x00000002;

	/* Initialize DRAM. */
	init_ddr3();
}
Beispiel #12
0
/**
 * find_empty_entry - returns the offset of the first empty M2I entry
 * @part: partition number
 *
 * This function looks for a deleted entry in an M2I file and returns
 * it offset. Returns 1 on error or an offset if successful. The
 * offset may point to a position beyond the end of file if there
 * were no free entries available.
 */
static uint16_t find_empty_entry(uint8_t part) {
  uint16_t pos = M2I_ENTRY_OFFSET;
  uint8_t i;

  while (1) {
    i = load_entry(part, pos);

    if (i) {
      if (i == 255)
        return 1;
      else
        return pos;
    }

    if (ops_scratch[0] == '-')
      return pos;

    pos += M2I_ENTRY_LEN;
  }
}
Beispiel #13
0
void load_config(void) {
	const char * const config_name = "ssd.conf";
	FILE *config_file = NULL;

	/* update sscanf line below with max name length (%s) if changing sizes */
	uint line_size = 128;
	char line[line_size];
	uint line_number;

	char name[line_size];
	double value;

	if ((config_file = fopen(config_name, "r")) == NULL) {
		fprintf(stderr, "Config file %s not found.  Exiting.\n", config_name);
		exit(FILE_ERR);
	}

	for (line_number = 1; fgets(line, line_size, config_file) != NULL; line_number++) {
		line[line_size - 1] = '\0';

		/* ignore comments and blank lines */
		if (line[0] == '#' || line[0] == '\n')
			continue;

		/* read lines with entries (name value) */
		if (sscanf(line, "%127s %lf", name, &value) == 2) {
			name[line_size - 1] = '\0';
			load_entry(name, value, line_number);
		} else
			fprintf(stderr, "Config file parsing error on line %u\n",
					line_number);
	}
	fclose(config_file);

	NUMBER_OF_ADDRESSABLE_BLOCKS = (SSD_SIZE * PACKAGE_SIZE * DIE_SIZE * PLANE_SIZE) / VIRTUAL_PAGE_SIZE;

	return;
}
Beispiel #14
0
int main(int argc, char** argv) {
	int i;
	INDEX* list = NULL;

	FILE* in = fopen("adb.txt", "rt");

	unsigned int count = load_table(in, &list);
	printf("Elements: %u\n", count);
	for(i = 0; i < count; i++)
		printf("nick(%d) = '%s'\n", i, list[i].nick);

	INDEX* index = find_nick("priska", list, count);

	ENTRY entry;
	fseek(in, 0, SEEK_SET);
	load_entry(index, &entry, in);
	printf("nick: '%s'\n", entry.nick);
	printf("email: '%s'\n", entry.email);
	printf("comment: '%s'\n", entry.comment);

	free_table(&list);
	fclose(in);
}
Beispiel #15
0
void
layout_load(lua_State *L, int index)
{
	layout_entry_t entry;

	lua_pushnil(L);  /* first key */
	while (lua_next(L, index) != 0) {
		/* uses 'key' (at index -2) and 'value' (at index -1) */
		load_entry(L, &entry);
		if (entry.length == 0)
			lua_pushnil(L);
		else
			new_entry(L, &entry);

		/* layout[ key ] = entry */
		luau_settable(L, index, -3, -1);

		/* removes 'value' and 'entry'; keeps 'key' for next iteration */
		lua_pop(L, 2);
	}

	lua_pushboolean(L, true);
	lua_setfield(L, index, LAYOUT_STAMP);
}
Beispiel #16
0
/*
 * Main program
 */
int main(int argc, char **argv) {
    int sock_fd, serv_len, n;
    struct sockaddr_in serv_addr;
    struct hostent *serv;

    struct {
        char message[BUFFER];
        int uuid;
    } msg_in, msg_out;

    /* Generate a random UUID */
    srand(time(NULL));
    uuid = rand();

    clearScreen();

    char *input;
    command *cmd;
    size_t buffer = BUFFER;
    while (TRUE) {
        /* Display prompt */
        printPrompt();

        /* malloc input to memory */
        input = (char *)malloc(sizeof(char) * BUFFER);

        /* Clear msg_in and msg_out */
        bzero((char *)msg_in.message, sizeof(msg_in.message));
        bzero((char *)msg_out.message, sizeof(msg_out.message));
        msg_in.uuid = -1;
        msg_out.uuid = uuid;

        /* Get input */
        getline(&input, &buffer, stdin);
        input[strcspn(input, "\n")] = '\0'; //Remove trailing '\n'

        /* Create command */
        cmd = new_command(input);

        /* Output redirection */
        int file_out, con_out;
        if (cmd->output_file) {
            file_out = open(cmd->output_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
            if (file_out < 0) {
                perror("open");
                break;
            }
            con_out = dup(STDOUT_FILENO);
            dup2(file_out, STDOUT_FILENO);
            close(file_out);
        }

        /* Execute user command if possible */
        switch (check_command(cmd->name)) {
            case HELP: //help
                printHelp();
                break;
            case FMOUNT: //fmount
                if (serv_uuid != -1) {
                    printf("[ERROR] You are already connected to a server\n");
                    break;
                }
                if (cmd->argc != 2) {
                    printf("[ERROR] Usage: fmount <server>\n");
                    break;
                }

                printf("Connecting to `%s`... ", cmd->argv[1]);
                fflush(stdout); //Safety precaution

                /* Parse server */
                serv = gethostbyname(cmd->argv[1]);

                /* Open UDP socket */
                sock_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
                if (sock_fd < 0) {
                    perror("socket");
                    break;
                }

                /* Write zero's to serv_addr */
                bzero((char *)&serv_addr, sizeof(serv_addr));

                /* Set up server */
                serv_addr.sin_family = AF_INET;
                bcopy(serv->h_addr, (char *)&serv_addr.sin_addr, serv->h_length);
                serv_addr.sin_port = htons(PORT);
                serv_len = sizeof(serv_addr);

                /* Send CONNECT command to server */
                sprintf(msg_out.message, "CONNECT");
                n = sendto(sock_fd, &msg_out, sizeof(msg_out), 0, (struct sockaddr *)&serv_addr, (socklen_t)serv_len);
                if (n < 0) {
                    perror("sendto");
                    break;
                }

                /* Get response from server */
                n = recvfrom(sock_fd, &msg_in, sizeof(msg_in), 0, (struct sockaddr *)&serv_addr, (socklen_t *)&serv_len);
                if (n < 0) {
                    perror("recvfrom");
                    break;
                }

                if (strcmp(msg_in.message, "CONNECT") != 0) {
                    printf("[ERROR] Invalid response from server\n");
                    break;
                }

                /* Save server UUID */
                serv_uuid = msg_in.uuid;

                /* Clear msg_in and msg_out */
                bzero((char *)&msg_out.message, sizeof(msg_out.message));
                bzero((char *)&msg_in.message, sizeof(msg_in.message));
                msg_out.uuid = uuid;
                msg_in.uuid = -1;

                /* Get SECTOR 0 from server */
                sprintf(msg_out.message, "GETSECTOR 0");
                n = sendto(sock_fd, &msg_out, sizeof(msg_out), 0, (struct sockaddr *)&serv_addr, (socklen_t)serv_len);
                if (n < 0) {
                    perror("sendto");
                    break;
                }

                /* Get response from server */
                n = recvfrom(sock_fd, &msg_in, sizeof(msg_in), 0, (struct sockaddr *)&serv_addr, (socklen_t *)&serv_len);
                if (n < 0) {
                    perror("recvfrom");
                    break;
                }

                /* Load bytes into Fat12Boot */
                load_boot((unsigned char *)msg_in.message);

                /* malloc Fat12Entry */
                entry = (Fat12Entry *)malloc(sizeof(Fat12Entry) * boot.MAX_ROOT_DIRS);

                /* Request all ROOT_DIRECTORY sector entries */
                for (int i = 0; i < 14; i++) {
                    /* Clear msg_in and msg_out */
                    bzero((char *)&msg_out.message, sizeof(msg_out.message));
                    bzero((char *)&msg_in.message, sizeof(msg_in.message));
                    msg_out.uuid = uuid;
                    msg_in.uuid = -1;

                    /* Get ROOT DIRECTORY sector from server */
                    sprintf(msg_out.message, "GETSECTOR %d", ((boot.NUM_OF_FATS * boot.SECTORS_PER_FAT) + 1) + i);
                    n = sendto(sock_fd, &msg_out, sizeof(msg_out), 0, (struct sockaddr *)&serv_addr, (socklen_t)serv_len);
                    if (n < 0) {
                        perror("sendto");
                        break;
                    }

                    /* Get response from server */
                    n = recvfrom(sock_fd, &msg_in, sizeof(msg_in), 0, (struct sockaddr *)&serv_addr, (socklen_t *)&serv_len);
                    if (n < 0) {
                        perror("recvfrom");
                        break;
                    }

                    /* Load bytes into Fat12Entry */
                    load_entry(16 * i, (unsigned char *)msg_in.message);
                }

                printf("Connected!\n");
                break;

            case FUMOUNT: //fumount
                if (serv_uuid == -1) {
                    printf("[ERROR] You are not connected to any server\n");
                    break;
                }
                if (cmd->argc != 1) {
                    printf("[ERROR] Usage: fumount\n");
                    break;
                }

                sprintf(msg_out.message, "DISCONNECT");
                n = sendto(sock_fd, &msg_out, sizeof(msg_out), 0, (struct sockaddr *)&serv_addr, (socklen_t)serv_len);
                if (n < 0) {
                    perror("sendto");
                    break;
                }

                /* Close and write zero's to server */
                close(sock_fd);
                bzero((char *)&serv_addr, sizeof(serv_addr));
                serv_uuid = -1;
                break;

            case STRUCTURE: //structure
                if (serv_uuid == -1) {
                    printf("[ERROR] You are not connected to any server\n");
                    break;
                }
                if (cmd->argc > 2) {
                    printf("[ERROR] Usage: structure [-l]\n");
                    break;
                } else if (cmd->argc == 2) {
                    if (strcmp(cmd->argv[1], "-l") != 0) {
                        printf("[ERROR] Usage: structure [-l]\n");
                        break;
                    }
                }

                printf("        number of FAT:                      %d\n", boot.NUM_OF_FATS);
                printf("        number of sectors used by FAT:      %d\n", boot.SECTORS_PER_FAT);
                printf("        number of sectors per cluster:      %d\n", boot.SECTORS_PER_CLUSTER);
                printf("        number of ROOT Entries:             %d\n", boot.MAX_ROOT_DIRS);
                printf("        number of bytes per sector          %d\n", boot.BYTES_PER_SECTOR);
                if (cmd->argc == 2) {
                    printf("        ---Sector #---      ---Sector Types---\n");
                    printf("             0                    BOOT\n");
                    for (int i = 0; i < boot.NUM_OF_FATS; i++)
                        printf("          %02d -- %02d                FAT%d\n", (boot.SECTORS_PER_FAT * i) + 1, boot.SECTORS_PER_FAT * (i + 1), i);

                    printf("          %02d -- %02d                ROOT DIRECTORY\n", boot.SECTORS_PER_FAT * boot.NUM_OF_FATS, (boot.MAX_ROOT_DIRS / 16) + (boot.SECTORS_PER_FAT * boot.NUM_OF_FATS));
                }
                break;

            case TRAVERSE: //traverse
                if (serv_uuid == -1) {
                    printf("[ERROR] You are not connected to any server\n");
                    break;
                }
                if (cmd->argc > 2) {
                    printf("[ERROR] Usage: traverse [-l]\n");
                    break;
                } else if (cmd->argc == 2) {
                    if (strcmp(cmd->argv[1], "-l") != 0) {
                        printf("[ERROR] Usage: traverse [-l]\n");
                        break;
                    }
                }

                if (cmd->argc == 2) {
                    printf("    *****************************\n");
                    printf("    ** FILE ATTRIBUTE NOTATION **\n");
                    printf("    **                         **\n");
                    printf("    ** R ------ READ ONLY FILE **\n");
                    printf("    ** S ------ SYSTEM FILE    **\n");
                    printf("    ** H ------ HIDDEN FILE    **\n");
                    printf("    ** A ------ ARCHIVE FILE   **\n");
                    printf("    *****************************\n");
                    printf("\n");

                    for (int i = 0; i < boot.MAX_ROOT_DIRS; i++) {
                        if (entry[i].FILENAME[0] != 0x00 && entry[i].START_CLUSTER != 0) {
                            char attr[6] = {'-', '-', '-', '-', '-'};
                            unsigned char a = entry[i].ATTRIBUTES[0];
                            if (a == 0x01)
                                attr[0] = 'R';
                            if (a == 0x02)
                                attr[1] = 'H';
                            if (a == 0x04)
                                attr[2] = 'S';
                            if (a == 0x20)
                                attr[5] = 'A';
                            if (a == 0x10) {
                                for (int j = 0; j < 6; j++)
                                    attr[j] = '-';
                            }

                            if (entry[i].ATTRIBUTES[0] == 0x10) {
                                printf("%.6s    %d %d       < DIR >      /%.8s                 %d\n", attr, entry[i].CREATION_DATE, entry[i].CREATION_TIME, entry[i].FILENAME, entry[i].START_CLUSTER);
                                printf("%.6s    %d %d       < DIR >      /%.8s/.                 %d\n", attr, entry[i].CREATION_DATE, entry[i].CREATION_TIME, entry[i].FILENAME, entry[i].START_CLUSTER);
                                printf("%.6s    %d %d       < DIR >      /%.8s/..                 %d\n", attr, entry[i].CREATION_DATE, entry[i].CREATION_TIME, entry[i].FILENAME, 0);
                            } else {
                                printf("%.6s    %d %d       %lu      /%.8s.%.3s                 %d\n", attr, entry[i].CREATION_DATE, entry[i].CREATION_TIME, entry[i].FILE_SIZE, entry[i].FILENAME, entry[i].EXT, entry[i].START_CLUSTER);
                            }
                        }
                    }
                } else {
                    for (int i = 0; i < boot.MAX_ROOT_DIRS; i++) {
                        if (entry[i].FILENAME[0] != 0x00 && entry[i].START_CLUSTER != 0) {
                            if (entry[i].ATTRIBUTES[0] == 0x10) {
                                printf("/%.8s                       < DIR >\n", entry[i].FILENAME);
                                printf("/%.8s/.                     < DIR >\n", entry[i].FILENAME);
                                printf("/%.8s/..                    < DIR >\n", entry[i].FILENAME);
                            } else {
                                printf("/%.8s.%.3s\n", entry[i].FILENAME, entry[i].EXT);
                            }
                        }
                    }
                }
                break;

            case SHOWFAT: //showfat
                if (serv_uuid == -1) {
                    printf("[ERROR] You are not connected to any server\n");
                    break;
                }
                if (cmd->argc != 1) {
                    printf("[ERROR] Usage: showfat\n");
                    break;
                }

                int sectors = (boot.NUM_OF_FATS * boot.SECTORS_PER_FAT);
                int count = 0;
                printf("        0    1    2    3    4    5    6    7    8    9    a    b    c    d    e    f\n");

                /* Send GETSECTOR command to server */
                for (int i = 1; i <= sectors; i++) {
                    sprintf(msg_out.message, "GETSECTOR %d", i);
                    n = sendto(sock_fd, &msg_out, sizeof(msg_out), 0, (struct sockaddr *)&serv_addr, (socklen_t)serv_len);
                    if (n < 0) {
                        perror("sendto");
                        break;
                    }

                    /* Get response from server */
                    n = recvfrom(sock_fd, &msg_in, sizeof(msg_in), 0, (struct sockaddr *)&serv_addr, (socklen_t *)&serv_len);
                    if (n < 0) {
                        perror("sendto");
                        break;
                    }

                    /* Check server UUID */
                    if (serv_uuid != msg_in.uuid) {
                        printf("[ERROR] Invalid server UUID - Connection rejected\n");
                        break;
                    }

                    for (int j = 0; j < boot.BYTES_PER_SECTOR; j++) {
                        if (count % 16 == 0 || count == 0) {
                            printf("\n");
                            printf("%4x", count);
                        }
                        printf("%5x", (unsigned char)msg_in.message[j]);
                        count++;
                    }
                }
                printf("\n");
                break;

            case SHOWSECTOR: //showsector
                if (serv_uuid == -1) {
                    printf("[ERROR] You are not connected to any server\n");
                    break;
                }
                if (cmd->argc != 2) {
                    printf("[ERROR] Usage: showsector <sector>\n");
                    break;
                }

                /* Parse sector */
                int sector = atoi(cmd->argv[1]);

                /* Send GETSECTOR command to server */
                sprintf(msg_out.message, "GETSECTOR %d", sector);
                n = sendto(sock_fd, &msg_out, sizeof(msg_out), 0, (struct sockaddr *)&serv_addr, (socklen_t)serv_len);
                if (n < 0) {
                    perror("sendto");
                    break;
                }

                /* Get response from server */
                n = recvfrom(sock_fd, &msg_in, sizeof(msg_in), 0, (struct sockaddr *)&serv_addr, (socklen_t *)&serv_len);
                if (n < 0) {
                    perror("recvfrom");
                    break;
                }

                /* Check for valid server UUID */
                if (serv_uuid != msg_in.uuid) {
                    printf("[ERROR] Invalid server UUID - Connection rejected\n");
                    break;
                }

                /* Read response */
                printf("        0    1    2    3    4    5    6    7    8    9    a    b    c    d    e    f\n");
                for (int i = 0; i < boot.BYTES_PER_SECTOR; i++) {
                    if (i % 16 == 0 || i == 0) {
                        printf("\n");
                        printf("%4x", i);
                    }
                    printf("%5x", (unsigned char)msg_in.message[i]);
                }
                printf("\n");
                break;

            case SHOWFILE: //showfile
                if (serv_uuid == -1) {
                    printf("[ERROR] You are not connected to a server\n");
                    break;
                }
                if (cmd->argc != 2) {
                    printf("[ERROR] Usage: showfile <filename>\n");
                    break;
                }

                char filename[12] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' , '\0'};

                int index = 0, k;
                for (k = 0; k < strlen(cmd->argv[1]) && k < 9; k++) {
                    if (cmd->argv[1][k] == '.') {
                        k++;
                        break;
                    }
                    filename[index] = cmd->argv[1][k];
                    index++;
                }

                index = 8;
                for (int j = k; j < strlen(cmd->argv[1]) && j < 12; j++) {
                    if (cmd->argv[1][j] == '\n' || cmd->argv[1][j] == '\0') {
                        break;
                    }
                    filename[index] = cmd->argv[1][j];
                    index++;
                }

                for (int i = 0; i < boot.MAX_ROOT_DIRS; i++) {
                    if (entry[i].FILENAME != 0x00 && entry[i].START_CLUSTER != 0) {
                        if (compare_char(filename, (char *)entry[i].FILENAME)) {
                            int sector = ((boot.MAX_ROOT_DIRS / 16) + (boot.SECTORS_PER_FAT * boot.NUM_OF_FATS) - 1) + entry[i].START_CLUSTER;
                            int size = (entry[i].FILE_SIZE / 512) + 1;
                            int count = 0;

                            printf("        0    1    2    3    4    5    6    7    8    9    a    b    c    d    e    f\n");
                            for (int p = sector; p <= sector + size + 1; p++) {
                                sprintf(msg_out.message, "GETSECTOR %d", p);
                                n = sendto(sock_fd, &msg_out, sizeof(msg_out), 0, (struct sockaddr *)&serv_addr, (socklen_t)serv_len);
                                if (n < 0) {
                                    perror("sendto");
                                    break;
                                }

                                n = recvfrom(sock_fd, &msg_in, sizeof(msg_in), 0, (struct sockaddr *)&serv_addr, (socklen_t *)&serv_len);
                                if (n < 0) {
                                    perror("recvfrom");
                                    break;
                                }

                                if (serv_uuid != msg_in.uuid) {
                                    printf("[ERROR] Invalid server UUID - Connection reject\n");
                                    break;
                                }

                                for (int j = 0; j < boot.BYTES_PER_SECTOR; j++) {
                                    if (j % 16 == 0 || j == 0) {
                                        printf("\n");
                                        printf("%4x", count++);
                                    }
                                    printf("%5x", (unsigned char)msg_in.message[j]);
                                }
                            }
                            printf("\n");
                        }
                    }
                }
                break;

            case EXIT: //exit
                free(input);
                delete_command(cmd);

                if (serv_uuid != -1) {
                    /* Send DISCONNECT command to server */
                    sprintf(msg_out.message, "DISCONNECT");
                    n = sendto(sock_fd, &msg_out, sizeof(msg_out), 0, (struct sockaddr *)&serv_addr, (socklen_t)serv_len);
                    if (n < 0) {
                        perror("sendto");
                        exit(EXIT_FAILURE);
                    }

                    close(sock_fd);
                    bzero((char *)&serv_addr, sizeof(serv_addr));
                    serv_uuid = -1;
                }
                exit(EXIT_SUCCESS);

            case INVALID_CMD: //Invalid command (default)
                printf("[ERROR] %s: Command not found\n", cmd->name);
                break;
        }

        fflush(stdout); //Safety precaution

        /* Restore output */
        if (cmd->output_file) {
            dup2(con_out, STDOUT_FILENO);
            close(con_out);
        }

        /* Free memory */
        free(input);
        delete_command(cmd);
    }
}
Beispiel #17
0
static int8_t m2i_readdir(dh_t *dh, cbmdirent_t *dent) {
  uint8_t i;

  while (1) {
    i = load_entry(dh->part, dh->dir.m2i);
    if (i) {
      if (i == 255)
        return 1;
      else
        return -1;
    }

    memset(dent, 0, sizeof(cbmdirent_t));
    dent->pvt.m2i.offset = dh->dir.m2i;

    dh->dir.m2i += M2I_ENTRY_LEN;

    /* Check file type */
    if (parsetype())
      continue;

    dent->opstype   = OPSTYPE_M2I;
    dent->typeflags = ops_scratch[0];

    /* Copy CBM file name */
    name_repad(' ', 0);
    memcpy(dent->name, ops_scratch + M2I_CBMNAME_OFFSET, CBM_NAME_LENGTH);

    /* Get file size */
    if (dent->typeflags != TYPE_DEL) {
      /* Let's annoy some users */
      FILINFO finfo;

      FRESULT res = f_stat(&partition[dh->part].fatfs, ops_scratch + M2I_FATNAME_OFFSET, &finfo);
      if (res != FR_OK) {
        if (res == FR_NO_FILE)
          continue;
        else {
          parse_error(res,1);
          return 1;
        }
      }

      if (finfo.fsize > 16255746)
        /* File too large -> size 63999 blocks */
        dent->blocksize = 63999;
      else
        dent->blocksize = (finfo.fsize+253) / 254;

      dent->remainder = finfo.fsize % 254;
    } else
      dent->blocksize = 0;

    /* Fake Date/Time */
    dent->date.year  = 82;
    dent->date.month = 8;
    dent->date.day   = 31;

    return 0;
  }
}
Beispiel #18
0
user *
load_user(int crontab_fd, struct passwd	*pw, const char *name) {
	char envstr[MAX_ENVSTR];
	FILE *file;
	user *u;
	entry *e;
	int status, save_errno;
	char **envp, **tenvp;

	if (!(file = fdopen(crontab_fd, "r"))) {
		perror("fdopen on crontab_fd in load_user");
		return (NULL);
	}

	Debug(DPARS, ("load_user()\n"))

	/* file is open.  build user entry, then read the crontab file.
	 */
	if ((u = (user *) malloc(sizeof(user))) == NULL)
		return (NULL);
	if ((u->name = strdup(name)) == NULL) {
		save_errno = errno;
		free(u);
		errno = save_errno;
		return (NULL);
	}
	u->crontab = NULL;

	/* init environment.  this will be copied/augmented for each entry.
	 */
	if ((envp = env_init()) == NULL) {
		save_errno = errno;
		free(u->name);
		free(u);
		errno = save_errno;
		return (NULL);
	}

	/* load the crontab
	 */
	while ((status = load_env(envstr, file)) >= OK) {
		switch (status) {
		case ERR:
			free_user(u);
			u = NULL;
			goto done;
		case FALSE:
			e = load_entry(file, NULL, pw, envp);
			if (e) {
				e->next = u->crontab;
				u->crontab = e;
			}
			break;
		case TRUE:
			if ((tenvp = env_set(envp, envstr)) == NULL) {
				save_errno = errno;
				free_user(u);
				u = NULL;
				errno = save_errno;
				goto done;
			}
			envp = tenvp;
			break;
		}
	}

 done:
	env_free(envp);
	fclose(file);
	Debug(DPARS, ("...load_user() done\n"))
	return (u);
}
int
JarFileParser::filtered_do_next_entries(JvmNameFilterProc entry_filter_proc,
                                        JvmDoJarEntryProc do_jar_entry_proc,
                                        void* caller_data,
                                        int entry_id, int max_size 
                                        JVM_TRAPS) {
  GUARANTEE(entry_id >= 0 && max_size > 0, "Sanity");
  DECLARE_STATIC_BUFFER(char, entry_name,  MAX_ENTRY_NAME);
  unsigned int name_length = 0;
  int total_size = 0;

  if (max_size <= 0) {
    max_size = max_jint;
  }

  if (entry_id > 0) {
    raw_current_entry()->nextCenOffset = entry_id;
  }

  // NOTE: max_entries can be -1 that indicates no limitation on the number of
  // entries processed.
  for (total_size = 0; total_size < max_size;) {
    bool found = find_entry(NULL JVM_MUST_SUCCEED);
    if (!found) {
      break;
    }

    // If find_entry succeeded, centralHeader contains the central directory  
    // header for the found entry.
    unsigned char *cenp = (unsigned char *)raw_current_entry()->centralHeader;
    name_length = CENNAM(cenp);

    if (name_length >= MAX_ENTRY_NAME) {
      return -1;
    }

    // Save the next offset as entry_filter_proc may move raw_current_entry()
    juint nextCenOffset = raw_current_entry()->nextCenOffset +
                          CENHDRSIZ + name_length + CENEXT(cenp) + CENCOM(cenp);

    {
      UsingFastOops fast_oops;
      BufferedFile::Fast bf = buffered_file();
      if (bf().get_bytes((address)entry_name, name_length) != name_length) {
        return -1;
      }
    }
    entry_name[name_length] = '\0';

    if (((entry_filter_proc == NULL) || 
         (entry_filter_proc(entry_name, caller_data) == KNI_TRUE)) &&
        (do_jar_entry_proc != NULL)) {
      UsingFastOops fast_oops;
      Buffer::Fast buffer = load_entry(JVM_SINGLE_ARG_CHECK_0);
      if (buffer.is_null()) {
        return -1;
      }

      if (do_jar_entry_proc((char*)entry_name, buffer().data(), 
                            buffer().length(), caller_data) == KNI_FALSE) {
        return 0;
      }
    }

    total_size += raw_current_entry()->length;

    if (CURRENT_HAS_PENDING_EXCEPTION) {
      // if entry_filter_proc returned NULL, check for exception
      return -1;
    }

    raw_current_entry()->nextCenOffset = nextCenOffset;
  }

  // If we reached the end of JAR return 0.
  // Otherwise return nextCenOffset, it is used as a JAR entry id.
  return (total_size < max_size) ? 0 : raw_current_entry()->nextCenOffset;
}
if (fp == NULL)
    { /* Okey, lets try open the file in the preference folder */
    FSpFindFolder_Name(
                   kOnSystemDisk,
                   kPreferencesFolderType,
                   kDontCreateFolder,
                   &spec,
                   "\pMacZip.Env");
    fp = FSp_fopen(&spec,"r");
    if (fp == NULL)
        {
        return NULL; /* there is no enviroment-file */
        }
    }

LineStr = load_entry(fp);
while (LineStr != NULL)
    {   /* parse the file line by line */
    Env1 = ParseLine(LineStr);
    if (strlen(Env1->value) > 0)
        {       /* we found a key/value pair */
        if (ListAllKeyValues)
            printf("\n   Line:%3d   [%s] = [%s]",LineNumber,Env1->key,Env1->value);
        if (stricmp(name,Env1->key) == 0)
            {   /* we found the value of a given key */
            return Env1->value;
            }
        }
    LineStr = load_entry(fp);  /* read next line */
    }
fclose(fp);
Beispiel #21
0
/* returns	0	on success
 *		-1	on syntax error
 *		-2	on install error
 */
static int
replace_cmd (void)
{
  char n[MAX_FNAME], envstr[MAX_ENVSTR], tn[MAX_FNAME];
  FILE *tmp;
  int ch, eof;
  entry *e;
  char **envp = env_init ();
  int n_header_lines;		/* Number of #CRONTAB header lines we write */

  (void) snprintf (n, MAX_FNAME, "tmp.%d", Pid);
  (void) snprintf (tn, MAX_FNAME, CRON_TAB (n));
  if (!(tmp = fopen (tn, "w+")))
    {
      fprintf (stderr, "Unable to create new crontab file '%s'.\n"
	       "fopen() failed with errno=%s (%d)\n",
	       tn, strerror (errno), errno);
      if (errno == EACCES)
	fprintf (stderr, "In order to have permission to create such files,\n"
		 "Crontab normally is installed setuid either superuser or \n"
		 "a user or group that owns the crontab files and "
		 "directories.\n");
      return (-2);
    }

  write_header_if_wanted (tmp, &n_header_lines);

  /* copy the crontab to the tmp
   */
  rewind (NewCrontab);
  Set_LineNum (1);
  while (EOF != (ch = get_char (NewCrontab)))
    putc (ch, tmp);
  ftruncate (fileno (tmp), ftell (tmp));
  fflush (tmp);
  rewind (tmp);

  if (ferror (tmp))
    {
      fprintf (stderr, "%s: error while writing new crontab to %s\n",
	       ProgramName, tn);
      fclose (tmp);
      unlink (tn);
      return (-2);
    }

  /* check the syntax of the file being installed.
   */

  /* BUG: was reporting errors after the EOF if there were any errors
   * in the file proper -- kludged it by stopping after first error.
   *              vix 31mar87
   */
  Set_LineNum (1 - n_header_lines);
  CheckErrorCount = 0;
  eof = FALSE;
  while (!CheckErrorCount && !eof)
    {
      switch (load_env (envstr, tmp))
	{
	case ERR:
	  eof = TRUE;
	  break;
	case FALSE:
	  e = load_entry (tmp, check_error, pw, envp);
	  if (e)
	    free (e);
	  break;
	case TRUE:
	  break;
	}
    }

  if (CheckErrorCount != 0)
    {
      fprintf (stderr, "errors in crontab file, can't install.\n");
      fclose (tmp);
      unlink (tn);
      return (-1);
    }

/* Why are we doing this?  We just created this file, so if we're privileged
   to do a chown(), the file's owner is already root.  (Maybe on some 
   systems the file doesn't automatically get the creator's effective uid?)
*/
#ifdef HAVE_FCHOWN
  if (fchown (fileno (tmp), ROOT_UID, -1) < OK)
#else
  if (chown (tn, ROOT_UID, -1) < OK)
#endif
    {
      if (errno == EPERM)
	{
	  /* This just means we aren't running as superuser.  We already
	     passed the test of having enough privilege to create the 
	     crontab file in the crontab directory, so the fact that we
	     aren't superuser just means the system administrator wants
	     the crontabs owned by the owner of Crontab, not root.  So
	     let it be.
	   */
	}
      else
	{
	  perror ("chown");
	  fclose (tmp);
	  unlink (tn);
	  return (-2);
	}
    }

#ifdef HAVE_FCHMOD
  if (fchmod (fileno (tmp), 0600) < OK)
#else
  if (chmod (tn, 0600) < OK)
#endif
    {
      perror ("chmod");
      fclose (tmp);
      unlink (tn);
      return (-2);
    }

  if (fclose (tmp) == EOF)
    {
      perror ("fclose");
      unlink (tn);
      return (-2);
    }

  (void) snprintf (n, sizeof (n), CRON_TAB (User));
  if (rename (tn, n))
    {
      fprintf (stderr, "%s: error renaming %s to %s\n", ProgramName, tn, n);
      perror ("rename");
      unlink (tn);
      return (-2);
    }
  log_it (RealUser, Pid, "REPLACE", User);

  poke_daemon ();

  return (0);
}
Beispiel #22
0
/* returns	0	on success
 *		-1	on syntax error
 *		-2	on install error
 */
static int
replace_cmd(void) {
	char n[MAX_FNAME], n2[MAX_FNAME], envstr[MAX_ENVSTR], lastch;
	FILE *tmp, *fmaxtabsize;
	int ch, eof, fd;
	int error = 0;
	entry *e;
	sig_t oint, oabrt, oquit, ohup;
	uid_t file_owner;
	time_t now = time(NULL);
	char **envp = env_init();
	size_t	maxtabsize;
	struct	stat statbuf;

	if (envp == NULL) {
		warn("Cannot allocate memory.");
		return (-2);
	}

	if (!glue_strings(TempFilename, sizeof TempFilename, SPOOL_DIR,
	    "tmp.XXXXXXXXXX", '/')) {
		TempFilename[0] = '\0';
		warnx("path too long");
		return (-2);
	}
	if ((fd = mkstemp(TempFilename)) == -1 || !(tmp = fdopen(fd, "w+"))) {
		warn("cannot create `%s'", TempFilename);
		if (fd != -1) {
			(void)close(fd);
			(void)unlink(TempFilename);
		}
		TempFilename[0] = '\0';
		return (-2);
	}

	ohup = signal(SIGHUP, SIG_IGN);
	oint = signal(SIGINT, SIG_IGN);
	oquit = signal(SIGQUIT, SIG_IGN);
	oabrt = signal(SIGABRT, SIG_IGN);

	/* Make sure that the crontab is not an unreasonable size.
	 *
	 * XXX This is subject to a race condition--the user could
	 * add stuff to the file after we've checked the size but
	 * before we slurp it in and write it out. We can't just move
	 * the test to test the temp file we later create, because by
	 * that time we've already filled up the crontab disk. Probably
	 * the right thing to do is to do a bytecount in the copy loop
	 * rather than stating the file we're about to read.
	 */
	(void)snprintf(n2, sizeof(n2), "%s/%s", CRONDIR, MAXTABSIZE_FILE);
	if ((fmaxtabsize = fopen(n2, "r")) != NULL)  {
	    if (fgets(n2, (int)sizeof(n2), fmaxtabsize) == NULL)  {
		maxtabsize = 0;
	    } else {
		maxtabsize = atoi(n2);
	    }
	    (void)fclose(fmaxtabsize);
	} else {
	    maxtabsize = MAXTABSIZE_DEFAULT;
	}

	if (fstat(fileno(NewCrontab), &statbuf))  {
	    warn("error stat'ing crontab input");
	    error = -2;
	    goto done;
	}
	if ((uintmax_t)statbuf.st_size > (uintmax_t)maxtabsize)  {
	    warnx("%ld bytes is larger than the maximum size of %ld bytes",
		(long) statbuf.st_size, (long) maxtabsize);
	    error = -2;
	    goto done;
	}

	/* write a signature at the top of the file.
	 *
	 * VERY IMPORTANT: make sure NHEADER_LINES agrees with this code.
	 */
	(void)fprintf(tmp, "# DO NOT EDIT THIS FILE - edit the master and reinstall.\n");
	(void)fprintf(tmp, "# (%s installed on %-24.24s)\n", Filename, ctime(&now));
	(void)fprintf(tmp, "# (Cron version %s -- %s)\n", CRON_VERSION, "$NetBSD: crontab.c,v 1.3.8.1 2012/03/07 23:41:17 riz Exp $");

	/* copy the crontab to the tmp
	 */
	(void)rewind(NewCrontab);
	Set_LineNum(1);
	lastch = EOF;
	while (EOF != (ch = get_char(NewCrontab)))
		(void)putc(lastch = ch, tmp);

	if (lastch != (char)EOF && lastch != '\n') {
		warnx("missing trailing newline in `%s'", Filename);
		error = -1;
		goto done;
	}

	if (ferror(NewCrontab)) {
		warn("error while reading `%s'", Filename);
		error = -2;
		goto done;
	}

	(void)ftruncate(fileno(tmp), ftell(tmp));
	/* XXX this should be a NOOP - is */
	(void)fflush(tmp);

	if (ferror(tmp)) {
		(void)fclose(tmp);
		warn("error while writing new crontab to `%s'", TempFilename);
		error = -2;
		goto done;
	}

	/* check the syntax of the file being installed.
	 */

	/* BUG: was reporting errors after the EOF if there were any errors
	 * in the file proper -- kludged it by stopping after first error.
	 *		vix 31mar87
	 */
	Set_LineNum(1 - NHEADER_LINES);
	CheckErrorCount = 0;  eof = FALSE;
	while (!CheckErrorCount && !eof) {
		switch (load_env(envstr, tmp)) {
		case ERR:
			/* check for data before the EOF */
			if (envstr[0] != '\0') {
				Set_LineNum(LineNumber + 1);
				check_error("premature EOF");
			}
			eof = TRUE;
			break;
		case FALSE:
			e = load_entry(tmp, check_error, pw, envp);
			if (e)
				free(e);
			break;
		case TRUE:
			break;
		}
	}

	if (CheckErrorCount != 0) {
		warnx("errors in crontab file, can't install.");
		(void)fclose(tmp);
		error = -1;
		goto done;
	}

	file_owner = (getgid() == getegid()) ? ROOT_UID : pw->pw_uid;

#ifdef HAVE_FCHOWN
	error = fchown(fileno(tmp), file_owner, (uid_t)-1);
#else
	error = chown(TempFilename, file_owner, (gid_t)-1);
#endif
	if (error < OK) {
		warn("cannot chown `%s'", TempFilename);
		(void)fclose(tmp);
		error = -2;
		goto done;
	}

	if (fclose(tmp) == EOF) {
		warn("error closing file");
		error = -2;
		goto done;
	}

	if (!glue_strings(n, sizeof n, SPOOL_DIR, User, '/')) {
		warnx("path too long");
		error = -2;
		goto done;
	}
	if (rename(TempFilename, n)) {
		warn("error renaming `%s' to `%s'", TempFilename, n);
		error = -2;
		goto done;
	}
	TempFilename[0] = '\0';
	log_it(RealUser, Pid, "REPLACE", User);

	poke_daemon();

done:
	(void)signal(SIGHUP, ohup);
	(void)signal(SIGINT, oint);
	(void)signal(SIGQUIT, oquit);
	(void)signal(SIGABRT, oabrt);
	if (TempFilename[0]) {
		(void) unlink(TempFilename);
		TempFilename[0] = '\0';
	}
	return (error);
}