static session * session_new (server *serv, char *from, int type, int focus) { session *sess; sess = malloc (sizeof (struct session)); if (sess == NULL) { return NULL; } memset (sess, 0, sizeof (struct session)); sess->server = serv; sess->logfd = -1; sess->scrollfd = -1; sess->type = type; sess->alert_beep = SET_DEFAULT; sess->alert_taskbar = SET_DEFAULT; sess->alert_tray = SET_DEFAULT; sess->text_hidejoinpart = SET_DEFAULT; sess->text_logging = SET_DEFAULT; sess->text_scrollback = SET_DEFAULT; sess->lastact_idx = LACT_NONE; if (from != NULL) safe_strcpy (sess->channel, from, CHANLEN); sess_list = g_slist_prepend (sess_list, sess); fe_new_window (sess, focus); return sess; }
static void mset(char *arg, int from_tty) { int argc; char *set_args, *p, *argv[5], tmpCmdLine[1024]; static char *macsbug_set_keywords[] = {"DITTO", "UNMANGLE", NULL}; gdb_setup_argv(safe_strcpy(tmpCmdLine, arg), "mset", &argc, argv, 4); if (argc > 1) { if (argc == 2) p = ""; else if (argc == 3) p = argv[2]; else p = NULL; if (p) { if (gdb_strcmpl(argv[1], "ditto")) { if (ditto_args) gdb_free(ditto_args); ditto_args = strcpy((char *)gdb_malloc(strlen(arg)+1), p); macsbug_set("mset", &ditto_args, &ditto, "Ditto-display in memory dumps", from_tty, NULL); } else if (gdb_strcmpl(argv[1], "unmangle")) { if (unmangle_args) gdb_free(unmangle_args); unmangle_args = strcpy((char *)gdb_malloc(strlen(arg)+1), p); macsbug_set("mset", &unmangle_args, &unmangle, "Unmangling of symbols", from_tty, set_gdb_demangle); } else gdb_error("usage: MSET DITTO | UNMANGLE [ON | OFF | NOW | SHOW] (invalid arguments)"); } else gdb_error("usage: MSET DITTO | UNMANGLE [ON | OFF | NOW | SHOW] (invalid arguments)"); } gdb_set_int("$__lastcmd__", 40); }
static int SearchNick (char *text, char *nicks) { char S[300]; /* size of bluestring in xchatprefs */ char *n; char *p; char *t; int ns; if (nicks == NULL) return 0; text = strip_color (text); safe_strcpy (S, nicks, sizeof (S)); n = strtok (S, ","); while (n != NULL) { t = text; ns = strlen (n); while ((p = nocasestrstr (t, n))) { if ((p == text || !isalnum (*(p - 1))) && !isalnum (*(p + ns))) { free (text); return 1; } t = p + 1; } n = strtok (NULL, ","); } free (text); return 0; }
// Delete the file located at path. // If "retry" is set, do retries for 5 sec in case some // other program (e.g. virus checker) has the file locked. // Don't do this if deleting directories - it can lock up the Manager. // int delete_project_owned_file(const char* path, bool retry) { int retval = 0; if (!boinc_file_or_symlink_exists(path)) { return 0; } retval = delete_project_owned_file_aux(path); if (retval && retry) { double start = dtime(); do { boinc_sleep(drand()*2); // avoid lockstep retval = delete_project_owned_file_aux(path); if (!retval) break; } while (dtime() < start + FILE_RETRY_INTERVAL); } if (retval) { safe_strcpy(boinc_failed_file, path); return ERR_UNLINK; } if (log_flags.slot_debug) { msg_printf(0, MSG_INFO, "[slot] removed file %s", path); } return 0; }
/** * Searches and grabs the metadata for all the scenarios. */ void scenario_load_list() { utf8 directory[MAX_PATH]; // Clear scenario list gScenarioListCount = 0; // Get scenario directory from RCT2 safe_strcpy(directory, gConfigGeneral.game_path, sizeof(directory)); safe_strcat_path(directory, "Scenarios", sizeof(directory)); scenario_list_include(directory); // Get scenario directory from user directory platform_get_user_directory(directory, "scenario"); scenario_list_include(directory); scenario_list_sort(); scenario_scores_load(); utf8 scoresPath[MAX_PATH]; scenario_scores_legacy_get_path(scoresPath); scenario_scores_legacy_load(scoresPath); scenario_scores_legacy_load(get_file_path(PATH_ID_SCORES)); }
static void window_multiplayer_groups_paint(rct_window *w, rct_drawpixelinfo *dpi) { window_draw_widgets(w, dpi); window_multiplayer_draw_tab_images(w, dpi); rct_widget* widget = &window_multiplayer_groups_widgets[WIDX_DEFAULT_GROUP]; sint32 group = network_get_group_index(network_get_default_group()); if (group != -1) { char buffer[300]; char* lineCh; lineCh = buffer; lineCh = utf8_write_codepoint(lineCh, FORMAT_WINDOW_COLOUR_2); safe_strcpy(lineCh, network_get_group_name(group), sizeof(buffer) - (lineCh - buffer)); set_format_arg(0, const char *, buffer); gfx_draw_string_centred_clipped( dpi, STR_STRING, gCommonFormatArgs, COLOUR_BLACK, w->x + (widget->left + widget->right - 11) / 2, w->y + widget->top, widget->right - widget->left - 8 ); }
/** * rct2: 0x006B6F3E * * Note: When the user has selection by track type enabled, the categories are determined by the track type, not those in the rct_ride_entry. */ static void window_new_ride_populate_list() { uint8 currentCategory = _windowNewRideCurrentTab; ride_list_item *nextListItem = _windowNewRideListItems; // For each ride type in the view order list for (int i = 0; i < countof(RideTypeViewOrder); i++) { uint8 rideType = RideTypeViewOrder[i]; if (rideType == RIDE_TYPE_NULL) continue; if(gConfigInterface.select_by_track_type) { if(gRideCategories[rideType]!=currentCategory) continue; } char preferredVehicleName[9]; safe_strcpy(preferredVehicleName, " ", sizeof(preferredVehicleName)); if (ride_type_is_invented(rideType)) { int dh = 0; uint8 *rideEntryIndexPtr = get_ride_entry_indices_for_ride_type(rideType); // For each ride entry for this ride type while (*rideEntryIndexPtr != 255) { uint8 rideEntryIndex = *rideEntryIndexPtr++; char rideEntryName[9]; memcpy(rideEntryName,object_entry_groups[OBJECT_TYPE_RIDE].entries[rideEntryIndex].name,8); rideEntryName[8]=0; // Skip if vehicle type is not invented yet if (!ride_entry_is_invented(rideEntryIndex)) continue; // Ride entries rct_ride_entry *rideEntry = get_ride_entry(rideEntryIndex); // Check if ride is in this category if (!gConfigInterface.select_by_track_type && (currentCategory != rideEntry->category[0] && currentCategory != rideEntry->category[1])) continue; // Skip if the vehicle isn't the preferred vehicle for this generic track type if (gConfigInterface.select_by_track_type && (!(rideEntry->flags & RIDE_ENTRY_FLAG_SEPARATE_RIDE) || rideTypeShouldLoseSeparateFlag(rideEntry))) { if (strcmp(preferredVehicleName, " \0") == 0) { safe_strcpy(preferredVehicleName, rideEntryName, sizeof(preferredVehicleName)); preferredVehicleName[8] = 0; } else { if (vehicle_preference_compare(rideType, preferredVehicleName, rideEntryName) == 1) { safe_strcpy(preferredVehicleName, rideEntryName, sizeof(preferredVehicleName)); preferredVehicleName[8] = 0; } else { continue; } } } if ((rideEntry->flags & RIDE_ENTRY_FLAG_SEPARATE_RIDE) && !rideTypeShouldLoseSeparateFlag(rideEntry)) { dh &= ~4; nextListItem->type = rideType; nextListItem->entry_index = rideEntryIndex; nextListItem++; } else if (!(dh & 1)) { dh |= 5; nextListItem->type = rideType; nextListItem->entry_index = rideEntryIndex; nextListItem++; } else if (dh & 4) { if (rideType == rideEntry->ride_type[0]) { nextListItem--; nextListItem->type = rideType; nextListItem->entry_index = rideEntryIndex; nextListItem++; } } } } } nextListItem->type = 255; nextListItem->entry_index = 255; _trackSelectionByType = gConfigInterface.select_by_track_type; }
// returns: // 0 if all went ok; // 1 on a transient error affecting only a single file; // -1 on a serious error that should switch off antique file deletion // int delete_antiques_from_dir(char*dirpath, time_t mtime, uid_t uid) { DIR*dir; struct dirent*entry; struct stat fstat; int ret; char path[MAXPATHLEN]; // open directory errno = 0; dir = opendir(dirpath); if (!dir) { log_messages.printf(MSG_CRITICAL, "delete_antiques_from_dir(): " "Couldn't open dir '%s': %s (%d)\n", dirpath, strerror(errno), errno ); return -1; } // scan directory errno = 0; while ((entry = readdir(dir))) { // might be woken by a signal check_stop_daemons(); // construct absolute path of this entry safe_strcpy(path, dirpath); strcat(path, "/"); strcat(path, entry->d_name); // examine file log_messages.printf(MSG_DEBUG, "delete_antiques_from_dir(): examining file: '%s'\n", path ); // stat errno = 0; if (lstat(path, &fstat)) { log_messages.printf(MSG_NORMAL, "delete_antiques_from_dir(): couldn't stat '%s: %s (%d)'\n", path, strerror(errno), errno ); // regular file } else if ((fstat.st_mode & S_IFMT) != S_IFREG) { log_messages.printf(MSG_DEBUG,"not a regular plain file\n"); // skip hidden files such as ".nfs" } else if (entry->d_name[0] == '.') { log_messages.printf(MSG_DEBUG,"hidden file or directory\n"); // modification time } else if (fstat.st_mtime > mtime) { log_messages.printf(MSG_DEBUG,"too young: %s\n", actime(fstat.st_mtime)); // check owner (must be apache) } else if (fstat.st_uid != uid) { log_messages.printf(MSG_DEBUG,"wrong owner: id %d\n", fstat.st_uid); // skip if dry_run } else if (antiques_deletion_dry_run) { log_messages.printf(MSG_NORMAL, "Would delete '%s/%s' (%s)\n", dirpath, entry->d_name, actime(fstat.st_mtime)); // found no reason to skip, actually delete this file } else { log_messages.printf(MSG_NORMAL, "Deleting file '%s' (%s)\n", path, actime(fstat.st_mtime) ); errno = 0; if (unlink(path)) { log_messages.printf(MSG_CRITICAL, "delete_antiques_from_dir(): " "Couldn't unlink '%s: %s (%d)'\n", path, strerror(errno), errno ); closedir(dir); return 1; } } // throttle I/O if told to if (antique_usleep) { usleep(antique_usleep); } } // while (readdir()) // if the loop terminated because of an error if (errno) { log_messages.printf(MSG_CRITICAL, "delete_antiques_from_dir(): " "Couldn't read dir '%s': %s (%d)\n", dirpath, strerror(errno), errno ); closedir(dir); return 1; } // close dir errno = 0; ret = closedir(dir); if (ret) { log_messages.printf(MSG_CRITICAL, "delete_antiques_from_dir(): " "Couldn't close dir '%s': %s (%d)\n", dirpath, strerror(errno), errno ); } return ret; }
static void window_text_input_paint(rct_window *w, rct_drawpixelinfo *dpi) { window_draw_widgets(w, dpi); int y = w->y + 25; int no_lines = 0; int font_height = 0; gfx_draw_string_centred(dpi, input_text_description, w->x + WW / 2, y, w->colours[1], &TextInputDescriptionArgs); y += 25; RCT2_GLOBAL(RCT2_ADDRESS_CURRENT_FONT_SPRITE_BASE, uint16) = 224; RCT2_GLOBAL(RCT2_ADDRESS_CURRENT_FONT_FLAGS, uint16) = 0; char wrapped_string[512]; safe_strcpy(wrapped_string, text_input, 512); // String length needs to add 12 either side of box // +13 for cursor when max length. gfx_wrap_string(wrapped_string, WW - (24 + 13), &no_lines, &font_height); gfx_fill_rect_inset(dpi, w->x + 10, y, w->x + WW - 10, y + 10 * (no_lines + 1) + 3, w->colours[1], 0x60); y += 1; char* wrap_pointer = wrapped_string; int char_count = 0; uint8 cur_drawn = 0; int cursorX, cursorY; for (int line = 0; line <= no_lines; line++) { gfx_draw_string(dpi, wrap_pointer, w->colours[1], w->x + 12, y); int string_length = get_string_size(wrap_pointer) - 1; if (!cur_drawn && (gTextInput.selection_offset <= (size_t)(char_count + string_length))) { // Make a copy of the string for measuring the width. char temp_string[512] = { 0 }; memcpy(temp_string, wrap_pointer, gTextInput.selection_offset - char_count); cursorX = w->x + 13 + gfx_get_string_width(temp_string); cursorY = y; int width = 6; if ((uint32)gTextInput.selection_offset < strlen(text_input)){ // Make a new 1 character wide string for measuring the width // of the character that the cursor is under. temp_string[1] = '\0'; temp_string[0] = text_input[gTextInput.selection_offset]; width = max(gfx_get_string_width(temp_string) - 2, 4); } if (w->frame_no > 15){ uint8 colour = ColourMapA[w->colours[1]].mid_light; gfx_fill_rect(dpi, cursorX, y + 9, cursorX + width, y + 9, colour + 5); } cur_drawn++; } wrap_pointer += string_length + 1; if (text_input[char_count + string_length] == ' ')char_count++; char_count += string_length; y += 10; } if (!cur_drawn) { cursorX = gLastDrawStringX; cursorY = y - 10; } // IME composition if (gTextInputCompositionActive) { int compositionWidth = gfx_get_string_width(gTextInputComposition); int x = cursorX - (compositionWidth / 2); int y = cursorY + 13; int w = compositionWidth; int h = 10; gfx_fill_rect(dpi, x - 1, y - 1, x + w + 1, y + h + 1, 12); gfx_fill_rect(dpi, x, y, x + w, y + h, 0); gfx_draw_string(dpi, gTextInputComposition, 12, x, y); } }
void window_text_input_open(rct_window* call_w, int call_widget, rct_string_id title, rct_string_id description, rct_string_id existing_text, uint32 existing_args, int maxLength) { _maxInputLength = maxLength; window_close_by_class(WC_TEXTINPUT); // Clear the text input buffer memset(text_input, 0, maxLength); // Enter in the the text input buffer any existing // text. if (existing_text != STR_NONE) format_string(text_input, existing_text, &existing_args); // In order to prevent strings that exceed the maxLength // from crashing the game. text_input[maxLength - 1] = '\0'; utf8_remove_format_codes(text_input, false); // This is the text displayed above the input box input_text_description = description; // Work out the existing size of the window char wrapped_string[512]; safe_strcpy(wrapped_string, text_input, 512); int no_lines = 0, font_height = 0; // String length needs to add 12 either side of box // +13 for cursor when max length. gfx_wrap_string(wrapped_string, WW - (24 + 13), &no_lines, &font_height); int height = no_lines * 10 + WH; // Window will be in the center of the screen rct_window* w = window_create_centred( WW, height, &window_text_input_events, WC_TEXTINPUT, WF_STICK_TO_FRONT ); w->widgets = window_text_input_widgets; w->enabled_widgets = (1 << WIDX_CLOSE) | (1<<WIDX_CANCEL) | (1<<WIDX_OKAY); window_text_input_widgets[WIDX_TITLE].image = title; // Save calling window details so that the information // can be passed back to the correct window & widget calling_class = call_w->classification; calling_number = call_w->number; calling_widget = call_widget; platform_start_text_input(text_input, maxLength); window_init_scroll_widgets(w); w->colours[0] = call_w->colours[0]; w->colours[1] = call_w->colours[1]; w->colours[2] = call_w->colours[2]; }
FILE *dictopen(char *dictname, char *filename, char *how) { /* This function is used to open a dictionary file or a word file, or any associated data file (like a post process knowledge file). It works as follows. If the file name begins with a "/", then it's assumed to be an absolute file name and it tries to open that exact file. If the filename does not begin with a "/", then it uses the dictpath mechanism to find the right file to open. This looks for the file in a sequence of directories until it finds it. The sequence of directories is specified in a dictpath string, in which each directory is followed by a ":". The dictpath that it uses is constructed as follows. If the dictname is non-null, and is an absolute path name (beginning with a "/", then the part after the last "/" is removed and this is the first directory on the dictpath. After this comes the DICTPATH environment variable, followed by the DEFAULTPATH */ char completename[MAX_PATH_NAME+1]; char fulldictpath[MAX_PATH_NAME+1]; char dummy1[MAX_PATH_NAME+1]; char *dp1, *dp2; char *pos, *oldpos; int filenamelen, len; FILE *fp; if (filename[0] == '/') { return fopen(filename, how); /* If the file does not exist NULL is returned */ } dp1 = ""; /* if (dictname != NULL && dictname[0] == '/') { */ if (dictname != NULL) { safe_strcpy(dummy1, dictname, sizeof(dummy1)); pos = strrchr(dummy1, '/'); if (pos != NULL) { *pos = ':'; *(pos+1) = '\0'; dp1 = dummy1; } } /* dp1 now points to the part of the dictpath due to dictname */ dp2 = ""; /* We're no longer using the dictpath in the environment if (strlen(getenv(DICTPATH)) > 0) { sprintf(dummy2, "%s:", getenv(DICTPATH)); dp2 = dummy2; } */ /* dp2 now points to the part of the dictpath due to the environment var */ sprintf(fulldictpath, "%s%s%s", dp1, dp2, DEFAULTPATH); /* now fulldictpath is our dictpath, where each entry is followed by a ":" including the last one */ filenamelen = strlen(filename); len = strlen(fulldictpath)+ filenamelen + 1 + 1; oldpos = fulldictpath; while ((pos = strchr(oldpos, ':')) != NULL) { strncpy(completename, oldpos, (pos-oldpos)); *(completename+(pos-oldpos)) = '/'; strcpy(completename+(pos-oldpos)+1,filename); if ((fp = fopen(completename, how)) != NULL) { printf(" Opening %s\n", completename); return fp; } oldpos = pos+1; } return NULL; }
FILE *old_dictopen(char *dictname, char *filename, char *how) { /* This is the old version. I think it's buggy and inelegant. I've rewritten it below *DS* */ /* This function is used to open a dictionary file or a word file. It tries the following sequence of places to look for the file. The first one that is successful is used. (1) Open the given file. (2) if DICTPATH is defined, try the paths defined by that. (3) Use the path name of the given dictionary. */ char completename[MAX_PATH_NAME+1], fullpath[MAX_PATH_NAME+1], *dictpath; char dummy[MAX_PATH_NAME+1]; char *pos, *oldpos; int filenamelen, len; FILE *fp; sprintf(fullpath, "%s%s", getenv(DICTPATH), DEFAULTPATH); dictpath = fullpath; if (dictpath == NULL && dictname != NULL) { /* look in the dictname part */ safe_strcpy(dummy, dictname, sizeof(dummy)); pos = strrchr(dummy, '/'); if (pos != NULL) { *pos = '\0'; dictpath = dummy; } } dictpath = fullpath; if (dictpath == NULL && dictname != NULL) { /* look in the dictname part */ safe_strcpy(dummy, dictname, sizeof(dummy)); pos = strrchr(dummy, '/'); if (pos != NULL) { *pos = '\0'; dictpath = dummy; } } if (dictpath == NULL) { printf(" Opening %s\n", filename); return (fopen(filename, how)); } else if ((fp = fopen(filename, how)) != NULL) { printf(" Opening %s\n", filename); return fp; } filenamelen = strlen(filename); len = strlen(dictpath)+ filenamelen + 1 + 1; oldpos = dictpath; fp = NULL; while ((pos = strchr(oldpos, ':')) != NULL) { strncpy(completename, oldpos, (pos-oldpos)); *(completename+(pos-oldpos)) = '/'; strcpy(completename+(pos-oldpos)+1,filename); if ((fp = fopen(completename, how)) != NULL) { printf(" Opening %s\n", completename); return fp; } oldpos = pos+1; } pos = oldpos+strlen(oldpos); strcpy(completename, oldpos); *(completename+(pos-oldpos)) = '/'; strcpy(completename+(pos-oldpos)+1,filename); fp = fopen(completename,how); printf(" Opening %s\n", completename); return fp; }
// Returns 0 on success, nonzero on error static int iso_extract_files(iso9660_t* p_iso, const char *psz_path) { HANDLE file_handle = NULL; DWORD buf_size, wr_size, err; BOOL s, is_syslinux_cfg, is_old_c32[NB_OLD_C32], is_symlink; int i_length, r = 1; char tmp[128], psz_fullpath[1024], *psz_basename; const char *psz_iso_name = &psz_fullpath[strlen(psz_extract_dir)]; unsigned char buf[ISO_BLOCKSIZE]; CdioListNode_t* p_entnode; iso9660_stat_t *p_statbuf; CdioList_t* p_entlist; size_t i, j, nul_pos; lsn_t lsn; int64_t i_file_length; if ((p_iso == NULL) || (psz_path == NULL)) return 1; i_length = _snprintf(psz_fullpath, sizeof(psz_fullpath), "%s%s/", psz_extract_dir, psz_path); if (i_length < 0) return 1; psz_basename = &psz_fullpath[i_length]; p_entlist = iso9660_ifs_readdir(p_iso, psz_path); if (!p_entlist) { uprintf("Could not access directory %s\n", psz_path); return 1; } _CDIO_LIST_FOREACH(p_entnode, p_entlist) { if (FormatStatus) goto out; p_statbuf = (iso9660_stat_t*) _cdio_list_node_data(p_entnode); // Eliminate . and .. entries if ( (strcmp(p_statbuf->filename, ".") == 0) || (strcmp(p_statbuf->filename, "..") == 0) ) continue; // Rock Ridge requires an exception is_symlink = FALSE; if ((p_statbuf->rr.b3_rock == yep) && enable_rockridge) { safe_strcpy(psz_basename, sizeof(psz_fullpath)-i_length-1, p_statbuf->filename); if (safe_strlen(p_statbuf->filename) > 64) iso_report.has_long_filename = TRUE; // libcdio has a memleak for Rock Ridge symlinks. It doesn't look like there's an easy fix there as // a generic list that's unaware of RR extensions is being used, so we prevent that memleak ourselves is_symlink = (p_statbuf->rr.psz_symlink != NULL); if (is_symlink) iso_report.has_symlinks = TRUE; if (scan_only) safe_free(p_statbuf->rr.psz_symlink); } else { iso9660_name_translate_ext(p_statbuf->filename, psz_basename, i_joliet_level); } if (p_statbuf->type == _STAT_DIR) { if (!scan_only) _mkdirU(psz_fullpath); if (iso_extract_files(p_iso, psz_iso_name)) goto out; } else { i_file_length = p_statbuf->size; if (check_iso_props(psz_path, &is_syslinux_cfg, is_old_c32, i_file_length, psz_basename, psz_fullpath)) { continue; } // Replace slashes with backslashes and append the size to the path for UI display nul_pos = safe_strlen(psz_fullpath); for (i=0; i<nul_pos; i++) if (psz_fullpath[i] == '/') psz_fullpath[i] = '\\'; safe_sprintf(&psz_fullpath[nul_pos], 24, " (%s)", SizeToHumanReadable(i_file_length, TRUE, FALSE)); uprintf("Extracting: %s\n", psz_fullpath); safe_sprintf(&psz_fullpath[nul_pos], 24, " (%s)", SizeToHumanReadable(i_file_length, FALSE, FALSE)); SetWindowTextU(hISOFileName, psz_fullpath); // ISO9660 cannot handle backslashes for (i=0; i<nul_pos; i++) if (psz_fullpath[i] == '\\') psz_fullpath[i] = '/'; psz_fullpath[nul_pos] = 0; for (i=0; i<NB_OLD_C32; i++) { if (is_old_c32[i] && use_own_c32[i]) { static_sprintf(tmp, "%s/syslinux-%s/%s", FILES_DIR, embedded_sl_version_str[0], old_c32_name[i]); if (CopyFileA(tmp, psz_fullpath, FALSE)) { uprintf(" Replaced with local version\n"); break; } uprintf(" Could not replace file: %s\n", WindowsErrorString()); } } if (i < NB_OLD_C32) continue; if (sanitize_filename(psz_fullpath)) uprintf(" File name sanitized to '%s'\n", psz_fullpath); if (is_symlink) { if (i_file_length == 0) uprintf(" Ignoring Rock Ridge symbolic link to '%s'\n", p_statbuf->rr.psz_symlink); safe_free(p_statbuf->rr.psz_symlink); } file_handle = CreateFileU(psz_fullpath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (file_handle == INVALID_HANDLE_VALUE) { err = GetLastError(); uprintf(" Unable to create file: %s\n", WindowsErrorString()); if ((err == ERROR_ACCESS_DENIED) && (safe_strcmp(&psz_fullpath[3], autorun_name) == 0)) uprintf(stupid_antivirus); else goto out; } else for (i=0; i_file_length>0; i++) { if (FormatStatus) goto out; memset(buf, 0, ISO_BLOCKSIZE); lsn = p_statbuf->lsn + (lsn_t)i; if (iso9660_iso_seek_read(p_iso, buf, lsn, 1) != ISO_BLOCKSIZE) { uprintf(" Error reading ISO9660 file %s at LSN %lu\n", psz_iso_name, (long unsigned int)lsn); goto out; } buf_size = (DWORD)MIN(i_file_length, ISO_BLOCKSIZE); for (j=0; j<WRITE_RETRIES; j++) { ISO_BLOCKING(s = WriteFile(file_handle, buf, buf_size, &wr_size, NULL)); if ((!s) || (buf_size != wr_size)) { uprintf(" Error writing file: %s", WindowsErrorString()); if (j < WRITE_RETRIES-1) uprintf(" RETRYING...\n"); } else { break; } } if (j >= WRITE_RETRIES) goto out; i_file_length -= ISO_BLOCKSIZE; if (nb_blocks++ % PROGRESS_THRESHOLD == 0) { SendMessage(hISOProgressBar, PBM_SETPOS, (WPARAM)((MAX_PROGRESS*nb_blocks)/total_blocks), 0); UpdateProgress(OP_DOS, 100.0f*nb_blocks/total_blocks); } } ISO_BLOCKING(safe_closehandle(file_handle)); if (is_syslinux_cfg) { if (replace_in_token_data(psz_fullpath, "append", iso_report.label, iso_report.usb_label, TRUE) != NULL) uprintf("Patched %s: '%s' -> '%s'\n", psz_fullpath, iso_report.label, iso_report.usb_label); } } } r = 0; out: ISO_BLOCKING(safe_closehandle(file_handle)); _cdio_list_free(p_entlist, true); return r; }
/* * Read from the driver installation syslog in real-time */ void __cdecl syslog_reader_thread(void* param) { #define NB_SYSLOGS 3 char* syslog_name[NB_SYSLOGS] = { "\\inf\\setupapi.dev.log", "\\setupapi.log", "\\setupact.log" }; HANDLE log_handle; DWORD last_offset, size, read_size, processed_size; char *buffer = NULL; char log_path[MAX_PATH_LENGTH]; DWORD duration = 0; int i; // Try the various driver installation logs for (i=0; i<NB_SYSLOGS; i++) { safe_strcpy(log_path, MAX_PATH_LENGTH, getenv("WINDIR")); // Use %WINDIR% env variable safe_strcat(log_path, MAX_PATH_LENGTH, syslog_name[i]); log_handle = CreateFileA(log_path, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (log_handle != INVALID_HANDLE_VALUE) { plog("using syslog '%s'", log_path); break; } } if (i == NB_SYSLOGS) { plog("Could not open any syslog"); goto out; } // We assert that the log file is never gonna be bigger than 2 GB // TODO: special case of setupapi.dev.log's last offset not being the end (v2) last_offset = SetFilePointer(log_handle, 0, NULL, FILE_END); if (last_offset == INVALID_SET_FILE_POINTER) { plog("Could not set syslog offset"); goto out; } plog("sylog reader thread started"); SetEvent(syslog_ready_event); processed_size = 0; while(WaitForSingleObject(syslog_terminate_event, 0) != WAIT_OBJECT_0) { // Find out if file size has increased since last time size = GetFileSize(log_handle, NULL); if (size == INVALID_FILE_SIZE) { plog("could not read syslog file size"); goto out; } size -= last_offset; if (size != 0) { // Read from file and add a zero terminator buffer = malloc(size+1); if (buffer == NULL) { plog("could not allocate buffer to read syslog"); goto out; } // Keep an extra spare byte at the beginning if (!ReadFile(log_handle, buffer, size, &read_size, NULL)) { plog("failed to read syslog"); goto out; } buffer[read_size] = 0; // Send all the complete lines through the pipe processed_size = process_syslog(buffer, read_size); safe_free(buffer); last_offset += processed_size; // Reposition at start of last line if needed if (processed_size != read_size) { last_offset = SetFilePointer(log_handle, processed_size-read_size, NULL, FILE_CURRENT); if (last_offset == INVALID_SET_FILE_POINTER) { plog("Could not set syslog offset"); goto out; } } // Reset adaptive sleep duration if we did send data out if (processed_size !=0) { duration = 0; } } // Compute adaptive sleep duration if (((size == 0) || (processed_size == 0)) && (duration < 500)) { duration += 100; // read log more frequently on recent update } Sleep(duration); } out: plog("syslog reader thread terminating"); safe_free(buffer); CloseHandle(log_handle); _endthread(); }
BOOL rename_share_filename(struct share_mode_lock *lck, const char *servicepath, const char *newname) { size_t sp_len; size_t fn_len; size_t msg_len; char *frm = NULL; int i; if (!lck) { return False; } DEBUG(10, ("rename_share_filename: servicepath %s newname %s\n", servicepath, newname)); /* * rename_internal_fsp() and rename_internals() add './' to * head of newname if newname does not contain a '/'. */ while (newname[0] && newname[1] && newname[0] == '.' && newname[1] == '/') { newname += 2; } lck->servicepath = talloc_strdup(lck, servicepath); lck->filename = talloc_strdup(lck, newname); if (lck->filename == NULL || lck->servicepath == NULL) { DEBUG(0, ("rename_share_filename: talloc failed\n")); return False; } lck->modified = True; sp_len = strlen(lck->servicepath); fn_len = strlen(lck->filename); msg_len = MSG_FILE_RENAMED_MIN_SIZE + sp_len + 1 + fn_len + 1; /* Set up the name changed message. */ frm = TALLOC(lck, msg_len); if (!frm) { return False; } SDEV_T_VAL(frm,0,lck->dev); SINO_T_VAL(frm,8,lck->ino); DEBUG(10,("rename_share_filename: msg_len = %u\n", (unsigned int)msg_len )); safe_strcpy(&frm[16], lck->servicepath, sp_len); safe_strcpy(&frm[16 + sp_len + 1], lck->filename, fn_len); /* Send the messages. */ for (i=0; i<lck->num_share_modes; i++) { struct share_mode_entry *se = &lck->share_modes[i]; if (!is_valid_share_mode_entry(se)) { continue; } /* But not to ourselves... */ if (procid_is_me(&se->pid)) { continue; } DEBUG(10,("rename_share_filename: sending rename message to pid %u " "dev %x, inode %.0f sharepath %s newname %s\n", (unsigned int)procid_to_pid(&se->pid), (unsigned int)lck->dev, (double)lck->ino, lck->servicepath, lck->filename )); become_root(); message_send_pid(se->pid, MSG_SMB_FILE_RENAME, frm, msg_len, True); unbecome_root(); } return True; }
/* * Scan and set ISO properties * Returns true if the the current file does not need to be processed further */ static BOOL check_iso_props(const char* psz_dirname, BOOL* is_syslinux_cfg, BOOL* is_old_c32, int64_t i_file_length, const char* psz_basename, const char* psz_fullpath) { size_t i, j; // Check for an isolinux/syslinux config file anywhere *is_syslinux_cfg = FALSE; for (i=0; i<ARRAYSIZE(syslinux_cfg); i++) { if (safe_stricmp(psz_basename, syslinux_cfg[i]) == 0) *is_syslinux_cfg = TRUE; } // Check for a syslinux v5.0+ file anywhere if (safe_stricmp(psz_basename, ldlinux_c32) == 0) { has_ldlinux_c32 = TRUE; } // Check for an old incompatible c32 file anywhere for (i=0; i<NB_OLD_C32; i++) { is_old_c32[i] = FALSE; if ((safe_stricmp(psz_basename, old_c32_name[i]) == 0) && (i_file_length <= old_c32_threshold[i])) is_old_c32[i] = TRUE; } if (scan_only) { // Check for a "bootmgr(.efi)" file in root (psz_path = "") if (*psz_dirname == 0) { if (safe_strnicmp(psz_basename, bootmgr_efi_name, safe_strlen(bootmgr_efi_name)-5) == 0) { iso_report.has_bootmgr = TRUE; } if (safe_stricmp(psz_basename, bootmgr_efi_name) == 0) { iso_report.has_win7_efi = TRUE; } } // Check for ReactOS' setupldr.sys anywhere if ((iso_report.reactos_path[0] == 0) && (safe_stricmp(psz_basename, reactos_name) == 0)) safe_strcpy(iso_report.reactos_path, sizeof(iso_report.reactos_path), psz_fullpath); // Check for the EFI boot directory if (safe_stricmp(psz_dirname, efi_dirname) == 0) iso_report.has_efi = TRUE; // Check for PE (XP) specific files in "/i386" or "/minint" for (i=0; i<ARRAYSIZE(pe_dirname); i++) if (safe_stricmp(psz_dirname, pe_dirname[i]) == 0) for (j=0; j<ARRAYSIZE(pe_file); j++) if (safe_stricmp(psz_basename, pe_file[j]) == 0) iso_report.winpe |= (1<<i)<<(ARRAYSIZE(pe_dirname)*j); if (*is_syslinux_cfg) { // Maintain a list of all the isolinux/syslinux configs identified so far StrArrayAdd(&config_path, psz_fullpath); } if (safe_stricmp(psz_basename, isolinux_bin) == 0) { // Maintain a list of all the isolinux.bin files found StrArrayAdd(&isolinux_path, psz_fullpath); } for (i=0; i<NB_OLD_C32; i++) { if (is_old_c32[i]) iso_report.has_old_c32[i] = TRUE; } if (i_file_length >= FOUR_GIGABYTES) iso_report.has_4GB_file = TRUE; // Compute projected size needed total_blocks += i_file_length/UDF_BLOCKSIZE; // NB: ISO_BLOCKSIZE = UDF_BLOCKSIZE if ((i_file_length != 0) && (i_file_length%ISO_BLOCKSIZE == 0)) // total_blocks++; return TRUE; } // In case there's an ldlinux.sys on the ISO, prevent it from overwriting ours if ((*psz_dirname == 0) && (safe_strcmp(psz_basename, ldlinux_name) == 0)) { uprintf("skipping % file from ISO image\n", ldlinux_name); return TRUE; } return FALSE; }
int SCHED_CONFIG::parse(FILE* f) { char buf[256]; MIOFILE mf; XML_PARSER xp(&mf); int retval, itemp; regex_t re; double x; mf.init_file(f); memset(this, 0, sizeof(*this)); ban_os = new vector<regex_t>; ban_cpu = new vector<regex_t>; locality_scheduling_workunit_file = new vector<regex_t>; locality_scheduling_sticky_file = new vector<regex_t>; max_wus_to_send = 10; default_disk_max_used_gb = 100.; default_disk_max_used_pct = 50.; default_disk_min_free_gb = .001; sched_debug_level = MSG_NORMAL; fuh_debug_level = MSG_NORMAL; strcpy(httpd_user, "apache"); max_ncpus = MAX_NCPUS; scheduler_log_buffer = 32768; version_select_random_factor = 1.; maintenance_delay = 3600; if (!xp.parse_start("boinc")) return ERR_XML_PARSE; if (!xp.parse_start("config")) return ERR_XML_PARSE; while (!xp.get_tag()) { if (!xp.is_tag) { fprintf(stderr, "SCHED_CONFIG::parse(): unexpected text %s\n", xp.parsed_tag ); continue; } if (xp.match_tag("/config")) { char hostname[256]; gethostname(hostname, 256); if (!strcmp(hostname, db_host)) strcpy(db_host, "localhost"); if (!strlen(replica_db_host)) { safe_strcpy(replica_db_host, db_host); } if (!strlen(replica_db_name)) { safe_strcpy(replica_db_name, db_name); } if (!strlen(replica_db_user)) { safe_strcpy(replica_db_user, db_user); } if (!strlen(replica_db_passwd)) { safe_strcpy(replica_db_passwd, db_passwd); } return 0; } if (xp.parse_str("master_url", master_url, sizeof(master_url))) continue; if (xp.parse_str("long_name", long_name, sizeof(long_name))) continue; if (xp.parse_str("db_name", db_name, sizeof(db_name))) continue; if (xp.parse_str("db_user", db_user, sizeof(db_user))) continue; if (xp.parse_str("db_passwd", db_passwd, sizeof(db_passwd))) continue; if (xp.parse_str("db_host", db_host, sizeof(db_host))) continue; if (xp.parse_str("replica_db_name", replica_db_name, sizeof(replica_db_name))) continue; if (xp.parse_str("replica_db_user", replica_db_user, sizeof(replica_db_user))) continue; if (xp.parse_str("replica_db_passwd", replica_db_passwd, sizeof(replica_db_passwd))) continue; if (xp.parse_str("replica_db_host", replica_db_host, sizeof(replica_db_host))) continue; if (xp.parse_str("project_dir", project_dir, sizeof(project_dir))) continue; if (xp.parse_int("shmem_key", shmem_key)) continue; if (xp.parse_str("key_dir", key_dir, sizeof(key_dir))) continue; if (xp.parse_str("download_url", download_url, sizeof(download_url))) continue; if (xp.parse_str("download_dir", download_dir, sizeof(download_dir))) continue; if (xp.parse_str("upload_url", upload_url, sizeof(upload_url))) continue; if (xp.parse_str("upload_dir", upload_dir, sizeof(upload_dir))) continue; if (xp.parse_bool("non_cpu_intensive", non_cpu_intensive)) continue; if (xp.parse_bool("verify_files_on_app_start", verify_files_on_app_start)) continue; if (xp.parse_int("homogeneous_redundancy", homogeneous_redundancy)) continue; if (xp.parse_bool("hr_allocate_slots", hr_allocate_slots)) continue; if (xp.parse_bool("msg_to_host", msg_to_host)) continue; if (xp.parse_bool("ignore_upload_certificates", ignore_upload_certificates)) continue; if (xp.parse_bool("dont_generate_upload_certificates", dont_generate_upload_certificates)) continue; if (xp.parse_int("uldl_dir_fanout", uldl_dir_fanout)) continue; if (xp.parse_bool("cache_md5_info", cache_md5_info)) continue; if (xp.parse_int("fuh_debug_level", fuh_debug_level)) continue; if (xp.parse_int("reliable_priority_on_over", reliable_priority_on_over)) continue; if (xp.parse_int("reliable_priority_on_over_except_error", reliable_priority_on_over_except_error)) continue; if (xp.parse_int("reliable_on_priority", reliable_on_priority)) continue; if (xp.parse_double("grace_period_hours", x)) { report_grace_period = (int)(x*3600); continue; } if (xp.parse_int("report_grace_period", report_grace_period)) continue; if (xp.parse_double("delete_delay_hours", x)) { delete_delay = x*3600; continue; } if (xp.parse_bool("distinct_beta_apps", distinct_beta_apps)) continue; if (xp.parse_bool("ended", ended)) continue; if (xp.parse_int("shmem_work_items", shmem_work_items)) continue; if (xp.parse_int("feeder_query_size", feeder_query_size)) continue; if (xp.parse_str("httpd_user", httpd_user, sizeof(httpd_user))) continue; if (xp.parse_bool("enable_vda", enable_vda)) continue; if (xp.parse_double("vda_host_timeout", vda_host_timeout)) continue; if (xp.parse_bool("enable_assignment", enable_assignment)) continue; if (xp.parse_bool("enable_assignment_multi", enable_assignment_multi)) continue; if (xp.parse_bool("job_size_matching", job_size_matching)) continue; if (xp.parse_bool("dont_send_jobs", dont_send_jobs)) continue; if (xp.parse_bool("estimate_flops_from_hav_pfc", estimate_flops_from_hav_pfc)) continue; //////////// STUFF RELEVANT ONLY TO SCHEDULER STARTS HERE /////// if (xp.parse_str("ban_cpu", buf, sizeof(buf))) { retval = regcomp(&re, buf, REG_EXTENDED|REG_NOSUB); if (retval) { log_messages.printf(MSG_CRITICAL, "BAD REGEXP: %s\n", buf); } else { ban_cpu->push_back(re); } continue; } if (xp.parse_str("ban_os", buf, sizeof(buf))) { retval = regcomp(&re, buf, REG_EXTENDED|REG_NOSUB); if (retval) { log_messages.printf(MSG_CRITICAL, "BAD REGEXP: %s\n", buf); } else { ban_os->push_back(re); } continue; } if (xp.parse_int("dont_search_host_for_user", retval)) { dont_search_host_for_userid.push_back(retval); continue; } if (xp.parse_int("daily_result_quota", daily_result_quota)) continue; if (xp.parse_double("default_disk_max_used_gb", default_disk_max_used_gb)) continue; if (xp.parse_double("default_disk_max_used_pct", default_disk_max_used_pct)) continue; if (xp.parse_double("default_disk_min_free_gb", default_disk_min_free_gb)) continue; if (xp.parse_bool("dont_store_success_stderr", dont_store_success_stderr)) continue; if (xp.parse_int("file_deletion_strategy", file_deletion_strategy)) continue; if (xp.parse_int("gpu_multiplier", gpu_multiplier)) continue; if (xp.parse_bool("ignore_delay_bound", ignore_delay_bound)) continue; if (xp.parse_bool("locality_scheduling", locality_scheduling)) continue; if (xp.parse_double("locality_scheduler_fraction", locality_scheduler_fraction)) continue; if (xp.parse_bool("locality_scheduling_sorted_order", locality_scheduling_sorted_order)) continue; if (xp.parse_int("locality_scheduling_wait_period", locality_scheduling_wait_period)) continue; if (xp.parse_int("locality_scheduling_send_timeout", locality_scheduling_send_timeout)) continue; if (xp.parse_str("locality_scheduling_workunit_file", buf, sizeof(buf))) { retval = regcomp(&re, buf, REG_EXTENDED|REG_NOSUB); if (retval) { log_messages.printf(MSG_CRITICAL, "BAD REGEXP: %s\n", buf); } else { locality_scheduling_workunit_file->push_back(re); } continue; } if (xp.parse_str("locality_scheduling_sticky_file", buf, sizeof(buf))) { retval = regcomp(&re, buf, REG_EXTENDED|REG_NOSUB); if (retval) { log_messages.printf(MSG_CRITICAL, "BAD REGEXP: %s\n", buf); } else { locality_scheduling_sticky_file->push_back(re); } continue; } if (xp.parse_bool("sched_old", sched_old)) continue; if (xp.parse_int("max_ncpus", max_ncpus)) continue; if (xp.parse_int("max_wus_in_progress", itemp)) { max_jobs_in_progress.project_limits.proc_type_limits[PROC_TYPE_CPU].base_limit = itemp; max_jobs_in_progress.project_limits.proc_type_limits[PROC_TYPE_CPU].per_proc = true; continue; } if (xp.parse_int("max_wus_in_progress_gpu", itemp)) { for (int i=1; i<NPROC_TYPES; i++) { max_jobs_in_progress.project_limits.proc_type_limits[i].base_limit = itemp; max_jobs_in_progress.project_limits.proc_type_limits[i].per_proc = true; } continue; } if (xp.parse_int("max_results_accepted", max_results_accepted)) continue; if (xp.parse_int("max_wus_to_send", max_wus_to_send)) continue; if (xp.parse_int("min_core_client_version", min_core_client_version)) { if (min_core_client_version && min_core_client_version < 10000) { log_messages.printf(MSG_CRITICAL, "min_core_client_version too small; multiplying by 100\n" ); min_core_client_version *= 100; } continue; } if (xp.parse_int("min_core_client_version_announced", min_core_client_version_announced)) { if (min_core_client_version_announced && min_core_client_version_announced < 10000) { log_messages.printf(MSG_CRITICAL, "min_core_client_version_announced too small; multiplying by 100\n" ); min_core_client_version_announced *= 100; } continue; } if (xp.parse_int("min_core_client_upgrade_deadline", min_core_client_upgrade_deadline)) continue; if (xp.parse_int("min_sendwork_interval", min_sendwork_interval)) continue; if (xp.parse_double("next_rpc_delay", next_rpc_delay)) continue; if (xp.parse_bool("no_amd_k6", no_amd_k6)) { if (no_amd_k6) { regcomp(&re, ".*AMD.*\t.*Family 5 Model 8 Stepping 0.*", REG_EXTENDED|REG_NOSUB); ban_cpu->push_back(re); } continue; } if (xp.parse_bool("no_vista_sandbox", no_vista_sandbox)) continue; if (xp.parse_bool("nowork_skip", nowork_skip)) continue; if (xp.parse_bool("one_result_per_host_per_wu", one_result_per_host_per_wu)) continue; if (xp.parse_bool("one_result_per_user_per_wu", one_result_per_user_per_wu)) continue; if (xp.parse_int("reliable_max_avg_turnaround", reliable_max_avg_turnaround)) continue; if (xp.parse_double("reliable_max_error_rate", reliable_max_error_rate)) continue; if (xp.parse_double("reliable_reduced_delay_bound", reliable_reduced_delay_bound)) continue; if (xp.parse_str("replace_download_url_by_timezone", replace_download_url_by_timezone, sizeof(replace_download_url_by_timezone))) continue; if (xp.parse_int("max_download_urls_per_file", max_download_urls_per_file)) continue; if (xp.parse_int("report_max", report_max)) continue; if (xp.parse_bool("request_time_stats_log", request_time_stats_log)) continue; if (xp.parse_bool("resend_lost_results", resend_lost_results)) continue; if (xp.parse_int("sched_debug_level", sched_debug_level)) continue; if (xp.parse_int("scheduler_log_buffer", scheduler_log_buffer)) continue; if (xp.parse_str("sched_lockfile_dir", sched_lockfile_dir, sizeof(sched_lockfile_dir))) continue; if (xp.parse_bool("send_result_abort", send_result_abort)) continue; if (xp.parse_str("symstore", symstore, sizeof(symstore))) continue; if (xp.parse_bool("user_filter", user_filter)) continue; if (xp.parse_bool("workload_sim", workload_sim)) continue; if (xp.parse_bool("prefer_primary_platform", prefer_primary_platform)) continue; if (xp.parse_double("version_select_random_factor", version_select_random_factor)) continue; if (xp.parse_double("maintenance_delay", maintenance_delay)) continue; if (xp.parse_bool("credit_by_app", credit_by_app)) continue; //////////// SCHEDULER LOG FLAGS ///////// if (xp.parse_bool("debug_assignment", debug_assignment)) continue; if (xp.parse_bool("debug_client_files", debug_client_files)) continue; if (xp.parse_bool("debug_credit", debug_credit)) continue; if (xp.parse_bool("debug_edf_sim_detail", debug_edf_sim_detail)) continue; if (xp.parse_bool("debug_edf_sim_workload", debug_edf_sim_workload)) continue; if (xp.parse_bool("debug_fcgi", debug_fcgi)) continue; if (xp.parse_bool("debug_handle_results", debug_handle_results)) continue; if (xp.parse_bool("debug_locality", debug_locality)) continue; if (xp.parse_bool("debug_locality_lite", debug_locality_lite)) continue; if (xp.parse_bool("debug_prefs", debug_prefs)) continue; if (xp.parse_bool("debug_quota", debug_quota)) continue; if (xp.parse_bool("debug_request_details", debug_request_details)) continue; if (xp.parse_bool("debug_request_headers", debug_request_headers)) continue; if (xp.parse_bool("debug_resend", debug_resend)) continue; if (xp.parse_bool("debug_send", debug_send)) continue; if (xp.parse_bool("debug_send_job", debug_send_job)) continue; if (xp.parse_bool("debug_send_scan", debug_send_scan)) continue; if (xp.parse_bool("debug_user_messages", debug_user_messages)) continue; if (xp.parse_bool("debug_vda", debug_vda)) continue; if (xp.parse_bool("debug_version_select", debug_version_select)) continue; if (xp.parse_str("debug_req_reply_dir", debug_req_reply_dir, sizeof(debug_req_reply_dir))) continue; // don't complain about unparsed XML; // there are lots of tags the scheduler doesn't know about xp.skip_unexpected(false, "SCHED_CONFIG::parse"); } return ERR_XML_PARSE; }
int result_delete_files(RESULT& result) { char* p; char filename[256], pathname[256], buf[BLOB_SIZE]; bool no_delete=false; int count_deleted = 0, retval, mthd_retval = 0; safe_strcpy(buf, result.xml_doc_in); p = strtok(buf,"\n"); while (p) { if (parse_str(p, "<name>", filename, sizeof(filename))) { } else if (match_tag(p, "<file_info>")) { no_delete = false; strcpy(filename, ""); } else if (match_tag(p, "<no_delete/>")) { no_delete = true; } else if (match_tag(p, "</file_info>")) { if (!no_delete) { retval = get_file_path( filename, config.upload_dir, config.uldl_dir_fanout, pathname ); if (retval == ERR_OPENDIR) { mthd_retval = ERR_OPENDIR; log_messages.printf(MSG_CRITICAL, "[RESULT#%d] missing dir for %s\n", result.id, pathname ); } else if (retval) { // the fact that no result files were found is a critical // error if this was a successful result, but is to be // expected if the result outcome was failure, since in // that case there may well be no output file produced. // int debug_or_crit; if (RESULT_OUTCOME_SUCCESS == result.outcome) { debug_or_crit=MSG_CRITICAL; } else { debug_or_crit=MSG_DEBUG; } log_messages.printf(debug_or_crit, "[RESULT#%d] outcome=%d client_state=%d No file %s to delete\n", result.id, result.outcome, result.client_state, filename ); } else { retval = unlink(pathname); if (retval) { mthd_retval = ERR_UNLINK; log_messages.printf(MSG_CRITICAL, "[RESULT#%d] unlink %s error: %s %s\n", result.id, pathname, boincerror(retval), (retval && errno)?strerror(errno):"" ); } else { count_deleted++; log_messages.printf(MSG_NORMAL, "[RESULT#%d] unlinked %s\n", result.id, pathname ); } } } } p = strtok(0, "\n"); } log_messages.printf(MSG_DEBUG, "[RESULT#%d] deleted %d file(s)\n", result.id, count_deleted ); return mthd_retval; }
void PROJECT::init() { safe_strcpy(master_url, ""); safe_strcpy(authenticator, ""); safe_strcpy(_project_dir, ""); safe_strcpy(_project_dir_absolute, ""); project_specific_prefs = ""; gui_urls = ""; resource_share = 100; desired_disk_usage = 0; for (int i=0; i<MAX_RSC; i++) { no_rsc_pref[i] = false; no_rsc_config[i] = false; no_rsc_apps[i] = false; no_rsc_ams[i] = false; } safe_strcpy(host_venue, ""); using_venue_specific_prefs = false; scheduler_urls.clear(); safe_strcpy(project_name, ""); safe_strcpy(symstore, ""); safe_strcpy(user_name, ""); safe_strcpy(team_name, ""); safe_strcpy(email_hash, ""); safe_strcpy(cross_project_id, ""); safe_strcpy(external_cpid, ""); cpid_time = 0; user_total_credit = 0; user_expavg_credit = 0; user_create_time = 0; ams_resource_share = -1; rpc_seqno = 0; userid = 0; teamid = 0; hostid = 0; host_total_credit = 0; host_expavg_credit = 0; host_create_time = 0; nrpc_failures = 0; master_fetch_failures = 0; min_rpc_time = 0; possibly_backed_off = true; master_url_fetch_pending = false; sched_rpc_pending = 0; next_rpc_time = 0; last_rpc_time = 0; trickle_up_pending = false; anonymous_platform = false; non_cpu_intensive = false; verify_files_on_app_start = false; pwf.reset(this); send_time_stats_log = 0; send_job_log = 0; send_full_workload = false; dont_use_dcf = false; suspended_via_gui = false; dont_request_more_work = false; detach_when_done = false; attached_via_acct_mgr = false; ended = false; safe_strcpy(code_sign_key, ""); user_files.clear(); project_files.clear(); next_runnable_result = NULL; duration_correction_factor = 1; project_files_downloaded_time = 0; use_symlinks = false; possibly_backed_off = false; nuploading_results = 0; too_many_uploading_results = false; njobs_success = 0; njobs_error = 0; elapsed_time = 0; app_configs.clear(); #ifdef SIM idle_time = 0; idle_time_sumsq = 0; completed_task_count = 0; completions_ratio_mean = 0.0; completions_ratio_s = 0.0; completions_ratio_stdev = 0.1; // for the first couple of completions - guess. completions_required_stdevs = 3.0; result_index = 0; ignore = false; #endif }
static void process_named_msg (session *sess, char *type, char *word[], char *word_eol[]) { server *serv = sess->server; char ip[128], nick[NICKLEN]; char *text, *ex; int len = strlen (type); /* fill in the "ip" and "nick" buffers */ ex = strchr (word[1], '!'); if (!ex) /* no '!', must be a server message */ { safe_strcpy (ip, word[1], sizeof (ip)); safe_strcpy (nick, word[1], sizeof (nick)); } else { safe_strcpy (ip, ex + 1, sizeof (ip)); ex[0] = 0; safe_strcpy (nick, word[1], sizeof (nick)); ex[0] = '!'; } if (len == 4) { guint32 t; t = WORDL((guint8)type[0], (guint8)type[1], (guint8)type[2], (guint8)type[3]); /* this should compile to a bunch of: CMP.L, JE ... nice & fast */ switch (t) { case WORDL('J','O','I','N'): { char *chan = word[3]; if (*chan == ':') chan++; if (!serv->p_cmp (nick, serv->nick)) inbound_ujoin (serv, chan, nick, ip); else inbound_join (serv, chan, nick, ip); } return; case WORDL('K','I','C','K'): { char *kicked = word[4]; char *reason = word_eol[5]; if (*kicked) { if (*reason == ':') reason++; if (!strcmp (kicked, serv->nick)) inbound_ukick (serv, word[3], nick, reason); else inbound_kick (serv, word[3], kicked, nick, reason); } } return; case WORDL('K','I','L','L'): EMIT_SIGNAL (XP_TE_KILL, sess, nick, word_eol[5], NULL, NULL, 0); return; case WORDL('M','O','D','E'): handle_mode (serv, word, word_eol, nick, FALSE); /* modes.c */ return; case WORDL('N','I','C','K'): inbound_newnick (serv, nick, (word_eol[3][0] == ':') ? word_eol[3] + 1 : word_eol[3], FALSE); return; case WORDL('P','A','R','T'): { char *chan = word[3]; char *reason = word_eol[4]; if (*chan == ':') chan++; if (*reason == ':') reason++; if (!strcmp (nick, serv->nick)) inbound_upart (serv, chan, ip, reason); else inbound_part (serv, chan, nick, ip, reason); } return; case WORDL('P','O','N','G'): inbound_ping_reply (serv->server_session, (word[4][0] == ':') ? word[4] + 1 : word[4], word[3]); return; case WORDL('Q','U','I','T'): inbound_quit (serv, nick, ip, (word_eol[3][0] == ':') ? word_eol[3] + 1 : word_eol[3]); return; } goto garbage; } else if (len >= 5) { guint32 t; t = WORDL((guint8)type[0], (guint8)type[1], (guint8)type[2], (guint8)type[3]); /* this should compile to a bunch of: CMP.L, JE ... nice & fast */ switch (t) { case WORDL('I','N','V','I'): if (ignore_check (word[1], IG_INVI)) return; if (word[4][0] == ':') EMIT_SIGNAL (XP_TE_INVITED, sess, word[4] + 1, nick, serv->servername, NULL, 0); else EMIT_SIGNAL (XP_TE_INVITED, sess, word[4], nick, serv->servername, NULL, 0); return; case WORDL('N','O','T','I'): { int id = FALSE; /* identified */ text = word_eol[4]; if (*text == ':') text++; if (serv->have_idmsg) { if (*text == '+') { id = TRUE; text++; } else if (*text == '-') text++; } if (!ignore_check (word[1], IG_NOTI)) inbound_notice (serv, word[3], nick, text, ip, id); } return; case WORDL('P','R','I','V'): { char *to = word[3]; int len; int id = FALSE; /* identified */ if (*to) { text = word_eol[4]; if (*text == ':') text++; if (serv->have_idmsg) { if (*text == '+') { id = TRUE; text++; } else if (*text == '-') text++; } len = strlen (text); if (text[0] == 1 && text[len - 1] == 1) /* ctcp */ { text[len - 1] = 0; text++; if (strncasecmp (text, "ACTION", 6) != 0) flood_check (nick, ip, serv, sess, 0); if (strncasecmp (text, "DCC ", 4) == 0) /* redo this with handle_quotes TRUE */ process_data_init (word[1], word_eol[1], word, word_eol, TRUE, FALSE); ctcp_handle (sess, to, nick, ip, text, word, word_eol, id); } else { if (is_channel (serv, to)) { if (ignore_check (word[1], IG_CHAN)) return; inbound_chanmsg (serv, NULL, to, nick, text, FALSE, id); } else { if (ignore_check (word[1], IG_PRIV)) return; inbound_privmsg (serv, nick, ip, text, id); } } } } return; case WORDL('T','O','P','I'): inbound_topicnew (serv, nick, word[3], (word_eol[4][0] == ':') ? word_eol[4] + 1 : word_eol[4]); return; case WORDL('W','A','L','L'): text = word_eol[3]; if (*text == ':') text++; EMIT_SIGNAL (XP_TE_WALLOPS, sess, nick, text, NULL, NULL, 0); return; } } else if (len == 3) { guint32 t; t = WORDL((guint8)type[0], (guint8)type[1], (guint8)type[2], (guint8)type[3]); switch (t) { case WORDL('C','A','P','\0'): if (strncasecmp(word[4], "ACK", 3) == 0) { if (strncasecmp(word[5][0]==':' ? word[5]+1 : word[5], "identify-msg", 12) == 0) { serv->have_idmsg = TRUE; tcp_send_len(serv, "CAP END\r\n", 9); } } else if (strncasecmp(word[4], "LS", 2) == 0) { if (strstr(word_eol[5], "identify-msg") != 0) tcp_send_len(serv, "CAP REQ :identify-msg\r\n", 23); else tcp_send_len(serv, "CAP END\r\n", 9); } else if (strncasecmp(word[4], "NAK",3) == 0) { tcp_send_len(serv, "CAP END\r\n", 9); } return; } } garbage: /* unknown message */ PrintTextf (sess, "GARBAGE: %s\n", word_eol[1]); }
int wu_delete_files(WORKUNIT& wu) { char* p; char filename[256], pathname[256], buf[BLOB_SIZE]; bool no_delete=false; int count_deleted = 0, retval, mthd_retval = 0; if (strstr(wu.name, "nodelete")) return 0; safe_strcpy(buf, wu.xml_doc); p = strtok(buf, "\n"); strcpy(filename, ""); while (p) { if (parse_str(p, "<name>", filename, sizeof(filename))) { } else if (match_tag(p, "<file_info>")) { no_delete = false; strcpy(filename, ""); } else if (match_tag(p, "<no_delete/>")) { no_delete = true; } else if (match_tag(p, "</file_info>")) { if (!no_delete) { retval = get_file_path( filename, config.download_dir, config.uldl_dir_fanout, pathname ); if (retval == ERR_OPENDIR) { log_messages.printf(MSG_CRITICAL, "[WU#%d] missing dir for %s\n", wu.id, filename ); mthd_retval = ERR_UNLINK; } else if (retval) { log_messages.printf(MSG_CRITICAL, "[WU#%d] get_file_path: %s: %s\n", wu.id, filename, boincerror(retval) ); } else { log_messages.printf(MSG_NORMAL, "[WU#%d] deleting %s\n", wu.id, filename ); retval = unlink(pathname); if (retval) { log_messages.printf(MSG_CRITICAL, "[WU#%d] unlink %s failed: %s\n", wu.id, filename, boincerror(retval) ); mthd_retval = ERR_UNLINK; } else { count_deleted++; } // delete the cached MD5 file if needed // if (config.cache_md5_info) { strcat(pathname,".md5"); log_messages.printf(MSG_NORMAL, "[WU#%d] deleting %s\n", wu.id, filename ); retval = unlink(pathname); if (retval) { log_messages.printf(MSG_CRITICAL, "[WU#%d] unlink %s failed: %s\n", wu.id, filename, boincerror(retval) ); } } } } } p = strtok(0, "\n"); } log_messages.printf(MSG_DEBUG, "[WU#%d] deleted %d file(s)\n", wu.id, count_deleted ); return mthd_retval; }
sint32 platform_enumerate_files_begin(const utf8 *pattern) { char npattern[MAX_PATH]; platform_utf8_to_multibyte(pattern, npattern, MAX_PATH); enumerate_file_info *enumFileInfo; log_verbose("begin file search, pattern: %s", npattern); char *file_name = strrchr(npattern, *PATH_SEPARATOR); char *dir_name; if (file_name != NULL) { dir_name = strndup(npattern, file_name - npattern); file_name = &file_name[1]; } else { file_name = npattern; dir_name = strdup("."); } sint32 pattern_length = strlen(file_name); g_file_pattern = strndup(file_name, pattern_length); for (sint32 j = 0; j < pattern_length; j++) { g_file_pattern[j] = (char)toupper(g_file_pattern[j]); } log_verbose("looking for file matching %s", g_file_pattern); sint32 cnt; for (sint32 i = 0; i < countof(_enumerateFileInfoList); i++) { enumFileInfo = &_enumerateFileInfoList[i]; if (!enumFileInfo->active) { safe_strcpy(enumFileInfo->pattern, npattern, sizeof(enumFileInfo->pattern)); cnt = scandir(dir_name, &enumFileInfo->fileListTemp, winfilter, alphasort); if (cnt < 0) { break; } log_verbose("found %d files matching in dir '%s'", cnt, dir_name); enumFileInfo->cnt = cnt; enumFileInfo->paths = malloc(cnt * sizeof(char *)); char **paths = enumFileInfo->paths; // 256 is size of dirent.d_name const sint32 dir_name_len = strnlen(dir_name, MAX_PATH); for (sint32 idx = 0; idx < cnt; idx++) { struct dirent *d = enumFileInfo->fileListTemp[idx]; const sint32 entry_len = strnlen(d->d_name, MAX_PATH); // 1 for separator, 1 for trailing null size_t path_len = sizeof(char) * min(MAX_PATH, entry_len + dir_name_len + 2); paths[idx] = malloc(path_len); log_verbose("dir_name: %s", dir_name); safe_strcpy(paths[idx], dir_name, path_len); safe_strcat_path(paths[idx], d->d_name, path_len); log_verbose("paths[%d] = %s", idx, paths[idx]); // macOS uses decomposed Unicode strings (e.g. an 'e' and a combining accent) in filenames // This causes problems with the sprite font, as the font only contains precomposed characters // The block below converts all filename strings to their precomposed form, preventing mojibake #ifdef __APPLE__ utf8* precomp_path = macos_str_decomp_to_precomp(paths[idx]); size_t precomp_len = sizeof(utf8) * min(MAX_PATH, strnlen(precomp_path, MAX_PATH) + 2); paths[idx] = malloc(precomp_len); safe_strcpy(paths[idx], precomp_path, precomp_len); log_verbose("macOS decomp-to-precomp fix - paths[%d] = %s", idx, paths[idx]); #endif } enumFileInfo->handle = 0; enumFileInfo->active = 1; free(dir_name); free(g_file_pattern); g_file_pattern = NULL; return i; } } free(dir_name); free(g_file_pattern); g_file_pattern = NULL; return -1; }
void platform_get_openrct_data_path(utf8 *outPath, size_t outSize) { safe_strcpy(outPath, _openrctDataDirectoryPath, outSize); }
/* * Refresh the list of USB devices */ BOOL GetUSBDevices(DWORD devnum) { // The first two are standard Microsoft drivers (including the Windows 8 UASP one). // The rest are the vendor UASP drivers I know of so far - list may be incomplete! const char* storage_name[] = { "USBSTOR", "UASPSTOR", "VUSBSTOR", "ETRONSTOR", "ASUSSTPT" }; const char* scsi_name = "SCSI"; const char* usb_speed_name[USB_SPEED_MAX] = { "USB", "USB 1.0", "USB 1.1", "USB 2.0", "USB 3.0" }; // Hash table and String Array used to match a Device ID with the parent hub's Device Interface Path htab_table htab_devid = HTAB_EMPTY; StrArray dev_if_path; char letter_name[] = " (?:)"; char uefi_togo_check[] = "?:\\EFI\\Rufus\\ntfs_x64.efi"; BOOL r = FALSE, found = FALSE, is_SCSI; HDEVINFO dev_info = NULL; SP_DEVINFO_DATA dev_info_data; SP_DEVICE_INTERFACE_DATA devint_data; PSP_DEVICE_INTERFACE_DETAIL_DATA_A devint_detail_data; DEVINST parent_inst, grandparent_inst, device_inst; DWORD size, i, j, k, l, datatype, drive_index; ULONG list_size[ARRAYSIZE(storage_name)] = { 0 }, list_start[ARRAYSIZE(storage_name)] = { 0 }, full_list_size, ulFlags; HANDLE hDrive; LONG maxwidth = 0; int s, score, drive_number; char drive_letters[27], *device_id, *devid_list = NULL, entry_msg[128]; char *label, *entry, buffer[MAX_PATH], str[MAX_PATH], *method_str; usb_device_props props; IGNORE_RETVAL(ComboBox_ResetContent(hDeviceList)); StrArrayClear(&DriveID); StrArrayClear(&DriveLabel); StrArrayCreate(&dev_if_path, 128); // Add a dummy for string index zero, as this is what non matching hashes will point to StrArrayAdd(&dev_if_path, ""); device_id = (char*)malloc(MAX_PATH); if (device_id == NULL) goto out; // Build a hash table associating a CM Device ID of an USB device with the SetupDI Device Interface Path // of its parent hub - this is needed to retrieve the device speed dev_info = SetupDiGetClassDevsA(&_GUID_DEVINTERFACE_USB_HUB, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE); if (dev_info != INVALID_HANDLE_VALUE) { if (htab_create(DEVID_HTAB_SIZE, &htab_devid)) { dev_info_data.cbSize = sizeof(dev_info_data); for (i=0; SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data); i++) { if (usb_debug) uprintf("Processing Hub %d:", i + 1); devint_detail_data = NULL; devint_data.cbSize = sizeof(devint_data); // Only care about the first interface (MemberIndex 0) if ( (SetupDiEnumDeviceInterfaces(dev_info, &dev_info_data, &_GUID_DEVINTERFACE_USB_HUB, 0, &devint_data)) && (!SetupDiGetDeviceInterfaceDetailA(dev_info, &devint_data, NULL, 0, &size, NULL)) && (GetLastError() == ERROR_INSUFFICIENT_BUFFER) && ((devint_detail_data = (PSP_DEVICE_INTERFACE_DETAIL_DATA_A)calloc(1, size)) != NULL) ) { devint_detail_data->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A); if (SetupDiGetDeviceInterfaceDetailA(dev_info, &devint_data, devint_detail_data, size, &size, NULL)) { // Find the Device IDs for all the children of this hub if (CM_Get_Child(&device_inst, dev_info_data.DevInst, 0) == CR_SUCCESS) { device_id[0] = 0; s = StrArrayAdd(&dev_if_path, devint_detail_data->DevicePath); if ((s>= 0) && (CM_Get_Device_IDA(device_inst, device_id, MAX_PATH, 0) == CR_SUCCESS)) { if ((k = htab_hash(device_id, &htab_devid)) != 0) { htab_devid.table[k].data = (void*)(uintptr_t)s; } if (usb_debug) uprintf(" Found ID[%03d]: %s", k, device_id); while (CM_Get_Sibling(&device_inst, device_inst, 0) == CR_SUCCESS) { device_id[0] = 0; if (CM_Get_Device_IDA(device_inst, device_id, MAX_PATH, 0) == CR_SUCCESS) { if ((k = htab_hash(device_id, &htab_devid)) != 0) { htab_devid.table[k].data = (void*)(uintptr_t)s; } if (usb_debug) uprintf(" Found ID[%03d]: %s", k, device_id); } } } } } free(devint_detail_data); } } } SetupDiDestroyDeviceInfoList(dev_info); } free(device_id); // Build a single list of Device IDs from all the storage enumerators we know of full_list_size = 0; ulFlags = CM_GETIDLIST_FILTER_SERVICE; if (nWindowsVersion >= WINDOWS_7) ulFlags |= CM_GETIDLIST_FILTER_PRESENT; for (s=0; s<ARRAYSIZE(storage_name); s++) { // Get a list of device IDs for all USB storage devices // This will be used to find if a device is UASP if (CM_Get_Device_ID_List_SizeA(&list_size[s], storage_name[s], ulFlags) != CR_SUCCESS) list_size[s] = 0; if (list_size[s] != 0) full_list_size += list_size[s]-1; // remove extra NUL terminator } devid_list = NULL; if (full_list_size != 0) { full_list_size += 1; // add extra NUL terminator devid_list = (char*)malloc(full_list_size); if (devid_list == NULL) { uprintf("Could not allocate Device ID list\n"); return FALSE; } for (s=0, i=0; s<ARRAYSIZE(storage_name); s++) { list_start[s] = i; if (list_size[s] > 1) { if (CM_Get_Device_ID_ListA(storage_name[s], &devid_list[i], list_size[s], ulFlags) != CR_SUCCESS) continue; if (usb_debug) { uprintf("Processing IDs belonging to %s:", storage_name[s]); for (device_id = &devid_list[i]; *device_id != 0; device_id += strlen(device_id) + 1) uprintf(" %s", device_id); } // The list_size is sometimes larger than required thus we need to find the real end for (i += list_size[s]; i > 2; i--) { if ((devid_list[i-2] != '\0') && (devid_list[i-1] == '\0') && (devid_list[i] == '\0')) break; } } } } // Now use SetupDi to enumerate all our storage devices dev_info = SetupDiGetClassDevsA(&_GUID_DEVINTERFACE_DISK, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE); if (dev_info == INVALID_HANDLE_VALUE) { uprintf("SetupDiGetClassDevs (Interface) failed: %s\n", WindowsErrorString()); goto out; } dev_info_data.cbSize = sizeof(dev_info_data); for (i=0; SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data); i++) { memset(buffer, 0, sizeof(buffer)); method_str = ""; if (!SetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_ENUMERATOR_NAME, &datatype, (LPBYTE)buffer, sizeof(buffer), &size)) { uprintf("SetupDiGetDeviceRegistryProperty (Enumerator Name) failed: %s\n", WindowsErrorString()); continue; } // UASP drives are listed under SCSI (along with regular SYSTEM drives => "DANGER, WILL ROBINSON!!!") is_SCSI = (safe_stricmp(buffer, scsi_name) == 0); if ((safe_stricmp(buffer, storage_name[0]) != 0) && (!is_SCSI)) continue; // We can't use the friendly name to find if a drive is a VHD, as friendly name string gets translated // according to your locale, so we poke the Hardware ID memset(&props, 0, sizeof(props)); memset(buffer, 0, sizeof(buffer)); props.is_VHD = SetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_HARDWAREID, &datatype, (LPBYTE)buffer, sizeof(buffer), &size) && IsVHD(buffer); if (usb_debug) uprintf("Processing Device: '%s'", buffer); memset(buffer, 0, sizeof(buffer)); if (!SetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_FRIENDLYNAME, &datatype, (LPBYTE)buffer, sizeof(buffer), &size)) { uprintf("SetupDiGetDeviceRegistryProperty (Friendly Name) failed: %s\n", WindowsErrorString()); // We can afford a failure on this call - just replace the name with "USB Storage Device (Generic)" safe_strcpy(buffer, sizeof(buffer), lmprintf(MSG_045)); } else if ((!props.is_VHD) && (devid_list != NULL)) { // Get the properties of the device. We could avoid doing this lookup every time by keeping // a lookup table, but there shouldn't be that many USB storage devices connected... // NB: Each of these Device IDs have an _only_ child, from which we get the Device Instance match. for (device_id = devid_list; *device_id != 0; device_id += strlen(device_id) + 1) { if ( (CM_Locate_DevNodeA(&parent_inst, device_id, 0) == CR_SUCCESS) && (CM_Get_Child(&device_inst, parent_inst, 0) == CR_SUCCESS) && (device_inst == dev_info_data.DevInst) ) { // If we're not dealing with the USBSTOR part of our list, then this is an UASP device props.is_UASP = ((((uintptr_t)device_id)+2) >= ((uintptr_t)devid_list)+list_start[1]); // Now get the properties of the device, and its Device ID, which we need to populate the properties j = htab_hash(device_id, &htab_devid); if (usb_debug) uprintf(" Matched with ID[%03d]: %s", j, device_id); // If the hash didn't match a populated string in dev_if_path[] (htab_devid.table[j].data > 0), // we might have an extra vendor driver in between (e.g. "ASUS USB 3.0 Boost Storage Driver" // for UASP devices in ASUS "Turbo Mode" or "Apple Mobile Device USB Driver" for iPods) // so try to see if we can match the grandparent. if ( ((uint32_t)htab_devid.table[j].data == 0) && (CM_Get_Parent(&grandparent_inst, parent_inst, 0) == CR_SUCCESS) && (CM_Get_Device_IDA(grandparent_inst, str, MAX_PATH, 0) == CR_SUCCESS) ) { device_id = str; method_str = "[GP]"; j = htab_hash(device_id, &htab_devid); if (usb_debug) uprintf(" Matched with (GP) ID[%03d]: %s", j, device_id); } if ((uint32_t)htab_devid.table[j].data > 0) GetUSBProperties(dev_if_path.String[(uint32_t)htab_devid.table[j].data], device_id, &props); if (usb_debug) uprintf(" Props VID:PID = %04X:%04X", props.vid, props.pid); // If previous calls still didn't succeed, try reading the VID:PID from the device_id if ((props.vid == 0) && (props.pid == 0)) { BOOL post_backslash = FALSE; method_str = "[ID]"; for (j=0, k=0; (j<strlen(device_id))&&(k<2); j++) { // The ID is in the form USB_VENDOR_BUSID\VID_xxxx&PID_xxxx\... if (device_id[j] == '\\') post_backslash = TRUE; if (!post_backslash) continue; if (device_id[j] == '_') { props.pid = (uint16_t)strtoul(&device_id[j+1], NULL, 16); if (k++==0) props.vid = props.pid; } } } } } } if (props.is_VHD) { uprintf("Found VHD device '%s'", buffer); } else { if ((props.vid == 0) && (props.pid == 0)) { if (is_SCSI) { // If we have an SCSI drive and couldn't get a VID:PID, we are most likely // dealing with a system drive => eliminate it! if (usb_debug) uprintf(" Non USB => Eliminated"); continue; } safe_strcpy(str, sizeof(str), "????:????"); // Couldn't figure VID:PID } else { static_sprintf(str, "%04X:%04X", props.vid, props.pid); } if (props.speed >= USB_SPEED_MAX) props.speed = 0; uprintf("Found %s%s%s device '%s' (%s) %s\n", props.is_UASP?"UAS (":"", usb_speed_name[props.speed], props.is_UASP?")":"", buffer, str, method_str); if (props.is_LowerSpeed) uprintf("NOTE: This device is an USB 3.0 device operating at lower speed..."); } devint_data.cbSize = sizeof(devint_data); hDrive = INVALID_HANDLE_VALUE; devint_detail_data = NULL; for (j=0; ;j++) { safe_closehandle(hDrive); safe_free(devint_detail_data); if (!SetupDiEnumDeviceInterfaces(dev_info, &dev_info_data, &_GUID_DEVINTERFACE_DISK, j, &devint_data)) { if(GetLastError() != ERROR_NO_MORE_ITEMS) { uprintf("SetupDiEnumDeviceInterfaces failed: %s\n", WindowsErrorString()); } else { uprintf("A device was eliminated because it didn't report itself as a disk\n"); } break; } if (!SetupDiGetDeviceInterfaceDetailA(dev_info, &devint_data, NULL, 0, &size, NULL)) { if(GetLastError() == ERROR_INSUFFICIENT_BUFFER) { devint_detail_data = (PSP_DEVICE_INTERFACE_DETAIL_DATA_A)calloc(1, size); if (devint_detail_data == NULL) { uprintf("Unable to allocate data for SP_DEVICE_INTERFACE_DETAIL_DATA\n"); continue; } devint_detail_data->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A); } else { uprintf("SetupDiGetDeviceInterfaceDetail (dummy) failed: %s\n", WindowsErrorString()); continue; } } if (devint_detail_data == NULL) { uprintf("SetupDiGetDeviceInterfaceDetail (dummy) - no data was allocated\n"); continue; } if(!SetupDiGetDeviceInterfaceDetailA(dev_info, &devint_data, devint_detail_data, size, &size, NULL)) { uprintf("SetupDiGetDeviceInterfaceDetail (actual) failed: %s\n", WindowsErrorString()); continue; } hDrive = CreateFileA(devint_detail_data->DevicePath, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(hDrive == INVALID_HANDLE_VALUE) { uprintf("Could not open '%s': %s\n", devint_detail_data->DevicePath, WindowsErrorString()); continue; } drive_number = GetDriveNumber(hDrive, devint_detail_data->DevicePath); if (drive_number < 0) continue; drive_index = drive_number + DRIVE_INDEX_MIN; if (!IsMediaPresent(drive_index)) { uprintf("Device eliminated because it appears to contain no media\n"); safe_closehandle(hDrive); safe_free(devint_detail_data); break; } if (GetDriveLabel(drive_index, drive_letters, &label)) { if ((!enable_HDDs) && (!props.is_VHD) && ((score = IsHDD(drive_index, (uint16_t)props.vid, (uint16_t)props.pid, buffer)) > 0)) { uprintf("Device eliminated because it was detected as an USB Hard Drive (score %d > 0)\n", score); uprintf("If this device is not an USB Hard Drive, please e-mail the author of this application\n"); uprintf("NOTE: You can enable the listing of USB Hard Drives in 'Advanced Options' (after clicking the white triangle)"); safe_closehandle(hDrive); safe_free(devint_detail_data); break; } // The empty string is returned for drives that don't have any volumes assigned if (drive_letters[0] == 0) { entry = lmprintf(MSG_046, label, drive_number, SizeToHumanReadable(GetDriveSize(drive_index), FALSE, use_fake_units)); } else { // Find the UEFI:TOGO partition(s) (and eliminate them form our listing) for (k=0; drive_letters[k]; k++) { uefi_togo_check[0] = drive_letters[k]; if (PathFileExistsA(uefi_togo_check)) { for (l=k; drive_letters[l]; l++) drive_letters[l] = drive_letters[l+1]; k--; } } // We have multiple volumes assigned to the same device (multiple partitions) // If that is the case, use "Multiple Volumes" instead of the label safe_strcpy(entry_msg, sizeof(entry_msg), ((drive_letters[0] != 0) && (drive_letters[1] != 0))? lmprintf(MSG_047):label); for (k=0; drive_letters[k]; k++) { // Append all the drive letters we detected letter_name[2] = drive_letters[k]; if (right_to_left_mode) safe_strcat(entry_msg, sizeof(entry_msg), RIGHT_TO_LEFT_MARK); safe_strcat(entry_msg, sizeof(entry_msg), letter_name); if (drive_letters[k] == (PathGetDriveNumberU(app_dir) + 'A')) break; } // Repeat as we need to break the outside loop if (drive_letters[k] == (PathGetDriveNumberU(app_dir) + 'A')) { uprintf("Removing %c: from the list: This is the disk from which " APPLICATION_NAME " is running!\n", app_dir[0]); safe_closehandle(hDrive); safe_free(devint_detail_data); break; } safe_sprintf(&entry_msg[strlen(entry_msg)], sizeof(entry_msg) - strlen(entry_msg), "%s [%s]", (right_to_left_mode)?RIGHT_TO_LEFT_MARK:"", SizeToHumanReadable(GetDriveSize(drive_index), FALSE, use_fake_units)); entry = entry_msg; } // Must ensure that the combo box is UNSORTED for indexes to be the same StrArrayAdd(&DriveID, buffer); StrArrayAdd(&DriveLabel, label); IGNORE_RETVAL(ComboBox_SetItemData(hDeviceList, ComboBox_AddStringU(hDeviceList, entry), drive_index)); maxwidth = max(maxwidth, GetEntryWidth(hDeviceList, entry)); safe_closehandle(hDrive); safe_free(devint_detail_data); break; } } } SetupDiDestroyDeviceInfoList(dev_info); // Adjust the Dropdown width to the maximum text size SendMessage(hDeviceList, CB_SETDROPPEDWIDTH, (WPARAM)maxwidth, 0); if (devnum >= DRIVE_INDEX_MIN) { for (i=0; i<ComboBox_GetCount(hDeviceList); i++) { if ((DWORD)ComboBox_GetItemData(hDeviceList, i) == devnum) { found = TRUE; break; } } } if (!found) i = 0; IGNORE_RETVAL(ComboBox_SetCurSel(hDeviceList, i)); SendMessage(hMainDialog, WM_COMMAND, (CBN_SELCHANGE<<16) | IDC_DEVICE, 0); SendMessage(hMainDialog, WM_COMMAND, (CBN_SELCHANGE<<16) | IDC_FILESYSTEM, ComboBox_GetCurSel(hFileSystem)); r = TRUE; out: // Set 'Start' as the selected button, so that tab selection works SendMessage(hMainDialog, WM_NEXTDLGCTL, (WPARAM)GetDlgItem(hMainDialog, IDC_START), TRUE); safe_free(devid_list); StrArrayDestroy(&dev_if_path); htab_destroy(&htab_devid); return r; }
void __init cmdline_parse(const char *cmdline) { char opt[100], *optval, *optkey, *q; const char *p = cmdline; struct kernel_param *param; int bool_assert; if ( cmdline == NULL ) return; safe_strcpy(saved_cmdline, cmdline); for ( ; ; ) { /* Skip whitespace. */ while ( *p == ' ' ) p++; if ( *p == '\0' ) break; /* Grab the next whitespace-delimited option. */ q = optkey = opt; while ( (*p != ' ') && (*p != '\0') ) { if ( (q-opt) < (sizeof(opt)-1) ) /* avoid overflow */ *q++ = *p; p++; } *q = '\0'; /* Search for value part of a key=value option. */ optval = strchr(opt, '='); if ( optval != NULL ) { *optval++ = '\0'; /* nul-terminate the option value */ q = strpbrk(opt, "([{<"); } else { optval = q; /* default option value is empty string */ q = NULL; } /* Boolean parameters can be inverted with 'no-' prefix. */ bool_assert = !!strncmp("no-", optkey, 3); if ( !bool_assert ) optkey += 3; for ( param = &__setup_start; param < &__setup_end; param++ ) { if ( strcmp(param->name, optkey) ) { if ( param->type == OPT_CUSTOM && q && strlen(param->name) == q + 1 - opt && !strncmp(param->name, opt, q + 1 - opt) ) { optval[-1] = '='; ((void (*)(const char *))param->var)(q); optval[-1] = '\0'; } continue; } switch ( param->type ) { case OPT_STR: strlcpy(param->var, optval, param->len); break; case OPT_UINT: assign_integer_param( param, simple_strtoll(optval, NULL, 0)); break; case OPT_BOOL: case OPT_INVBOOL: if ( !parse_bool(optval) ) bool_assert = !bool_assert; assign_integer_param( param, (param->type == OPT_BOOL) == bool_assert); break; case OPT_SIZE: assign_integer_param( param, parse_size_and_unit(optval, NULL)); break; case OPT_CUSTOM: if ( !bool_assert ) { if ( *optval ) break; safe_strcpy(opt, "no"); optval = opt; } ((void (*)(const char *))param->var)(optval); break; default: BUG(); break; } } } }
static DATA_BLOB negprot_spnego(void) { DATA_BLOB blob; nstring dos_name; fstring unix_name; #ifdef DEVELOPER size_t slen; #endif char guid[17]; const char *OIDs_krb5[] = {OID_KERBEROS5, OID_KERBEROS5_OLD, OID_NTLMSSP, NULL}; const char *OIDs_plain[] = {OID_NTLMSSP, NULL}; global_spnego_negotiated = True; memset(guid, '\0', sizeof(guid)); safe_strcpy(unix_name, global_myname(), sizeof(unix_name)-1); strlower_m(unix_name); push_ascii_nstring(dos_name, unix_name); safe_strcpy(guid, dos_name, sizeof(guid)-1); #ifdef DEVELOPER /* Fix valgrind 'uninitialized bytes' issue. */ slen = strlen(dos_name); if (slen < sizeof(guid)) { memset(guid+slen, '\0', sizeof(guid) - slen); } #endif /* strangely enough, NT does not sent the single OID NTLMSSP when not a ADS member, it sends no OIDs at all OLD COMMENT : "we can't do this until we teach our sesssion setup parser to know about raw NTLMSSP (clients send no ASN.1 wrapping if we do this)" Our sessionsetup code now handles raw NTLMSSP connects, so we can go back to doing what W2K3 does here. This is needed to make PocketPC 2003 CIFS connections work with SPNEGO. See bugzilla bugs #1828 and #3133 for details. JRA. */ if (lp_security() != SEC_ADS && !lp_use_kerberos_keytab()) { #if 0 /* Code for PocketPC client */ blob = data_blob(guid, 16); #else /* Code for standalone WXP client */ blob = spnego_gen_negTokenInit(guid, OIDs_plain, "NONE"); #endif } else { fstring myname; char *host_princ_s = NULL; const char * lkdc_realm = lp_parm_talloc_string(GLOBAL_SECTION_SNUM, "com.apple", "lkdc realm", NULL); myname[0] = '\0'; get_mydnsfullname(myname); strlower_m(myname); /* If we have a LKDC, use it unless there is a managed realm * also configured. The managed realm should have precedence. */ if (lkdc_realm && (*lp_realm() == '\0' || strcmp(lkdc_realm, lp_realm()) == 0)) { asprintf(&host_princ_s, "cifs/%s@%s", lkdc_realm, lkdc_realm); } else { asprintf(&host_princ_s, "cifs/%s@%s", myname, lp_realm()); } blob = spnego_gen_negTokenInit(guid, OIDs_krb5, host_princ_s); SAFE_FREE(host_princ_s); TALLOC_FREE(lkdc_realm); } return blob; }
connection_struct *make_connection_snum(struct smbd_server_connection *sconn, int snum, user_struct *vuser, DATA_BLOB password, const char *pdev, NTSTATUS *pstatus) { connection_struct *conn; struct smb_filename *smb_fname_cpath = NULL; fstring dev; int ret; char addr[INET6_ADDRSTRLEN]; bool on_err_call_dis_hook = false; NTSTATUS status; fstrcpy(dev, pdev); if (NT_STATUS_IS_ERR(*pstatus = share_sanity_checks(snum, dev))) { return NULL; } conn = conn_new(sconn); if (!conn) { DEBUG(0,("Couldn't find free connection.\n")); *pstatus = NT_STATUS_INSUFFICIENT_RESOURCES; return NULL; } conn->params->service = snum; status = create_connection_server_info(sconn, conn, snum, vuser ? vuser->server_info : NULL, password, &conn->server_info); if (!NT_STATUS_IS_OK(status)) { DEBUG(1, ("create_connection_server_info failed: %s\n", nt_errstr(status))); *pstatus = status; conn_free(conn); return NULL; } if ((lp_guest_only(snum)) || (lp_security() == SEC_SHARE)) { conn->force_user = true; } add_session_user(sconn, conn->server_info->unix_name); safe_strcpy(conn->client_address, client_addr(get_client_fd(),addr,sizeof(addr)), sizeof(conn->client_address)-1); conn->num_files_open = 0; conn->lastused = conn->lastused_count = time(NULL); conn->used = True; conn->printer = (strncmp(dev,"LPT",3) == 0); conn->ipc = ( (strncmp(dev,"IPC",3) == 0) || ( lp_enable_asu_support() && strequal(dev,"ADMIN$")) ); /* Case options for the share. */ if (lp_casesensitive(snum) == Auto) { /* We will be setting this per packet. Set to be case * insensitive for now. */ conn->case_sensitive = False; } else { conn->case_sensitive = (bool)lp_casesensitive(snum); } conn->case_preserve = lp_preservecase(snum); conn->short_case_preserve = lp_shortpreservecase(snum); conn->encrypt_level = lp_smb_encrypt(snum); conn->veto_list = NULL; conn->hide_list = NULL; conn->veto_oplock_list = NULL; conn->aio_write_behind_list = NULL; conn->read_only = lp_readonly(SNUM(conn)); conn->admin_user = False; if (*lp_force_user(snum)) { /* * Replace conn->server_info with a completely faked up one * from the username we are forced into :-) */ char *fuser; struct auth_serversupplied_info *forced_serverinfo; fuser = talloc_string_sub(conn, lp_force_user(snum), "%S", lp_servicename(snum)); if (fuser == NULL) { conn_free(conn); *pstatus = NT_STATUS_NO_MEMORY; return NULL; } status = make_serverinfo_from_username( conn, fuser, conn->server_info->guest, &forced_serverinfo); if (!NT_STATUS_IS_OK(status)) { conn_free(conn); *pstatus = status; return NULL; } TALLOC_FREE(conn->server_info); conn->server_info = forced_serverinfo; conn->force_user = True; DEBUG(3,("Forced user %s\n", fuser)); } /* * If force group is true, then override * any groupid stored for the connecting user. */ if (*lp_force_group(snum)) { status = find_forced_group( conn->force_user, snum, conn->server_info->unix_name, &conn->server_info->ptok->user_sids[1], &conn->server_info->utok.gid); if (!NT_STATUS_IS_OK(status)) { conn_free(conn); *pstatus = status; return NULL; } /* * We need to cache this gid, to use within * change_to_user() separately from the conn->server_info * struct. We only use conn->server_info directly if * "force_user" was set. */ conn->force_group_gid = conn->server_info->utok.gid; } conn->vuid = (vuser != NULL) ? vuser->vuid : UID_FIELD_INVALID; { char *s = talloc_sub_advanced(talloc_tos(), lp_servicename(SNUM(conn)), conn->server_info->unix_name, conn->connectpath, conn->server_info->utok.gid, conn->server_info->sanitized_username, pdb_get_domain(conn->server_info->sam_account), lp_pathname(snum)); if (!s) { conn_free(conn); *pstatus = NT_STATUS_NO_MEMORY; return NULL; } if (!set_conn_connectpath(conn,s)) { TALLOC_FREE(s); conn_free(conn); *pstatus = NT_STATUS_NO_MEMORY; return NULL; } DEBUG(3,("Connect path is '%s' for service [%s]\n",s, lp_servicename(snum))); TALLOC_FREE(s); } /* * New code to check if there's a share security descripter * added from NT server manager. This is done after the * smb.conf checks are done as we need a uid and token. JRA. * */ { bool can_write = False; can_write = share_access_check(conn->server_info->ptok, lp_servicename(snum), FILE_WRITE_DATA); if (!can_write) { if (!share_access_check(conn->server_info->ptok, lp_servicename(snum), FILE_READ_DATA)) { /* No access, read or write. */ DEBUG(0,("make_connection: connection to %s " "denied due to security " "descriptor.\n", lp_servicename(snum))); conn_free(conn); *pstatus = NT_STATUS_ACCESS_DENIED; return NULL; } else { conn->read_only = True; } } } /* Initialise VFS function pointers */ if (!smbd_vfs_init(conn)) { DEBUG(0, ("vfs_init failed for service %s\n", lp_servicename(snum))); conn_free(conn); *pstatus = NT_STATUS_BAD_NETWORK_NAME; return NULL; } /* * If widelinks are disallowed we need to canonicalise the connect * path here to ensure we don't have any symlinks in the * connectpath. We will be checking all paths on this connection are * below this directory. We must do this after the VFS init as we * depend on the realpath() pointer in the vfs table. JRA. */ if (!lp_widelinks(snum)) { if (!canonicalize_connect_path(conn)) { DEBUG(0, ("canonicalize_connect_path failed " "for service %s, path %s\n", lp_servicename(snum), conn->connectpath)); conn_free(conn); *pstatus = NT_STATUS_BAD_NETWORK_NAME; return NULL; } } if ((!conn->printer) && (!conn->ipc)) { conn->notify_ctx = notify_init(conn, server_id_self(), smbd_messaging_context(), smbd_event_context(), conn); } /* ROOT Activities: */ /* * Enforce the max connections parameter. */ if ((lp_max_connections(snum) > 0) && (count_current_connections(lp_servicename(SNUM(conn)), True) >= lp_max_connections(snum))) { DEBUG(1, ("Max connections (%d) exceeded for %s\n", lp_max_connections(snum), lp_servicename(snum))); conn_free(conn); *pstatus = NT_STATUS_INSUFFICIENT_RESOURCES; return NULL; } /* * Get us an entry in the connections db */ if (!claim_connection(conn, lp_servicename(snum), 0)) { DEBUG(1, ("Could not store connections entry\n")); conn_free(conn); *pstatus = NT_STATUS_INTERNAL_DB_ERROR; return NULL; } /* Preexecs are done here as they might make the dir we are to ChDir * to below */ /* execute any "root preexec = " line */ if (*lp_rootpreexec(snum)) { char *cmd = talloc_sub_advanced(talloc_tos(), lp_servicename(SNUM(conn)), conn->server_info->unix_name, conn->connectpath, conn->server_info->utok.gid, conn->server_info->sanitized_username, pdb_get_domain(conn->server_info->sam_account), lp_rootpreexec(snum)); DEBUG(5,("cmd=%s\n",cmd)); ret = smbrun(cmd,NULL); TALLOC_FREE(cmd); if (ret != 0 && lp_rootpreexec_close(snum)) { DEBUG(1,("root preexec gave %d - failing " "connection\n", ret)); yield_connection(conn, lp_servicename(snum)); conn_free(conn); *pstatus = NT_STATUS_ACCESS_DENIED; return NULL; } } /* USER Activites: */ if (!change_to_user(conn, conn->vuid)) { /* No point continuing if they fail the basic checks */ DEBUG(0,("Can't become connected user!\n")); yield_connection(conn, lp_servicename(snum)); conn_free(conn); *pstatus = NT_STATUS_LOGON_FAILURE; return NULL; } /* Remember that a different vuid can connect later without these * checks... */ /* Preexecs are done here as they might make the dir we are to ChDir * to below */ /* execute any "preexec = " line */ if (*lp_preexec(snum)) { char *cmd = talloc_sub_advanced(talloc_tos(), lp_servicename(SNUM(conn)), conn->server_info->unix_name, conn->connectpath, conn->server_info->utok.gid, conn->server_info->sanitized_username, pdb_get_domain(conn->server_info->sam_account), lp_preexec(snum)); ret = smbrun(cmd,NULL); TALLOC_FREE(cmd); if (ret != 0 && lp_preexec_close(snum)) { DEBUG(1,("preexec gave %d - failing connection\n", ret)); *pstatus = NT_STATUS_ACCESS_DENIED; goto err_root_exit; } } #ifdef WITH_FAKE_KASERVER if (lp_afs_share(snum)) { afs_login(conn); } #endif /* Add veto/hide lists */ if (!IS_IPC(conn) && !IS_PRINT(conn)) { set_namearray( &conn->veto_list, lp_veto_files(snum)); set_namearray( &conn->hide_list, lp_hide_files(snum)); set_namearray( &conn->veto_oplock_list, lp_veto_oplocks(snum)); set_namearray( &conn->aio_write_behind_list, lp_aio_write_behind(snum)); } /* Invoke VFS make connection hook - do this before the VFS_STAT call to allow any filesystems needing user credentials to initialize themselves. */ if (SMB_VFS_CONNECT(conn, lp_servicename(snum), conn->server_info->unix_name) < 0) { DEBUG(0,("make_connection: VFS make connection failed!\n")); *pstatus = NT_STATUS_UNSUCCESSFUL; goto err_root_exit; } /* Any error exit after here needs to call the disconnect hook. */ on_err_call_dis_hook = true; status = create_synthetic_smb_fname(talloc_tos(), conn->connectpath, NULL, NULL, &smb_fname_cpath); if (!NT_STATUS_IS_OK(status)) { *pstatus = status; goto err_root_exit; } /* win2000 does not check the permissions on the directory during the tree connect, instead relying on permission check during individual operations. To match this behaviour I have disabled this chdir check (tridge) */ /* the alternative is just to check the directory exists */ if ((ret = SMB_VFS_STAT(conn, smb_fname_cpath)) != 0 || !S_ISDIR(smb_fname_cpath->st.st_ex_mode)) { if (ret == 0 && !S_ISDIR(smb_fname_cpath->st.st_ex_mode)) { DEBUG(0,("'%s' is not a directory, when connecting to " "[%s]\n", conn->connectpath, lp_servicename(snum))); } else { DEBUG(0,("'%s' does not exist or permission denied " "when connecting to [%s] Error was %s\n", conn->connectpath, lp_servicename(snum), strerror(errno) )); } *pstatus = NT_STATUS_BAD_NETWORK_NAME; goto err_root_exit; } string_set(&conn->origpath,conn->connectpath); #if SOFTLINK_OPTIMISATION /* resolve any soft links early if possible */ if (vfs_ChDir(conn,conn->connectpath) == 0) { TALLOC_CTX *ctx = talloc_tos(); char *s = vfs_GetWd(ctx,s); if (!s) { *status = map_nt_error_from_unix(errno); goto err_root_exit; } if (!set_conn_connectpath(conn,s)) { *status = NT_STATUS_NO_MEMORY; goto err_root_exit; } vfs_ChDir(conn,conn->connectpath); } #endif if (lp_unix_extensions() && lp_widelinks(snum)) { DEBUG(0,("Share '%s' has wide links and unix extensions enabled. " "These parameters are incompatible. " "Disabling wide links for this share.\n", lp_servicename(snum) )); lp_do_parameter(snum, "wide links", "False"); } /* Figure out the characteristics of the underlying filesystem. This * assumes that all the filesystem mounted withing a share path have * the same characteristics, which is likely but not guaranteed. */ conn->fs_capabilities = SMB_VFS_FS_CAPABILITIES(conn, &conn->ts_res); /* * Print out the 'connected as' stuff here as we need * to know the effective uid and gid we will be using * (at least initially). */ if( DEBUGLVL( IS_IPC(conn) ? 3 : 1 ) ) { dbgtext( "%s (%s) ", get_remote_machine_name(), conn->client_address ); dbgtext( "%s", srv_is_signing_active(smbd_server_conn) ? "signed " : ""); dbgtext( "connect to service %s ", lp_servicename(snum) ); dbgtext( "initially as user %s ", conn->server_info->unix_name ); dbgtext( "(uid=%d, gid=%d) ", (int)geteuid(), (int)getegid() ); dbgtext( "(pid %d)\n", (int)sys_getpid() ); } /* we've finished with the user stuff - go back to root */ change_to_root_user(); return(conn); err_root_exit: TALLOC_FREE(smb_fname_cpath); change_to_root_user(); if (on_err_call_dis_hook) { /* Call VFS disconnect hook */ SMB_VFS_DISCONNECT(conn); } yield_connection(conn, lp_servicename(snum)); conn_free(conn); return NULL; }
/* ************************************************************************** ** * MangledMap is a series of name pairs in () separated by spaces. * If s matches the first of the pair then the name given is the * second of the pair. A * means any number of any character and if * present in the second of the pair as well as the first the * matching part of the first string takes the place of the * in the * second. * * I wanted this so that we could have RCS files which can be used * by UNIX and DOS programs. My mapping string is (RCS rcs) which * converts the UNIX RCS file subdirectory to lowercase thus * preventing mangling. * * See 'mangled map' in smb.conf(5). * * ************************************************************************** ** */ static void mangled_map(char *s, const char *MangledMap) { const char *start=MangledMap; /* Use this to search for mappings. */ const char *end; /* Used to find the end of strings. */ char *match_string; pstring new_string; /* Make up the result here. */ char *np; /* Points into new_string. */ DEBUG( 5, ("Mangled Mapping '%s' map '%s'\n", s, MangledMap) ); while( *start ) { while( (*start) && (*start != '(') ) start++; if( !*start ) continue; /* Always check for the end. */ start++; /* Skip the ( */ end = start; /* Search for the ' ' or a ')' */ DEBUG( 5, ("Start of first in pair '%s'\n", start) ); while( (*end) && !((*end == ' ') || (*end == ')')) ) end++; if( !*end ) { start = end; continue; /* Always check for the end. */ } DEBUG( 5, ("End of first in pair '%s'\n", end) ); if( (match_string = map_filename( s, start, end-start )) ) { int size_left = sizeof(new_string) - 1; DEBUG( 5, ("Found a match\n") ); /* Found a match. */ start = end + 1; /* Point to start of what it is to become. */ DEBUG( 5, ("Start of second in pair '%s'\n", start) ); end = start; np = new_string; while( (*end && size_left > 0) /* Not the end of string. */ && (*end != ')') /* Not the end of the pattern. */ && (*end != '*') ) { /* Not a wildcard. */ *np++ = *end++; size_left--; } if( !*end ) { start = end; continue; /* Always check for the end. */ } if( *end == '*' ) { if (size_left > 0 ) safe_strcpy( np, match_string, size_left ); np += strlen( match_string ); size_left -= strlen( match_string ); end++; /* Skip the '*' */ while ((*end && size_left > 0) /* Not the end of string. */ && (*end != ')') /* Not the end of the pattern. */ && (*end != '*')) { /* Not a wildcard. */ *np++ = *end++; size_left--; } } if (!*end) { start = end; continue; /* Always check for the end. */ } if (size_left > 0) *np++ = '\0'; /* NULL terminate it. */ DEBUG(5,("End of second in pair '%s'\n", end)); new_string[sizeof(new_string)-1] = '\0'; pstrcpy( s, new_string ); /* Substitute with the new name. */ DEBUG( 5, ("s is now '%s'\n", s) ); } start = end; /* Skip a bit which cannot be wanted anymore. */ start++; } }
void chat_draw(rct_drawpixelinfo* dpi, uint8_t chatBackgroundColor) { if (!chat_available()) { gChatOpen = false; return; } _chatLeft = 10; _chatRight = std::min((context_get_width() - 10), CHAT_MAX_WINDOW_WIDTH); _chatWidth = _chatRight - _chatLeft; _chatBottom = context_get_height() - 45; _chatTop = _chatBottom - 10; char lineBuffer[CHAT_INPUT_SIZE + 10]; char* lineCh = lineBuffer; char* inputLine = _chatCurrentLine; int32_t inputLineHeight = 10; // Draw chat window if (gChatOpen) { inputLineHeight = chat_string_wrapped_get_height((void*)&inputLine, _chatWidth - 10); _chatTop -= inputLineHeight; for (int32_t i = 0; i < CHAT_HISTORY_SIZE; i++) { if (strlen(chat_history_get(i)) == 0) { continue; } safe_strcpy(lineBuffer, chat_history_get(i), sizeof(lineBuffer)); int32_t lineHeight = chat_string_wrapped_get_height((void*)&lineCh, _chatWidth - 10); _chatTop -= (lineHeight + 5); } _chatHeight = _chatBottom - _chatTop; if (_chatTop < 50) { _chatTop = 50; } else if (_chatHeight < 150) { // Min height _chatTop = _chatBottom - 150; _chatHeight = 150; } gfx_set_dirty_blocks(_chatLeft, _chatTop - 5, _chatRight, _chatBottom + 5); // Background area + Textbox gfx_filter_rect(dpi, _chatLeft, _chatTop - 5, _chatRight, _chatBottom + 5, PALETTE_51); // Opaque gray background gfx_fill_rect_inset( dpi, _chatLeft, _chatTop - 5, _chatRight, _chatBottom + 5, chatBackgroundColor, INSET_RECT_FLAG_FILL_NONE); gfx_fill_rect_inset( dpi, _chatLeft + 1, _chatTop - 4, _chatRight - 1, _chatBottom - inputLineHeight - 6, chatBackgroundColor, INSET_RECT_FLAG_BORDER_INSET); gfx_fill_rect_inset( dpi, _chatLeft + 1, _chatBottom - inputLineHeight - 5, _chatRight - 1, _chatBottom + 4, chatBackgroundColor, INSET_RECT_FLAG_BORDER_INSET); // Textbox } int32_t x = _chatLeft + 5; int32_t y = _chatBottom - inputLineHeight - 20; int32_t stringHeight = 0; // Draw chat history for (int32_t i = 0; i < CHAT_HISTORY_SIZE; i++, y -= stringHeight) { uint32_t expireTime = chat_history_get_time(i) + 10000; if (!gChatOpen && platform_get_ticks() > expireTime) { break; } safe_strcpy(lineBuffer, chat_history_get(i), sizeof(lineBuffer)); stringHeight = chat_history_draw_string(dpi, (void*)&lineCh, x, y, _chatWidth - 10) + 5; gfx_set_dirty_blocks(x, y - stringHeight, x + _chatWidth, y + 20); if ((y - stringHeight) < 50) { break; } } // Draw current chat input if (gChatOpen) { lineCh = utf8_write_codepoint(lineCh, FORMAT_OUTLINE); lineCh = utf8_write_codepoint(lineCh, FORMAT_CELADON); safe_strcpy(lineCh, _chatCurrentLine, sizeof(_chatCurrentLine)); y = _chatBottom - inputLineHeight - 5; lineCh = lineBuffer; inputLineHeight = gfx_draw_string_left_wrapped( dpi, (void*)&lineCh, x, y + 3, _chatWidth - 10, STR_STRING, TEXT_COLOUR_255); gfx_set_dirty_blocks(x, y, x + _chatWidth, y + inputLineHeight + 15); // TODO: Show caret if the input text has multiple lines if (_chatCaretTicks < 15 && gfx_get_string_width(lineBuffer) < (_chatWidth - 10)) { std::memcpy(lineBuffer, _chatCurrentLine, _chatTextInputSession->SelectionStart); lineBuffer[_chatTextInputSession->SelectionStart] = 0; int32_t caretX = x + gfx_get_string_width(lineBuffer); int32_t caretY = y + 14; gfx_fill_rect(dpi, caretX, caretY, caretX + 6, caretY + 1, PALETTE_INDEX_56); } } }
BOOL ExtractISO(const char* src_iso, const char* dest_dir, BOOL scan) { size_t i, k, size; int j; uint16_t sl_version; FILE* fd; int r = 1; iso9660_t* p_iso = NULL; udf_t* p_udf = NULL; udf_dirent_t* p_udf_root; LONG progress_style; char *tmp, *buf; char path[MAX_PATH]; const char* basedir[] = { "i386", "minint" }; const char* tmp_sif = ".\\txtsetup.sif~"; const char ISOLINUX[] = { 'I', 'S', 'O', 'L', 'I', 'N', 'U', 'X', ' ' }; iso_extension_mask_t iso_extension_mask = ISO_EXTENSION_ALL; if ((src_iso == NULL) || (dest_dir == NULL)) return FALSE; scan_only = scan; cdio_log_set_handler(log_handler); psz_extract_dir = dest_dir; progress_style = GetWindowLong(hISOProgressBar, GWL_STYLE); if (scan_only) { total_blocks = 0; memset(&iso_report, 0, sizeof(iso_report)); has_ldlinux_c32 = FALSE; // String array of all isolinux/syslinux locations StrArrayCreate(&config_path, 8); StrArrayCreate(&isolinux_path, 8); // Change the Window title and static text SetWindowTextU(hISOProgressDlg, lmprintf(MSG_202)); SetWindowTextU(hISOFileName, lmprintf(MSG_202)); // Change progress style to marquee for scanning SetWindowLong(hISOProgressBar, GWL_STYLE, progress_style | PBS_MARQUEE); SendMessage(hISOProgressBar, PBM_SETMARQUEE, TRUE, 0); } else { uprintf("Extracting files...\n"); IGNORE_RETVAL(_chdirU(app_dir)); SetWindowTextU(hISOProgressDlg, lmprintf(MSG_231)); if (total_blocks == 0) { uprintf("Error: ISO has not been properly scanned.\n"); FormatStatus = ERROR_SEVERITY_ERROR|FAC(FACILITY_STORAGE)|APPERR(ERROR_ISO_SCAN); goto out; } nb_blocks = 0; iso_blocking_status = 0; SetWindowLong(hISOProgressBar, GWL_STYLE, progress_style & (~PBS_MARQUEE)); SendMessage(hISOProgressBar, PBM_SETPOS, 0, 0); } SendMessage(hISOProgressDlg, UM_ISO_INIT, 0, 0); /* First try to open as UDF - fallback to ISO if it failed */ p_udf = udf_open(src_iso); if (p_udf == NULL) goto try_iso; uprintf("Disc image is an UDF image\n"); p_udf_root = udf_get_root(p_udf, true, 0); if (p_udf_root == NULL) { uprintf("Couldn't locate UDF root directory\n"); goto out; } if (scan_only) { if (udf_get_logical_volume_id(p_udf, iso_report.label, sizeof(iso_report.label)) <= 0) iso_report.label[0] = 0; } r = udf_extract_files(p_udf, p_udf_root, ""); goto out; try_iso: // Perform our first scan with Joliet disabled (if Rock Ridge is enabled), so that we can find if // there exists a Rock Ridge file with a name > 64 chars or if there are symlinks. If that is the // case then we also disable Joliet during the extract phase. if ((!enable_joliet) || (enable_rockridge && (scan_only || iso_report.has_long_filename || iso_report.has_symlinks))) { iso_extension_mask &= ~ISO_EXTENSION_JOLIET; } if (!enable_rockridge) { iso_extension_mask &= ~ISO_EXTENSION_ROCK_RIDGE; } p_iso = iso9660_open_ext(src_iso, iso_extension_mask); if (p_iso == NULL) { uprintf("Unable to open '%s' as an ISO image.\n", src_iso); r = 1; goto out; } uprintf("Disc image is an ISO9660 image\n"); i_joliet_level = iso9660_ifs_get_joliet_level(p_iso); if (scan_only) { if (iso9660_ifs_get_volume_id(p_iso, &tmp)) { safe_strcpy(iso_report.label, sizeof(iso_report.label), tmp); safe_free(tmp); } else iso_report.label[0] = 0; } else { if (iso_extension_mask & (ISO_EXTENSION_JOLIET|ISO_EXTENSION_ROCK_RIDGE)) uprintf("This image will be extracted using %s extensions (if present)", (iso_extension_mask & ISO_EXTENSION_JOLIET)?"Joliet":"Rock Ridge"); else uprintf("This image will not be extracted using any ISO extensions"); } r = iso_extract_files(p_iso, ""); out: iso_blocking_status = -1; if (scan_only) { // Remove trailing spaces from the label for (j=(int)safe_strlen(iso_report.label)-1; ((j>=0)&&(isspaceU(iso_report.label[j]))); j--) iso_report.label[j] = 0; // We use the fact that UDF_BLOCKSIZE and ISO_BLOCKSIZE are the same here iso_report.projected_size = total_blocks * ISO_BLOCKSIZE; // We will link the existing isolinux.cfg from a syslinux.cfg we create // If multiple config files exist, choose the one with the shortest path // (so that a '/syslinux.cfg' is preferred over a '/isolinux/isolinux.cfg') if (!IsStrArrayEmpty(config_path)) { safe_strcpy(iso_report.cfg_path, sizeof(iso_report.cfg_path), config_path.String[0]); for (i=1; i<config_path.Index; i++) { if (safe_strlen(iso_report.cfg_path) > safe_strlen(config_path.String[i])) safe_strcpy(iso_report.cfg_path, sizeof(iso_report.cfg_path), config_path.String[i]); } uprintf("Will use %s for Syslinux\n", iso_report.cfg_path); // Extract all of the isolinux.bin files we found to identify their versions for (i=0; i<isolinux_path.Index; i++) { size = (size_t)ExtractISOFile(src_iso, isolinux_path.String[i], dot_isolinux_bin); if (size == 0) { uprintf("Could not access %s\n", isolinux_path.String[i]); } else { buf = (char*)calloc(size, 1); if (buf == NULL) break; fd = fopen(dot_isolinux_bin, "rb"); if (fd == NULL) { free(buf); continue; } fread(buf, 1, size, fd); fclose(fd); for (k=0; k<size-16; k++) { if (memcmp(&buf[k], ISOLINUX, sizeof(ISOLINUX)) == 0) { k += sizeof(ISOLINUX); sl_version = (((uint8_t)strtoul(&buf[k], &tmp, 10))<<8) + (uint8_t)strtoul(&tmp[1], NULL, 10); if (iso_report.sl_version == 0) { iso_report.sl_version = sl_version; j = (int)i; } else if (iso_report.sl_version != sl_version) { uprintf("Found conflicting %s versions:\n '%s' (%d.%02d) vs '%s' (%d.%02d)\n", isolinux_bin, isolinux_path.String[j], SL_MAJOR(iso_report.sl_version), SL_MINOR(iso_report.sl_version), isolinux_path.String[i], SL_MAJOR(sl_version), SL_MINOR(sl_version)); } break; } } free(buf); _unlink(dot_isolinux_bin); } } if (iso_report.sl_version != 0) { static_sprintf(iso_report.sl_version_str, "%d.%02d", SL_MAJOR(iso_report.sl_version), SL_MINOR(iso_report.sl_version)); uprintf("Detected Isolinux version: %s (from '%s')", iso_report.sl_version_str, isolinux_path.String[j]); if ( (has_ldlinux_c32 && (SL_MAJOR(iso_report.sl_version) < 5)) || (!has_ldlinux_c32 && (SL_MAJOR(iso_report.sl_version) >= 5)) ) uprintf("Warning: Conflict between Isolinux version and the presence of ldlinux.c32...\n"); } else { // Couldn't find a version from isolinux.bin. Force set to the versions we embed iso_report.sl_version = embedded_sl_version[has_ldlinux_c32?1:0]; static_sprintf(iso_report.sl_version_str, "%d.%02d", SL_MAJOR(iso_report.sl_version), SL_MINOR(iso_report.sl_version)); uprintf("Warning: Could not detect Isolinux version - Forcing to %s (embedded)", iso_report.sl_version_str); } } if (IS_WINPE(iso_report.winpe)) { // In case we have a WinPE 1.x based iso, we extract and parse txtsetup.sif // during scan, to see if /minint was provided for OsLoadOptions, as it decides // whether we should use 0x80 or 0x81 as the disk ID in the MBR safe_sprintf(path, sizeof(path), "/%s/txtsetup.sif", basedir[((iso_report.winpe&WINPE_I386) == WINPE_I386)?0:1]); ExtractISOFile(src_iso, path, tmp_sif); tmp = get_token_data_file("OsLoadOptions", tmp_sif); if (tmp != NULL) { for (i=0; i<strlen(tmp); i++) tmp[i] = (char)tolower(tmp[i]); uprintf("Checking txtsetup.sif:\n OsLoadOptions = %s\n", tmp); iso_report.uses_minint = (strstr(tmp, "/minint") != NULL); } _unlink(tmp_sif); safe_free(tmp); } StrArrayDestroy(&config_path); StrArrayDestroy(&isolinux_path); } else if (HAS_SYSLINUX(iso_report)) { safe_sprintf(path, sizeof(path), "%s\\syslinux.cfg", dest_dir); // Create a /syslinux.cfg (if none exists) that points to the existing isolinux cfg fd = fopen(path, "r"); if (fd == NULL) { fd = fopen(path, "w"); // No "/syslinux.cfg" => create a new one if (fd == NULL) { uprintf("Unable to create %s - booting from USB will not work\n", path); r = 1; } else { fprintf(fd, "DEFAULT loadconfig\n\nLABEL loadconfig\n CONFIG %s\n", iso_report.cfg_path); for (i=safe_strlen(iso_report.cfg_path); (i>0)&&(iso_report.cfg_path[i]!='/'); i--); if (i>0) { iso_report.cfg_path[i] = 0; fprintf(fd, " APPEND %s/\n", iso_report.cfg_path); iso_report.cfg_path[i] = '/'; } uprintf("Created: %s\n", path); } } if (fd != NULL) fclose(fd); } SendMessage(hISOProgressDlg, UM_ISO_EXIT, 0, 0); if (p_iso != NULL) iso9660_close(p_iso); if (p_udf != NULL) udf_close(p_udf); if ((r != 0) && (FormatStatus == 0)) FormatStatus = ERROR_SEVERITY_ERROR|FAC(FACILITY_STORAGE)|APPERR((scan_only?ERROR_ISO_SCAN:ERROR_ISO_EXTRACT)); return (r == 0); }