예제 #1
0
void discover_package_replier(IoT_Package *package_info, IoT_Command *cmd)
{
	const int max_device_list_buf = 4096;
	int data_len = 0,n=0;
	char allDeviceList[max_device_list_buf] = { '\0' };
	char send_buf[max_device_list_buf] = { '\0' };

	if (strcmp(cmd->ID, "Dis_All") == 0)
	{
		puts("Discover all device\n");
		data_len = encodeAllDevices_except_one(allDeviceList, package_info->sor_ip.ip);
	}
	else if (strcmp(cmd->ID, "Dis_Pxd")==0)
	{
		puts("Discover Proxied device\n");
		data_len = encodePxdDevices_except_one(allDeviceList, package_info->sor_ip.ip,1);
	}
	else if (strcmp(cmd->ID, "Dis_NPx")==0)
	{
		puts("Discover Non-Proxied device\n");
		data_len = encodePxdDevices_except_one(allDeviceList, package_info->sor_ip.ip, 0);
	}

	//int data_len=encodeAllDevices(allDeviceList);
	IoT_Package new_package = generate_iot_package();
	create_package(&new_package, ServerIP, package_info->sor_ip.ip, allDeviceList, data_len);
	n = encode_package(send_buf, &new_package);

	send(client_socket[package_info->belongSocketIdx], send_buf, n, 0);
	printf("Device info Data:%d sended\n", n);
	free_package(&new_package);
}
int add_this_kernel(Options *op)
{
    Package *p;
    PrecompiledFileInfo *fileInfos;
    
    /* parse the manifest */

    if ((p = parse_manifest(op)) == NULL) goto failed;

    /* make sure we have the development tools */

    if (!check_development_tools(op, p)) goto failed;

    /* find the kernel header files */

    if (!determine_kernel_source_path(op, p)) goto failed;

    /* build the precompiled files */

    if (p->num_kernel_modules != build_kernel_interfaces(op, p, &fileInfos))
        goto failed;
    
    /* pack the precompiled files */

    if (!pack_precompiled_files(op, p, p->num_kernel_modules, fileInfos))
        goto failed;
    
    free_package(p);

    return TRUE;

 failed:

    ui_error(op, "Unable to add a precompiled kernel interface for the "
             "running kernel.");
    
    free_package(p);

    return FALSE;
    
} /* add_this_kernel() */
예제 #3
0
static void *
lex_chunks(void *vpp){
	const char *start,*end,*veryend;
	struct pkgparse *pp = vpp;
	pkgobj *head,**enq,*po;
	unsigned packages = 0;
	unsigned filter;
	size_t offset;

	head = NULL;
	enq = &head;
	filter = pp->dfa && *(pp->dfa) ? 1 : 0;
	offset = get_new_offset(pp);
	// We can go past the end of our chunk to finish a package's parsing
	// in media res, but we can't go past the end of the actual map!
	veryend = (const char *)pp->mem + pp->len;
	while(offset < pp->len){
		int newp;

		start = (const char *)pp->mem + offset;
		if(pp->csize + offset > pp->len){
			end = start + (pp->len - offset);
		}else{
			end = start + pp->csize;
		}
		newp = lex_chunk(offset,start,end,veryend,&enq,pp);
		if(newp < 0){
			goto err;
		}
		packages += newp;
		offset = get_new_offset(pp);
	}
	if(head){
		pthread_mutex_lock(&pp->lock); // Success!
			if(pp->dfa && !filter){
				for(po = head ; po ; po = po->next){
					augment_dfa(pp->dfa,po->name,po);
				}
			}
			pp->sharedpcache->pcount += packages;
			*enq = pp->sharedpcache->pobjs;
			pp->sharedpcache->pobjs = head;
		pthread_mutex_unlock(&pp->lock);
	}
	return vpp;

err:
	while( (po = head) ){
		head = po->next;
		free_package(po);
	}
	return NULL;
}
예제 #4
0
static void free_packages(packages_t *p)
{
	package_t *e, *f;
	if (!p) return;
	
	e = SEQUENCE_FIRST(p->package);
	while (e) {
		f = SEQUENCE_NEXT(e);
		free_package(e);
		e = f;
	}
	cds_free(p);
}
예제 #5
0
void handle_forwarding_package(IoT_Package *package_info)
{
	int n=0, idx=0,cmd_len=0;
	char sendBuffer[MAXPACKETSIZE];
	char cmdBuffer[MAXPACKETSIZE];
	printf("forwarding to:%s\n", package_info->des_ip.ip);
	//printAllChar(package_info->data, package_info->data_length);
	IoT_Device_Info *device_info = NULL;

	device_info = find_device_with_ip(package_info->des_ip);
	if (device_info == NULL)
	{
		puts("Cannot found target device ip");
		IoT_Command cmd = generate_iot_command();
		cmd.cmd_type = command_t_Management;
		strcpy(cmd.ID, "Del_Dev");
		strcpy(cmd.Value, package_info->des_ip.ip);
		memset(cmdBuffer,'\0', MAXPACKETSIZE);
		cmd_len =encode_iot_cmd(cmdBuffer, &cmd);

		IoT_Package send_package_info = generate_iot_package();
		create_package(&send_package_info, ServerIP, package_info->sor_ip.ip, cmdBuffer, cmd_len);
		n = encode_package(sendBuffer, &send_package_info);

		idx = package_info->belongSocketIdx;
		send(client_socket[idx], sendBuffer,n,0);
		free_package(&send_package_info);
	}
	else
	{
		n = encode_package(sendBuffer, package_info);
		//printf("Send to XBee agent:\n");
		//printAllChar(sendBuffer,n);
		idx = device_info->socket_index;
		send(client_socket[idx], sendBuffer, n, 0);

		//print_device_info(device_info);
	}
	//scan_all_device();
}
예제 #6
0
void handle_ip_request_package(IoT_Package *package_info)
{

	char suffix[3];
	char newIp[20];
	int offset = 0;
	sprintf(suffix, "%d", ip_count);
	int prefix_len = strlen(prefix);
	//int suffix_len = strlen(suffix);
	ip_count++;
	charcat(newIp, prefix, offset, prefix_len);
	offset += prefix_len;
	charcat(newIp, suffix, offset, prefix_len);

	char buffer[MAXRECV];
	IoT_Package new_package_info = generate_iot_package();
	create_package(&new_package_info, ServerIP, newIp, "0", 1);
	int packageLength = encode_package(buffer, &new_package_info);
	send(client_socket[package_info->belongSocketIdx], buffer, packageLength, 0);
	printf("Give ip:%s\n", new_package_info.des_ip.ip);
	free_package(&new_package_info);
}
예제 #7
0
unsigned int fill_package_struct(char *control_buffer)
{
	common_node_t *new_node = (common_node_t *) xcalloc(1, sizeof(common_node_t));

	char **field_name = xmalloc(sizeof(char *));
	char **field_value = xmalloc(sizeof(char *));
	int field_start = 0;
	int num = -1;
	int buffer_length = strlen(control_buffer);

	new_node->version = search_name_hashtable("unknown");
	while (field_start < buffer_length) {
		field_start += read_package_field(&control_buffer[field_start], field_name, field_value);

		if (*field_name == NULL) {
			goto fill_package_struct_cleanup; // Oh no, the dreaded goto statement !!
		}

		if (strcmp(*field_name, "Package") == 0) {
			new_node->name = search_name_hashtable(*field_value);
		}
		else if (strcmp(*field_name, "Version") == 0) {
			new_node->version = search_name_hashtable(*field_value);
		}
		else if (strcmp(*field_name, "Pre-Depends") == 0) {
			add_split_dependencies(new_node, *field_value, EDGE_PRE_DEPENDS);
		}
		else if (strcmp(*field_name, "Depends") == 0) {
			add_split_dependencies(new_node, *field_value, EDGE_DEPENDS);
		}
		else if (strcmp(*field_name, "Replaces") == 0) {
			add_split_dependencies(new_node, *field_value, EDGE_REPLACES);
		}
		else if (strcmp(*field_name, "Provides") == 0) {
			add_split_dependencies(new_node, *field_value, EDGE_PROVIDES);
		}
		else if (strcmp(*field_name, "Conflicts") == 0) {
			add_split_dependencies(new_node, *field_value, EDGE_CONFLICTS);
		}
		else if (strcmp(*field_name, "Suggests") == 0) {
			add_split_dependencies(new_node, *field_value, EDGE_SUGGESTS);
		}
		else if (strcmp(*field_name, "Recommends") == 0) {
			add_split_dependencies(new_node, *field_value, EDGE_RECOMMENDS);
		}
		else if (strcmp(*field_name, "Enhances") == 0) {
			add_split_dependencies(new_node, *field_value, EDGE_ENHANCES);
		}
fill_package_struct_cleanup:
		if (*field_name) {
			free(*field_name);
		}
		if (*field_value) {
			free(*field_value);
		}
	}
	free(field_name);
	free(field_value);

	if (new_node->version == search_name_hashtable("unknown")) {
		free_package(new_node);
		return(-1);
	}
	num = search_package_hashtable(new_node->name, new_node->version, VER_EQUAL);
	if (package_hashtable[num] == NULL) {
		package_hashtable[num] = new_node;
	} else {
		free_package(new_node);
	}
	return(num);
}
예제 #8
0
extern int dpkg_main(int argc, char **argv)
{
	deb_file_t **deb_file = NULL;
	status_node_t *status_node;
	int opt = 0;
	int package_num;
	int dpkg_opt = 0;
	int deb_count = 0;
	int state_status;
	int status_num;
	int i;

	while ((opt = getopt(argc, argv, "CF:ilPru")) != -1) {
		switch (opt) {
			case 'C': // equivalent to --configure in official dpkg
				dpkg_opt |= dpkg_opt_configure;
				dpkg_opt |= dpkg_opt_package_name;
				break;
			case 'F': // equivalent to --force in official dpkg
				if (strcmp(optarg, "depends") == 0) {
					dpkg_opt |= dpkg_opt_force_ignore_depends;
				}				
			case 'i':
				dpkg_opt |= dpkg_opt_install;
				dpkg_opt |= dpkg_opt_filename;
				break;
			case 'l':
				dpkg_opt |= dpkg_opt_list_installed;
			case 'P':
				dpkg_opt |= dpkg_opt_purge;
				dpkg_opt |= dpkg_opt_package_name;
				break;
			case 'r':
				dpkg_opt |= dpkg_opt_remove;
				dpkg_opt |= dpkg_opt_package_name;
				break;
			case 'u':	/* Equivalent to --unpack in official dpkg */
				dpkg_opt |= dpkg_opt_unpack;
				dpkg_opt |= dpkg_opt_filename;
				break;
			default:
				show_usage();
		}
	}

	if ((argc == optind) || (dpkg_opt == 0)) {
		show_usage();
	} 

	puts("(Reading database ... xxxxx files and directories installed.)");
	index_status_file("/var/lib/dpkg/status");

	/* Read arguments and store relevant info in structs */
	deb_file = xmalloc(sizeof(deb_file_t));
	while (optind < argc) {
		deb_file[deb_count] = (deb_file_t *) xmalloc(sizeof(deb_file_t));
		if (dpkg_opt & dpkg_opt_filename) {
			deb_file[deb_count]->filename = xstrdup(argv[optind]);
			deb_file[deb_count]->control_file = deb_extract(argv[optind], stdout, (extract_control_tar_gz | extract_one_to_buffer), NULL, "./control");
			if (deb_file[deb_count]->control_file == NULL) {
				error_msg_and_die("Couldnt extract control file");
			}
			package_num = fill_package_struct(deb_file[deb_count]->control_file);

			if (package_num == -1) {
				error_msg("Invalid control file in %s", argv[optind]);
				continue;
			}
			deb_file[deb_count]->package = (unsigned int) package_num;
			/* Add the package to the status hashtable */
			if ((dpkg_opt & dpkg_opt_unpack) || (dpkg_opt & dpkg_opt_install)) {
				status_node = (status_node_t *) xmalloc(sizeof(status_node_t));
				status_node->package = deb_file[deb_count]->package;
				/* use reinstreq isnt changed to "ok" until the package control info
				 * is written to the status file*/
				status_node->status = search_name_hashtable("install reinstreq not-installed");

				status_num = search_status_hashtable(name_hashtable[package_hashtable[deb_file[deb_count]->package]->name]);
				status_hashtable[status_num] = status_node;
			}
		}
		else if (dpkg_opt & dpkg_opt_package_name) {
			deb_file[deb_count]->filename = NULL;
			deb_file[deb_count]->control_file = NULL;
			deb_file[deb_count]->package = search_package_hashtable(
				search_name_hashtable(argv[optind]),
				search_name_hashtable("ANY"), VER_ANY);
			if (package_hashtable[deb_file[deb_count]->package] == NULL) {
				error_msg_and_die("Package %s is uninstalled or unknown\n", argv[optind]);
			}
			state_status = get_status(search_status_hashtable(name_hashtable[package_hashtable[deb_file[deb_count]->package]->name]), 3);

			/* check package status is "installed" */
			if (dpkg_opt & dpkg_opt_remove) {
				if ((strcmp(name_hashtable[state_status], "not-installed") == 0) ||
					(strcmp(name_hashtable[state_status], "config-files") == 0)) {
					error_msg_and_die("%s is already removed.", name_hashtable[package_hashtable[deb_file[deb_count]->package]->name]);
				}
			}
			else if (dpkg_opt & dpkg_opt_purge) {
				/* if package status is "conf-files" then its ok */
				if (strcmp(name_hashtable[state_status], "not-installed") == 0) {
					error_msg_and_die("%s is already purged.", name_hashtable[package_hashtable[deb_file[deb_count]->package]->name]);
				}
			}
		}
		deb_count++;
		optind++;
	}
	deb_file[deb_count] = NULL;

	/* Check that the deb file arguments are installable */
	/* TODO: check dependencies before removing */
	if ((dpkg_opt & dpkg_opt_force_ignore_depends) != dpkg_opt_force_ignore_depends) {
		if (!check_deps(deb_file, 0, deb_count)) {
			error_msg_and_die("Dependency check failed");
		}
	}

	for (i = 0; i < deb_count; i++) {
		/* Remove or purge packages */
		if (dpkg_opt & dpkg_opt_remove) {
			remove_package(deb_file[i]->package);
		}
		else if (dpkg_opt & dpkg_opt_purge) {
			purge_package(deb_file[i]->package);
		}
		else if (dpkg_opt & dpkg_opt_unpack) {
			unpack_package(deb_file[i]);
		}
		else if (dpkg_opt & dpkg_opt_install) {
			unpack_package(deb_file[i]);
			configure_package(deb_file[i]);
		}
		else if (dpkg_opt & dpkg_opt_configure) {
			configure_package(deb_file[i]);
		}
	}

	write_status_file(deb_file);

	for (i = 0; i < deb_count; i++) {
		free(deb_file[i]->control_file);
		free(deb_file[i]->filename);
		free(deb_file[i]);
	}
	free(deb_file);

	for (i = 0; i < NAME_HASH_PRIME; i++) {
		if (name_hashtable[i] != NULL) {
			free(name_hashtable[i]);
		}
	}

	for (i = 0; i < PACKAGE_HASH_PRIME; i++) {
		free_package(package_hashtable[i]);
	}

	for (i = 0; i < STATUS_HASH_PRIME; i++) {
		if (status_hashtable[i] != NULL) {
			free(status_hashtable[i]);
		}
	}

	return(EXIT_FAILURE);
}
int install_from_cwd(Options *op)
{
    Package *p;
    CommandList *c;
    int ret;
    int ran_pre_install_hook = FALSE;
    HookScriptStatus res;

    static const char* edit_your_xf86config =
        "Please update your XF86Config or xorg.conf file as "
        "appropriate; see the file /usr/share/doc/"
        "NVIDIA_GLX-1.0/README.txt for details.";

    /*
     * validate the manifest file in the cwd, and process it, building
     * a Package struct
     */
    
    if ((p = parse_manifest(op)) == NULL) goto failed;

    if (!op->x_files_packaged) {
        edit_your_xf86config = "";
    }

    ui_set_title(op, "%s (%s)", p->description, p->version);
    
    /* 
     * warn the user if "legacy" GPUs are installed in this system
     * and if no supported GPU is found, at all.
     */

    check_for_nvidia_graphics_devices(op, p);

    /* check that we are not running any X server */

    if (!check_for_running_x(op)) goto failed;

    /* make sure the kernel module is unloaded */
    
    if (!check_for_unloaded_kernel_module(op)) goto failed;
    
    /* ask the user to accept the license */
    
    if (!get_license_acceptance(op)) goto exit_install;
    
    ui_log(op, "Installing NVIDIA driver version %s.", p->version);

    /*
     * determine the current NVIDIA version (if any); ask the user if
     * they really want to overwrite the existing installation
     */

    if (!check_for_existing_driver(op, p)) goto exit_install;

    /*
     * check to see if an alternate method of installation is already installed
     * or is available, but not installed; ask the user if they really want to
     * install anyway despite the presence/availability of an alternate install.
     */

    if (!check_for_alternate_install(op)) goto exit_install;

    /* run the distro preinstall hook */

    res = run_distro_hook(op, "pre-install");
    if (res == HOOK_SCRIPT_FAIL) {
        if (ui_multiple_choice(op, CONTINUE_ABORT_CHOICES,
                               NUM_CONTINUE_ABORT_CHOICES,
                               CONTINUE_CHOICE, /* Default choice */
                               "The distribution-provided pre-install "
                               "script failed!  Are you sure you want "
                               "to continue?") == ABORT_CHOICE) {
            goto failed;
        }
    } else if (res == HOOK_SCRIPT_SUCCESS) {
        if (ui_multiple_choice(op, CONTINUE_ABORT_CHOICES,
                               NUM_CONTINUE_ABORT_CHOICES,
                               CONTINUE_CHOICE, /* Default choice */
                               "The distribution-provided pre-install script "
                               "completed successfully. If this is the first "
                               "time you have run the installer, this script "
                               "may have helped disable Nouveau, but a reboot "
                               "may be required first.  "
                               "Would you like to continue, or would you "
                               "prefer to abort installation to reboot the "
                               "system?") == ABORT_CHOICE) {
            goto exit_install;
        }
        ran_pre_install_hook = TRUE;
    }

    /* fail if the nouveau driver is currently in use */

    if (!check_for_nouveau(op)) goto failed;

    /* ask if we should install the UVM kernel module */

    should_install_uvm(op, p);

    /* attempt to build the kernel modules for the target kernel */

    if (!op->no_kernel_module) {
        if (!install_kernel_modules(op, p)) {
            goto failed;
        }
    } else {
        ui_warn(op, "You specified the '--no-kernel-module' command line "
                "option, nvidia-installer will not install a kernel "
                "module as part of this driver installation, and it will "
                "not remove existing NVIDIA kernel modules not part of "
                "an earlier NVIDIA driver installation.  Please ensure "
                "that an NVIDIA kernel module matching this driver version "
                "is installed seperately.");

        /* no_kernel_module should imply no DKMS */

        if (op->dkms) {
            ui_warn(op, "You have specified both the '--no-kernel-module' "
                    "and the '--dkms' command line options. The '--dkms' "
                    "option will be ignored.");
            op->dkms = FALSE;
        }
    }
    
    /*
     * if we are only installing the kernel module, then remove
     * everything else from the package; otherwise do some
     * OpenGL-specific stuff
     */

    if (op->kernel_module_only) {
        remove_non_kernel_module_files_from_package(op, p);
    } else {

        /* ask for the XFree86 and OpenGL installation prefixes. */
    
        if (!get_prefixes(op)) goto failed;

        /* ask if we should install the OpenGL header files */

        should_install_opengl_headers(op, p);

        /*
         * select the appropriate TLS class, modifying the package as
         * necessary.
         */
    
        select_tls_class(op, p);

        /*
         * if the package contains any libGL.la or .desktop files,
         * process them (perform some search and replacing so
         * that they reflect the correct installation path, etc)
         * and add them to the package list (files to be installed).
         */
        
        process_libGL_la_files(op, p);
        process_dot_desktop_files(op, p);

#if defined(NV_X86_64)
        /*
         * ask if we should install the 32bit compatibility files on
         * this machine.
         */

        should_install_compat32_files(op, p);
#endif /* NV_X86_64 */
    }

    if (op->no_opengl_files) {
        remove_opengl_files_from_package(op, p);
    }

    /*
     * now that we have the installation prefixes, build the
     * destination for each file to be installed
     */
    
    if (!set_destinations(op, p)) goto failed;

    /*
     * if we are installing OpenGL libraries, ensure that a symlink gets
     * installed to /usr/lib/libGL.so.1. add_libgl_abi_symlink() sets its own
     * destination, so it must be called after set_destinations().
     */
    if (!op->kernel_module_only && !op->no_opengl_files) {
        add_libgl_abi_symlink(op, p);
    }
    
    /*
     * uninstall the existing driver; this needs to be done before
     * building the command list.
     *
     * XXX if we uninstall now, then build the command list, and
     * then ask the user if they really want to execute the
     * command list, if the user decides not to execute the
     * command list, they'll be left with no driver installed.
     */

    if (!op->kernel_module_only) {
        if (!run_existing_uninstaller(op)) goto failed;
    }

    if (!check_libglvnd_files(op, p)) {
        goto failed;
    }

    /* build a list of operations to execute to do the install */
    
    if ((c = build_command_list(op, p)) == NULL) goto failed;

    /* call the ui to get approval for the list of commands */
    
    if (!ui_approve_command_list(op, c, "%s", p->description)) {
        goto exit_install;
    }
    
    /* initialize the backup log file */

    if (!op->kernel_module_only) {
        if (!init_backup(op, p)) goto failed;
    }

    /* execute the command list */

    if (!do_install(op, p, c)) goto failed;

    /* Register, build, and install the module with DKMS, if requested */

    if (op->dkms && !dkms_install_module(op, p->version, get_kernel_name(op)))
        goto failed;

    /*
     * Leave the RM loaded in case an X server with OutputClass-based driver
     * matching is being used.
     */

    if (!op->no_kernel_module || op->dkms) {
        if (!load_kernel_module(op, p->kernel_modules[0].module_name)) {
            goto failed;
        }
    }

    /* run the distro postinstall script */

    run_distro_hook(op, "post-install");

    /*
     * check that everything is installed properly (post-install
     * sanity check)
     */

    check_installed_files_from_package(op, p);

    if (!check_runtime_configuration(op, p)) goto failed;
    
    /* done */

    if (op->kernel_module_only || op->no_nvidia_xconfig_question) {

        ui_message(op, "Installation of the kernel module for the %s "
                   "(version %s) is now complete.",
                   p->description, p->version);
    } else {
        
        /* ask the user if they would like to run nvidia-xconfig */
        
        const char *msg = "Would you like to run the nvidia-xconfig utility "
                          "to automatically update your X configuration file "
                          "so that the NVIDIA X driver will be used when you "
                          "restart X?  Any pre-existing X configuration "
                          "file will be backed up.";
        
        ret = run_nvidia_xconfig(op, FALSE, msg, op->run_nvidia_xconfig);
        
        if (ret) {
            ui_message(op, "Your X configuration file has been successfully "
                       "updated.  Installation of the %s (version: %s) is now "
                       "complete.", p->description, p->version);
        } else {
            ui_message(op, "Installation of the %s (version: %s) is now "
                       "complete.  %s", p->description,
                       p->version, edit_your_xf86config);
        }
    }
    
    free_package(p);

    return TRUE;
    
 failed:

    /*
     * something bad happened during installation; print an error
     * message and return FALSE
     */
    
    if (op->logging) {
        ui_error(op, "Installation has failed.  Please see the file '%s' "
                 "for details.  You may find suggestions on fixing "
                 "installation problems in the README available on the "
                 "Linux driver download page at www.nvidia.com.",
                 op->log_file_name);
    } else {
        ui_error(op, "Installation has failed.  You may find suggestions "
                 "on fixing installation problems in the README available "
                 "on the Linux driver download page at www.nvidia.com.");
    }

    if (ran_pre_install_hook)
        run_distro_hook(op, "failed-install");

    /* fall through into exit_install... */

 exit_install:

    /*
     * we are exiting installation; this can happen for reasons that
     * do not merit the error message (e.g., the user declined the
     * license agreement)
     */
    
    free_package(p);
    
    return FALSE;

} /* install_from_cwd() */
예제 #10
0
static Package *parse_manifest (Options *op)
{
    char *buf, *c, *tmpstr;
    int line;
    int fd, ret, len = 0;
    struct stat stat_buf;
    Package *p;
    char *manifest = MAP_FAILED, *ptr;
    int opengl_files_packaged = FALSE;

    p = (Package *) nvalloc(sizeof (Package));

    /* open the manifest file */

    if ((fd = open(".manifest", O_RDONLY)) == -1) {
        ui_error(op, "No package found for installation.  Please run "
                 "this utility with the '--help' option for usage "
                 "information.");
        goto fail;
    }
    
    if (fstat(fd, &stat_buf) == -1) goto cannot_open;
    
    len = stat_buf.st_size;

    manifest = mmap(0, len, PROT_READ, MAP_FILE|MAP_SHARED, fd, 0);
    if (manifest == MAP_FAILED) goto cannot_open;
    
    /* the first line is the description */

    line = 1;
    p->description = get_next_line(manifest, &ptr, manifest, len);
    if (!p->description) goto invalid_manifest_file;
    
    /* the second line is the version */
    
    line++;
    p->version = get_next_line(ptr, &ptr, manifest, len);
    if (!p->version) goto invalid_manifest_file;
    
    /* Ignore the third line */

    line++;
    nvfree(get_next_line(ptr, &ptr, manifest, len));

    /* the fourth line is the list of kernel modules. */

    line++;
    tmpstr = get_next_line(ptr, &ptr, manifest, len);
    if (parse_kernel_modules_list(p, tmpstr) == 0) {
        goto invalid_manifest_file;
    }
    nvfree(tmpstr);

    /*
     * set the default value of excluded_kernel_modules to an empty, heap
     * allocated string so that it can be freed and won't prematurely end
     * an nvstrcat()ed string when unset.
     */

    p->excluded_kernel_modules = nvstrdup("");

    /*
     * ignore the fifth and sixth lines
     */

    line++;
    nvfree(get_next_line(ptr, &ptr, manifest, len));
    line++;
    nvfree(get_next_line(ptr, &ptr, manifest, len));

    /* the seventh line is the kernel module build directory */

    line++;
    p->kernel_module_build_directory = get_next_line(ptr, &ptr, manifest, len);
    if (!p->kernel_module_build_directory) goto invalid_manifest_file;
    remove_trailing_slashes(p->kernel_module_build_directory);

    /*
     * the eigth line is the directory containing precompiled kernel
     * interfaces
     */

    line++;
    p->precompiled_kernel_interface_directory =
        get_next_line(ptr, &ptr, manifest, len);
    if (!p->precompiled_kernel_interface_directory)
        goto invalid_manifest_file;
    remove_trailing_slashes(p->precompiled_kernel_interface_directory);

    /* the rest of the file is file entries */

    line++;
    
    for (; (buf = get_next_line(ptr, &ptr, manifest, len)); line++) {
        char *flag = NULL;
        PackageEntry entry;
        int entry_success = FALSE;

        if (buf[0] == '\0') {
            free(buf);
            break;
        }

        /* initialize the new entry */

        memset(&entry, 0, sizeof(PackageEntry));

        /* read the file name and permissions */

        c = buf;

        entry.file = read_next_word(buf, &c);

        if (!entry.file) goto entry_done;

        tmpstr = read_next_word(c, &c);

        if (!tmpstr) goto entry_done;

        /* translate the mode string into an octal mode */

        ret = mode_string_to_mode(op, tmpstr, &entry.mode);

        free(tmpstr);

        if (!ret) goto entry_done;

        /* every file has a type field */

        entry.type = FILE_TYPE_NONE;

        flag = read_next_word(c, &c);
        if (!flag) goto entry_done;

        entry.type = parse_manifest_file_type(flag, &entry.caps);

        if (entry.type == FILE_TYPE_NONE) {
            goto entry_done;
        }

        /* Track whether certain file types were packaged */

        switch (entry.type) {
            case FILE_TYPE_XMODULE_SHARED_LIB:
                op->x_files_packaged = TRUE;
                break;
            default: break;
        }

        /* set opengl_files_packaged if any OpenGL files were packaged */

        if (entry.caps.is_opengl) {
            opengl_files_packaged = TRUE;
        }

        /* some libs/symlinks have an arch field */

        entry.compat_arch = FILE_COMPAT_ARCH_NONE;

        if (entry.caps.has_arch) {
            nvfree(flag);
            flag = read_next_word(c, &c);
            if (!flag) goto entry_done;

            if (strcmp(flag, "COMPAT32") == 0)
                entry.compat_arch = FILE_COMPAT_ARCH_COMPAT32;
            else if (strcmp(flag, "NATIVE") == 0)
                entry.compat_arch = FILE_COMPAT_ARCH_NATIVE;
            else {
                goto entry_done;
            }
        }

        /* if compat32 files are packaged, set compat32_files_packaged */

        if (entry.compat_arch == FILE_COMPAT_ARCH_COMPAT32) {
            op->compat32_files_packaged = TRUE;
        }

        /* some libs/symlinks have a class field */

        entry.tls_class = FILE_TLS_CLASS_NONE;

        if (entry.caps.has_tls_class) {
            nvfree(flag);
            flag = read_next_word(c, &c);
            if (!flag) goto entry_done;

            if (strcmp(flag, "CLASSIC") == 0)
                entry.tls_class = FILE_TLS_CLASS_CLASSIC;
            else if (strcmp(flag, "NEW") == 0)
                entry.tls_class = FILE_TLS_CLASS_NEW;
            else {
                goto entry_done;
            }
        }

        /* some file types have a path field, or inherit their paths */

        if (entry.caps.has_path) {
            entry.path = read_next_word(c, &c);
            if (!entry.path) goto invalid_manifest_file;
        } else if (entry.caps.inherit_path) {
            int i;
            char *path, *depth, *slash;
            const char * const depth_marker = "INHERIT_PATH_DEPTH:";

            depth = read_next_word(c, &c);
            if (!depth ||
                strncmp(depth, depth_marker, strlen(depth_marker)) != 0) {
                goto invalid_manifest_file;
            }
            entry.inherit_path_depth = atoi(depth + strlen(depth_marker));
            nvfree(depth);

            /* Remove the file component from the packaged filename */
            path = entry.path = nvstrdup(entry.file);
            slash = strrchr(path, '/');
            if (slash == NULL) {
                goto invalid_manifest_file;
            }
            slash[1] = '\0';

            /* Strip leading directory components from the path */
            for (i = 0; i < entry.inherit_path_depth; i++) {
                slash = strchr(entry.path, '/');

                if (slash == NULL) {
                    goto invalid_manifest_file;
                }

                entry.path = slash + 1;
            }

            entry.path = nvstrdup(entry.path);
            nvfree(path);
        } else {
            entry.path = NULL;
        }

        /* symlinks have a target */

        if (entry.caps.is_symlink) {
            entry.target = read_next_word(c, &c);
            if (!entry.target) goto invalid_manifest_file;
        } else {
            entry.target = NULL;
        }

        /*
         * as a convenience for later, set the 'name' pointer to
         * the basename contained in 'file' (ie the portion of
         * 'file' without any leading directory components
         */

        entry.name = strrchr(entry.file, '/');
        if (entry.name) entry.name++;

        if (!entry.name) entry.name = entry.file;

        add_package_entry(p,
                          entry.file,
                          entry.path,
                          entry.name,
                          entry.target,
                          entry.dst,
                          entry.type,
                          entry.tls_class,
                          entry.compat_arch,
                          entry.mode);

        entry_success = TRUE;

 entry_done:
        /* clean up */

        nvfree(buf);
        nvfree(flag);
        if (!entry_success) {
            goto invalid_manifest_file;
        }
    }

    /* If no OpenGL files were packaged, we can't install them. Set the
     * no_opengl_files flag so that everything we skip when explicitly
     * excluding OpenGL is also skipped when OpenGL is not packaged. */

    if (!opengl_files_packaged) {
        op->no_opengl_files = TRUE;
    }

    munmap(manifest, len);
    if (fd != -1) close(fd);

    return p;
    
 cannot_open:
    ui_error(op, "Failure opening package's .manifest file (%s).",
             strerror(errno));
    goto fail;

 invalid_manifest_file:

    ui_error(op, "Invalid .manifest file; error on line %d.", line);
    goto fail;

 fail:
    free_package(p);
    if (manifest != MAP_FAILED) munmap(manifest, len);
    if (fd != -1) close(fd);
    return NULL;
       
} /* parse_manifest() */
예제 #11
0
int main_server_loop(Server_Object *server_obj)
{
	IoTSocket new_socket;
	struct sockaddr_in  address;
	int activity, i,  valread,fdmax=65535;
	//first received buffer
	char buffer[MAXRECV];

	TimeSpan timeout;
	timeout.tv_sec = 100;
	timeout.tv_usec = 0;
	//set of socket descriptors
	fd_set master, readfds;

	//Bind
	if (bind(server_obj->listener, (struct sockaddr *)&server_obj->address, sizeof(server_obj->address)) == -1)
	{
		printf("Main server Bind failed\n");
		PAUSE;
		exit(EXIT_FAILURE);
	}

	puts("Main server  Bind done");

	//Listen to incoming connections
	listen(server_obj->listener, MAXCLIENTS);

	//Accept and incoming connection
	puts("Main server Waiting for incoming connections...");


	#if defined(WIN32)
        int addrlen = sizeof(struct sockaddr_in);
	#elif defined(__linux__) || defined(__FreeBSD__)
        socklen_t addrlen = sizeof(struct sockaddr_in);
    #endif

	//clear the socket fd set
	FD_ZERO(&master);
	FD_ZERO(&readfds);

	//add listener socket to fd set

	FD_SET(server_obj->listener, &master);

	//fdmax = server_obj->listener + 1;

	while (1)
	{
		readfds = master;
		activity = select(MAXCLIENTS, &readfds, NULL, NULL, &timeout);

		if (activity == -1)
		{
			printf("Main server select call failed");
			PAUSE;
			exit(EXIT_FAILURE);
		}

		//Add new connection into set
		if (FD_ISSET(server_obj->listener, &readfds))
		{
			if ((new_socket = accept(server_obj->listener, (struct sockaddr *)&address, &addrlen))<0)
			{
				perror("accept");
				PAUSE;
				exit(EXIT_FAILURE);
			}

			//inform user of socket number - used in send and receive commands
			printf("Main server has new connection , socket fd is %d , ip is : %s , port : %d \n", new_socket, inet_ntoa(address.sin_addr), ntohs(address.sin_port));

			//add new socket to array of sockets
			for (i = 0; i < MAXCLIENTS; i++)
			{
				if (client_socket[i] == 0)
				{
					client_socket[i] = new_socket;
					FD_SET(new_socket, &master);
					printf("Main server adding a new item to list of sockets at index %d \n", i);
					packageBuffer[i] = generate_package_buffer();
					break;
				}
			}
		}

		//handle connected conndetion,find which connection active
		for (i = 0; i < MAXCLIENTS; i++)
		{
			/*
			if (FD_ISSET(client_socket[i], &readfds))
			{
				valread = recv(client_socket[i], buffer, MAXRECV, 0);

				if (valread <= 0)
				{
					//Somebody disconnected , get his details and print
					printf("Host disconnected , ip %s , port %d \n", inet_ntoa(address.sin_addr), ntohs(address.sin_port));
					//Close the socket and mark as 0 in list for reuse
					FD_CLR(client_socket[i], &master);
					CloseIoTSocket(client_socket[i]);
					client_socket[i] = 0;
					free_package_buffer(packageBuffer[i]);
					packageBuffer[i] = NULL;
				}
				//Echo back the message that came in
				else if (valread>0)
				{
					//add null character, if you want to use with printf/puts or other string handling functions
					//buffer[valread] = '\0';
					printf("FD_Index:%d\n", i);
					printf("%s:%d-", inet_ntoa(address.sin_addr), ntohs(address.sin_port));
					printAllChar(buffer, valread);
					char buf[10];
					strcpy(buf, "Hello");
					//ms_sleep(4000);
					while (1)
					{
						send(client_socket[i], buf, 5, 0);
						ms_sleep(1000);
						printf("Sended\n");
					}


				}
			}
			*/

			if (FD_ISSET(client_socket[i], &readfds))
			{
				//get details of the client
				getpeername(client_socket[i], (struct sockaddr*)&address, &addrlen);

				//Check if it was for closing , and also read the incoming message
				//recv does not place a null terminator at the end of the string (whilst printf %s assumes there is one).
				memset(buffer, '\0', MAXRECV);
				valread = recv(client_socket[i], buffer, MAXRECV, 0);

				if (valread <= 0)
				{
					//Somebody disconnected , get his details and print
					printf("Main server got host disconnected , ip %s , port %d \n", inet_ntoa(address.sin_addr), ntohs(address.sin_port));
					//Close the socket and mark as 0 in list for reuse
					FD_CLR(client_socket[i], &master);
					CloseIoTSocket(client_socket[i]);
					client_socket[i] = 0;
					free_package_buffer(packageBuffer[i]);
					packageBuffer[i] = NULL;
				}
				//Echo back the message that came in
				else if (valread>0)
				{
					/*
					printf("Received data[%d]", valread);
					printAllChar(buffer, valread);
					*/
					if (packageBuffer[i]->receiveCount+ valread > MAXRECV)
					{
						puts("Buffer over flow clear All buffer");
						packageBuffer[i]->receiveCount = 0;
						memset(packageBuffer[i]->tempBuffer,'\0', MAXRECV);
					}
					else
					{
						charcat(packageBuffer[i]->tempBuffer, buffer, packageBuffer[i]->receiveCount, valread);
						packageBuffer[i]->receiveCount += valread;
					}


					//try to get a completed IoT Package
					recv_result result;
					do
					{
						IoT_Package package_info = generate_iot_package();

						result = getCompletedPackage(packageBuffer[i]->tempBuffer,
							&packageBuffer[i]->receiveCount,
							&package_info);

						if (result== recv_result_COMPLETED)
						{
							package_info.belongSocketIdx = i;
							handle_package(&package_info);
						}

						free_package(&package_info);
					} while (result == recv_result_COMPLETED);

					if (packageBuffer[i]->receiveCount == 0)
					{
						printf("Buffer[%d] cleared2\n",i);
					}


				}
			}

		}
	}
}
예제 #12
0
// Threads handle chunks of the packages list. Since we don't know where
// package definitions are split in the list data, we'll usually toss some data
// from the front (it was handled as part of another chunk), and grab some
// extra data from the back. These will typically be small amounts, and the
// data is read-only, so rather than track splits (requiring synchronization),
// we just always locally discover the bounds (put another way, the overlapping
// areas at the front and back of chunks are lexed twice).
//
// Returns the number of packages parsed (possibly 0), or -1 on error. In the
// case of an error, packages already parsed *are not* freed, and enq *is
// not* reset.
//
// We're not treating the input as anything but ASCII text, though it's almost
// certainly UTF8. Need to ensure that newlines and pattern tags are all
// strictly ASCII or change how we handle things FIXME.
//
// Typical rules for DFA: If NULL, it's unused. If it points to a pointer to
// NULL, construct it from whatever we find. If it points to a non-NULL
// pointer, use that as a filter for construction of our list.
static int
lex_chunk(size_t offset,const char *start,const char *end,
		const char *veryend,pkgobj ***enq,
		struct pkgparse *pp){
	const char *expect,*pname,*pver,*pstatus,*c,*delim;
	size_t pnamelen,pverlen;
	int rewardstate,state;
	unsigned newp = 0;
	unsigned filter;
	dfactx dctx;
	pkgobj *po;

	// filter is 0 if we're building the dfa, 1 if we're being filtered by
	// the dfa, and undefined if dga == NULL
	if(pp->dfa){
		filter = *(pp->dfa) ? 1 : 0;
	}else{
		filter = 0; // FIXME get rid of this when gcc improves
	}
	// First, find the start of our chunk:
	//  - If we are offset 0, we are at the start of our chunk
	//  - Otherwise, if the previous two characters (those preceding our
	//     chunk) are newlines, we are at the start of our chunk,
	//  - Otherwise, if the first character is a newline, and the previous
	//     character is a newline, we are at the start of our chunk
	//  - Otherwise, our chunk starts at the first double newline
	if(offset){
		// We can be in one of two states: we know the previous
		// character to have been a newline, or we don't.
		state = STATE_PDATA;
		//assert(pp->csize > 2); // sanity check
		for(c = start - 2 ; c < end ; ++c){
			if(*c == '\n'){
				if(state == STATE_NLINE){
					++c;
					break;
				}
				state = STATE_NLINE;
			}else{
				state = STATE_PDATA;
			}
		}
	}else{
		c = start;
	}
	// We are at the beginning of our chunk, which might be 0 bytes. Any
	// partial record with which our map started has been skipped
	// Upon reaching the (optional, only one allowed) delimiter on each
	// line, delim will be updated to point one past that delimiter (which
	// might be outside the chunk!), and to chew whitespace.
	delim = NULL;
	expect = NULL;
	// We hand create_package our raw map bytes; it allocates the destbuf.
	// These are thus reset on each package.
	pname = NULL; pver = NULL; pstatus = NULL;
	state = STATE_RESET; // number of newlines we've seen, bounded by 2
	rewardstate = STATE_RESET;
	pverlen = pnamelen = 0;
	while(c < end || (state != STATE_RESET && c < veryend)){
		if(*c == '\n'){ // State machine is driven by newlines
			switch(state){
			case STATE_NLINE:{ // double newline
				if(pname == NULL || pnamelen == 0){
					return -1; // No package name
				}
				if(pver == NULL || pverlen == 0){
					if(!pp->statusfile){
						return -1; // No package version
					}
				}
				if(!pp->statusfile || pstatus){
					if(pp->dfa && filter){
						pkgobj *mpo;

						init_dfactx(&dctx,*pp->dfa);
						if( (mpo = match_dfactx_nstring(&dctx,pname,pnamelen)) ){
							if((po = create_package(pname,pnamelen,pver,pverlen,pp->sharedpcache)) == NULL){
								return -1;
							}
							pthread_mutex_lock(&mpo->lock);
							po->dfanext = mpo->dfanext;
							mpo->dfanext = po;
							pthread_mutex_unlock(&mpo->lock);
							po->haslock = 0;
						}else{
							po = NULL;
						}
					}else if((po = create_package(pname,pnamelen,pver,pverlen,pp->sharedpcache)) == NULL){
						return -1;
					}else if(pthread_mutex_init(&po->lock,NULL)){
						free_package(po);
					}else{
						po->haslock = 1;
					}
				}else{
					po = NULL;
				}
				// Package ended!
				if(po){
					++newp;
					**enq = po;
					*enq = &po->next;
				}
				pname = NULL;
				pver = NULL;
				pstatus = NULL;
				state = STATE_RESET;
				break;
			} // Else we processed a line of the current package
			case STATE_PACKAGE_DELIMITED:
// Don't allow a package to be named twice. Defined another way, require an
// empty line between every two instances of a Package: line.
				if(pname){
					return -1;
				}
				pnamelen = c - delim;
				pname = delim;
				break;
			case STATE_VERSION_DELIMITED:
				if(pver){
					return -1;
				}
				pverlen = c - delim;
				pver = delim;
				break;
			case STATE_STATUS_DELIMITED:
				if(pstatus){
					return -1;
				}
				pstatus = delim;
				break;
			}
			if(state != STATE_RESET){
				state = STATE_NLINE;
			}
		}else switch(state){ // not a newline
			case STATE_NLINE:
			case STATE_RESET:
				delim = NULL;
				start = c;
				if(*c == 'V'){
					state = STATE_EXPECT;
					expect = "ersion:";
					rewardstate = STATE_VERSION_DELIMITED;
				}else if(*c == 'P'){
					state = STATE_EXPECT;
					expect = "ackage:";
					rewardstate = STATE_PACKAGE_DELIMITED;
				}else if(*c == 'S'){
					state = STATE_EXPECT;
					expect = "tatus: install ";
					rewardstate = STATE_STATUS_DELIMITED;
				}else{
					state = STATE_PDATA;
				}
				break;
			case STATE_EXPECT:
				if(*c == *expect){
					if(!*++expect){
						state = STATE_DELIM;
						delim = c + 1;
					}
				}else{
					state = STATE_PDATA;
				}
				break;
			case STATE_DELIM:
				if(isspace(*c)){
					++delim;
				}else{
					state = rewardstate;
				}
				break;
		}
		++c;
	}
	if(state != STATE_RESET){
		return -1;
	}
	return newp;
}