static void
handle_packet_in( uint64_t datapath_id, uint32_t transaction_id,
                  uint32_t buffer_id, uint16_t total_len,
                  uint16_t in_port, uint8_t reason, const buffer *data,
                  void *user_data ) {
  assert( in_port != 0 );
  assert( data != NULL );
  assert( user_data != NULL );

  routing_switch *routing_switch = user_data;

  debug( "Packet-In received ( datapath_id = %#" PRIx64 ", transaction_id = %#lx, "
         "buffer_id = %#lx, total_len = %u, in_port = %u, reason = %#x, "
         "data_len = %u ).", datapath_id, transaction_id, buffer_id,
         total_len, in_port, reason, data->length );

  const port_info *port = lookup_port( routing_switch->switches, datapath_id, in_port );
  if ( port == NULL ) {
    debug( "Ignoring Packet-In from unknown port." );
    return;
  }

  packet_info packet_info = get_packet_info( data );
  const uint8_t *src = packet_info.eth_macsa;
  const uint8_t *dst = packet_info.eth_macda;

  if ( in_port > OFPP_MAX && in_port != OFPP_LOCAL ) {
    error( "Packet-In from invalid port ( in_port = %u ).", in_port );
    return;
  }
  if ( !port->external_link || port->switch_to_switch_reverse_link ) {
    if ( !port->external_link
         && port->switch_to_switch_link
         && port->switch_to_switch_reverse_link
         && !is_ether_multicast( dst )
         && lookup_fdb( routing_switch->fdb, src, &datapath_id, &in_port ) ) {
      debug( "Found a Packet-In from switch-to-switch link." );
    }
    else {
      debug( "Ignoring Packet-In from not external link." );
      return;
    }
  }

  if ( !update_fdb( routing_switch->fdb, src, datapath_id, in_port ) ) {
    return;
  }

  if ( !authenticate( src ) ) {
    if ( packet_type_ipv4( data ) ) {
      if ( packet_type_ipv4_udp( data ) ) {
        if ( ( packet_info.udp_src_port == 67 ) ||
             ( packet_info.udp_src_port == 68 ) ||
             ( packet_info.udp_dst_port == 67 ) ||
             ( packet_info.udp_dst_port == 68 ) ) {
          // DHCP/BOOTP is allowed by default
          goto authenticated;
        }
        if ( ( packet_info.udp_src_port == 53 ) ||
             ( packet_info.udp_dst_port == 53 ) ) {
          // DNS is allowed by default
          goto authenticated;
        }
      }
      else if ( packet_type_ipv4_tcp( data ) ) {
        if ( ( packet_info.tcp_src_port == 53 ) ||
             ( packet_info.tcp_dst_port == 53 ) ) {
          // DNS is allowed by default
          goto authenticated;
        }
      }
      redirect( datapath_id, in_port, data );
    }
    else if ( packet_type_arp( data ) ) {
      // ARP request/reply is allowed
      goto authenticated;
    }
    return;
  }

authenticated:
  {
    uint16_t out_port;
    uint64_t out_datapath_id;

    if ( lookup_fdb( routing_switch->fdb, dst, &out_datapath_id, &out_port ) ) {
      // Host is located, so resolve path and send flowmod
      if ( ( datapath_id == out_datapath_id ) && ( in_port == out_port ) ) {
        // in and out are same
        return;
      }

      make_path( routing_switch, datapath_id, in_port, out_datapath_id, out_port, data );
    }
    else {
      // Host's location is unknown, so flood packet
      flood_packet( datapath_id, in_port, data, routing_switch->switches );
    }
  }
}
Exemplo n.º 2
0
void qlevel_load(STRING *filename)
{
	STRING *file = "#256";
	make_path(file, filename);
	if(!file_exists(file))
	{
		error("FIXIT! qlevel_load: File does not exist!");
		return;
	}
		
	level_load(NULL);
	
	int countEntity = ini_read_int(file, "Level Information", "EntityCount", 0);
	int countLight = ini_read_int(file, "Level Information", "LightCount", 0);
	int countFog = ini_read_int(file, "Level Information", "FogCount", 0);
	
	STRING *section = "#64";
	
	int i;
	char buffer[256];
	STRING *strTemp = "#128";
	for(i = 0; i < countEntity; i++)
	{
		diag("\nLoad :");
		str_cpy(section, "Entity ");
		str_cat(section, str_for_int(NULL, i));
		diag(section);
		
		ini_read_buffer(file, section, "Model", "error.mdl", buffer, 256);
		ENTITY *ent = ent_create(buffer, nullvector, qlevel_entity_init);
		ent->group = GROUP_LEVEL;
		ent->x = ini_read_float(file, section, "X", 0);
		ent->y = ini_read_float(file, section, "Y", 0);
		ent->z = ini_read_float(file, section, "Z", 0);
		
		ent->pan = ini_read_float(file, section, "Pan", 0);
		ent->tilt = ini_read_float(file, section, "Tilt", 0);
		ent->roll = ini_read_float(file, section, "Roll", 0);
		
		ent->scale_x = ini_read_float(file, section, "ScaleX", 0);
		ent->scale_y = ini_read_float(file, section, "ScaleY", 0);
		ent->scale_z = ini_read_float(file, section, "ScaleZ", 0);
		
		ent->lightrange = ini_read_float(file, section, "Lightrange", 0);
		
		int iActionCount = ini_read_int(file, section, "ActionCount", 0);
		int iA = 0;
		STRING *actionName = "#64";
		for(iA = 0; iA < iActionCount; iA++)
		{
			str_cpy(actionName, "Action");
			str_cat(actionName, str_for_int(NULL, iA));
			ini_read_buffer(file, section, actionName, "", buffer, 256);
			str_cpy(strTemp, buffer);
			diag("\nTry adding action '");
			diag(strTemp);
			diag("'...");
			if(actinfo_add(ent->string1, strTemp))
			{
				diag(" SUCCESS!\n\tTry getting function pointer...");
				void *fn = action_getptr(strTemp);
				if(fn != NULL)
				{
					diag(" SUCCESS!");
					scheduler_add(fn, ent);
				}
				else
				{
					diag(" FAILED!");				
				}
			}
			else
			{
				diag(" FAILED!");
			}
		}
		diag("\nEntity loaded!");
	}
}
Exemplo n.º 3
0
/* Load PLS file into plist. Return the number of items read. */
static int plist_load_pls (struct plist *plist, const char *fname,
		const char *cwd)
{
	FILE *file;
	char *line;
	long i, nitems, added = 0;
	char *e;

	if (!(file = fopen(fname, "r"))) {
		error ("Can't open playlist file: %s",
				strerror(errno));
		return 0;
	}

	line = read_ini_value (file, "playlist", "NumberOfEntries");
	if (!line) {

		/* Assume that it is a pls file version 1 - plist_load_m3u()
		 * should handle it like an m3u file without the m3u extensions. */
		fclose (file);
		return plist_load_m3u (plist, fname, cwd, 0);
	}

	nitems = strtol (line, &e, 10);
	if (*e) {
		error ("Broken PLS file");
		free (line);
		return 0;
	}
	free (line);

	for (i = 1; i <= nitems; i++) {
		char *pls_file, *pls_title, *pls_length;
		char key[16];
		int time;
		int last_added;
		char path[2*PATH_MAX];

		sprintf (key, "File%ld", i);
		if (!(pls_file = read_ini_value(file, "playlist", key))) {
			error ("Broken PLS file");
			break;
		}

		sprintf (key, "Title%ld", i);
		pls_title = read_ini_value(file, "playlist", key);

		sprintf (key, "Length%ld", i);
		pls_length = read_ini_value(file, "playlist", key);

		if (pls_length) {
			time = strtol (pls_length, &e, 10);
			if (*e)
				time = -1;
		}
		else
			time = -1;

		if (strlen(pls_file) <= PATH_MAX) {
			make_path (path, sizeof(path), cwd, pls_file);
			if (plist_find_fname(plist, path) == -1) {
				last_added = plist_add (plist, path);

				if (pls_title && pls_title[0])
					plist_set_title_tags (plist, last_added,
							pls_title);

				if (time > 0) {
					plist->items[last_added].tags
						= tags_new ();
					plist->items[last_added].tags->time
						= time;
					plist->items[last_added].tags->filled
						|= TAGS_TIME;
				}
			}
		}

		free (pls_file);
		if (pls_title)
			free (pls_title);
		if (pls_length)
			free (pls_length);
		added++;
	}

	fclose (file);

	return added;
}
Exemplo n.º 4
0
hid_device * HID_API_EXPORT hid_open_path(const char *path)
{
	hid_device *dev = NULL;

	dev = new_hid_device();

	libusb_device **devs;
	libusb_device *usb_dev;
	ssize_t num_devs;
	int res;
	int d = 0;
	int good_open = 0;
	
	setlocale(LC_ALL,"");
	
	if (!initialized)
		hid_init();

	num_devs = libusb_get_device_list(NULL, &devs);
	while ((usb_dev = devs[d++]) != NULL) {
		struct libusb_device_descriptor desc;
		struct libusb_config_descriptor *conf_desc = NULL;
		int i,j,k;
		libusb_get_device_descriptor(usb_dev, &desc);

		if (libusb_get_active_config_descriptor(usb_dev, &conf_desc) < 0)
			continue;
		for (j = 0; j < conf_desc->bNumInterfaces; j++) {
			const struct libusb_interface *intf = &conf_desc->interface[j];
			for (k = 0; k < intf->num_altsetting; k++) {
				const struct libusb_interface_descriptor *intf_desc;
				intf_desc = &intf->altsetting[k];
				if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID) {
					char *dev_path = make_path(usb_dev, intf_desc->bInterfaceNumber);
					if (!strcmp(dev_path, path)) {
						/* Matched Paths. Open this device */

						// OPEN HERE //
						res = libusb_open(usb_dev, &dev->device_handle);
						if (res < 0) {
							LOG("can't open device\n");
							free(dev_path);
 							break;
						}
						good_open = 1;
						
						/* Detach the kernel driver, but only if the
						   device is managed by the kernel */
						if (libusb_kernel_driver_active(dev->device_handle, intf_desc->bInterfaceNumber) == 1) {
							res = libusb_detach_kernel_driver(dev->device_handle, intf_desc->bInterfaceNumber);
							if (res < 0) {
								libusb_close(dev->device_handle);
								LOG("Unable to detach Kernel Driver\n");
								free(dev_path);
								good_open = 0;
								break;
							}
						}
						
						res = libusb_claim_interface(dev->device_handle, intf_desc->bInterfaceNumber);
						if (res < 0) {
							LOG("can't claim interface %d: %d\n", intf_desc->bInterfaceNumber, res);
							free(dev_path);
							libusb_close(dev->device_handle);
							good_open = 0;
							break;
						}

						/* Store off the string descriptor indexes */
						dev->manufacturer_index = desc.iManufacturer;
						dev->product_index      = desc.iProduct;
						dev->serial_index       = desc.iSerialNumber;

						/* Store off the interface number */
						dev->interface = intf_desc->bInterfaceNumber;
												
						/* Find the INPUT and OUTPUT endpoints. An
						   OUTPUT endpoint is not required. */
						for (i = 0; i < intf_desc->bNumEndpoints; i++) {
							const struct libusb_endpoint_descriptor *ep
								= &intf_desc->endpoint[i];

							/* Determine the type and direction of this
							   endpoint. */
							int is_interrupt =
								(ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK)
							      == LIBUSB_TRANSFER_TYPE_INTERRUPT;
							int is_output = 
								(ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)
							      == LIBUSB_ENDPOINT_OUT;
							int is_input = 
								(ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)
							      == LIBUSB_ENDPOINT_IN;

							/* Decide whether to use it for intput or output. */
							if (dev->input_endpoint == 0 &&
							    is_interrupt && is_input) {
								/* Use this endpoint for INPUT */
								dev->input_endpoint = ep->bEndpointAddress;
								dev->input_ep_max_packet_size = ep->wMaxPacketSize;
							}
							if (dev->output_endpoint == 0 &&
							    is_interrupt && is_output) {
								/* Use this endpoint for OUTPUT */
								dev->output_endpoint = ep->bEndpointAddress;
							}
						}
						
						pthread_create(&dev->thread, NULL, read_thread, dev);
						
						// Wait here for the read thread to be initialized.
						pthread_barrier_wait(&dev->barrier);
						
					}
					free(dev_path);
				}
			}
		}
		libusb_free_config_descriptor(conf_desc);

	}

	libusb_free_device_list(devs, 1);
	
	// If we have a good handle, return it.
	if (good_open) {
		return dev;
	}
	else {
		// Unable to open any devices.
		free_hid_device(dev);
		return NULL;
	}
}
Exemplo n.º 5
0
/* Load image 'path' in the background and insert into pixmap_cache.
 * Call callback(data, path) when done (path is NULL => error).
 * If the image is already uptodate, or being created already, calls the
 * callback right away.
 */
void
pixmap_background_thumb(const gchar *path, GFunc callback, gpointer data)
{
	gboolean	found = FALSE;

	MaskedPixmap* image = g_fscache_lookup_full(pixmap_cache, path, FSCACHE_LOOKUP_ONLY_NEW, &found);

	if (found)
	{
		dbg(0, "found");
		// Thumbnail is known, or being created
		if (image) g_object_unref(image);
		callback(data, NULL);
		return;
	}

	dbg(0, "FIXME not found");
#if 0
	pid_t		child;
	ChildThumbnail	*info;
	g_return_if_fail(image == NULL);

	GdkPixbuf* pixbuf = get_thumbnail_for(path);
	
	if (!pixbuf)
	{
		struct stat info1, info2;
		char *dir;

		dir = g_path_get_dirname(path);

		// If the image itself is in ~/.thumbnails, load it now (ie, don't create thumbnails for thumbnails!).
		if (stat(dir, &info1) != 0)
		{
			callback(data, NULL);
			g_free(dir);
			return;
		}
		g_free(dir);

		if (stat(make_path(home_dir, ".thumbnails/normal"),
			    &info2) == 0 &&
			    info1.st_dev == info2.st_dev &&
			    info1.st_ino == info2.st_ino)
		{
			pixbuf = rox_pixbuf_new_from_file_at_scale(path, PIXMAP_THUMB_SIZE, PIXMAP_THUMB_SIZE, TRUE, NULL);
			if (!pixbuf)
			{
				g_fscache_insert(pixmap_cache, path, NULL, TRUE);
				callback(data, NULL);
				return;
			}
		}
	}
		
	if (pixbuf)
	{
		MaskedPixmap *image;

		image = masked_pixmap_new(pixbuf);
		gdk_pixbuf_unref(pixbuf);
		g_fscache_insert(pixmap_cache, path, image, TRUE);
		callback(data, (gchar *) path);
		g_object_unref(G_OBJECT(image));
		return;
	}

	MIME_type* type = type_from_path(path);
	if (!type) type = text_plain;

	// Add an entry, set to NULL, so no-one else tries to load this image.
	g_fscache_insert(pixmap_cache, path, NULL, TRUE);

	gchar* thumb_prog = thumbnail_program(type);

	// Only attempt to load 'images' types ourselves
	if (thumb_prog == NULL && strcmp(type->media_type, "image") != 0)
	{
		callback(data, NULL);
		return;		// Don't know how to handle this type
	}

	child = fork();

	if (child == -1)
	{
		g_free(thumb_prog);
		delayed_error("fork(): %s", g_strerror(errno));
		callback(data, NULL);
		return;
	}

	if (child == 0)
	{
		// We are the child process.  (We are sloppy with freeing memory, but since we go away very quickly, that's ok.)
		if (thumb_prog)
		{
			DirItem *item;
			
			item = diritem_new(g_basename(thumb_prog));

			diritem_restat(thumb_prog, item, NULL);
			if (item->flags & ITEM_FLAG_APPDIR)
				thumb_prog = g_strconcat(thumb_prog, "/AppRun",
						       NULL);

			execl(thumb_prog, thumb_prog, path,
			      thumbnail_path(path),
			      g_strdup_printf("%d", PIXMAP_THUMB_SIZE),
			      NULL);
			_exit(1);
		}

		child_create_thumbnail(path);
		_exit(0);
	}

	g_free(thumb_prog);

	info = g_new(ChildThumbnail, 1);
	info->path = g_strdup(path);
	info->callback = callback;
	info->data = data;
	on_child_death(child, (CallbackFn) thumbnail_child_done, info);
#endif
}
Exemplo n.º 6
0
/* returns:
 * 0   ok, remove file from list
 * -1  failure
 */
static int getfile(const rfile *fi, unsigned int opt,
             const char *output, const char *destname)
{
    struct stat sb;
    char* dest = NULL;
    getmode_t how = getNormal;
    bool mkunique = false;
    int r, ret = -1;

    if((get_glob_mask && fnmatch(get_glob_mask, base_name_ptr(fi->path),
                                 FNM_EXTMATCH) == FNM_NOMATCH)
#ifdef HAVE_REGEX
       || (get_rx_mask_set && regexec(&get_rx_mask, base_name_ptr(fi->path),
                                      0, 0, 0) == REG_NOMATCH)
#endif
        )
    {
        return 0;
    }

    if(!output)
        output = ".";

    if(test(opt, GET_PARENTS)) {
        char *apath = base_dir_xptr(fi->path);
        if (asprintf(&dest, "%s%s/%s", output, apath, destname) == -1)
        {
          free(apath);
          fprintf(stderr, _("Failed to allocate memory.\n"));
          return -1;
        }
        free(apath);
    } else {
        /* check if -o option is given, if GET_OUTPUT_FILE is set, we only
         * transfer one file and output is set to the filename. However, if
         * the destination already exists and is a directory, we assume
         * that the user meant a directory */

        int dest_is_file = test(opt, GET_OUTPUT_FILE);

        if(stat(output, &sb) == 0) {
            if(S_ISDIR(sb.st_mode)) {
                dest_is_file = false;
            }
        }

        if(dest_is_file)
            dest = xstrdup(output);
        else
            if (asprintf(&dest, "%s/%s", output, destname) == -1)
            {
              fprintf(stderr, _("Failed to allocate memory.\n"));
              return -1;
            }
    }

    /* make sure destination directory exists */
    {
        char *destdir = base_dir_xptr(dest);
        if(destdir) {
            bool r = make_path(destdir);
            if(!r) {
                if (errno == EEXIST)
                  ftp_err("`%s' exists but is not a directory\n", destdir);
                else
                  ftp_err("%s: %s\n", destdir, strerror(errno));
                transfer_mail_msg(_("Couldn't create directory: %s\n"),
                                  destdir);
                free(destdir);
                return -1;
            }
            /* change permission and group, if requested */
            if(test(opt, GET_CHMOD)) {
                if(stat(destdir, &sb) == 0) {
                    mode_t m = sb.st_mode;
                    m = mode_adjust(m, cmod);
                    if(chmod(destdir, m) != 0)
                        perror(destdir);
                }           }
            if(test(opt, GET_CHGRP)) {
                if(chown(destdir, -1, group_change) != 0)
                    perror(dest);
            }
            free(destdir);
        }
    }

    /* check if destination file exists */
    if(stat(dest, &sb) == 0) {
        if(test(opt, GET_SKIP_EXISTING)) {
            if(test(opt, GET_VERBOSE)) {
							char* sp = shortpath(dest, 42, gvLocalHomeDir);
              fprintf(stderr, _("Local file '%s' exists, skipping...\n"),
                      sp);
							stats_file(STATS_SKIP, 0);
							free(sp);
						}
            return 0;
        }
        if(test(opt, GET_UNIQUE))
            mkunique = true;
        else if(test(opt, GET_APPEND))
            how = getAppend;
        else if(test(opt, GET_NEWER)) {
            struct tm *fan = gmtime(&sb.st_mtime);
            time_t ft = ftp_filetime(fi->path, test(opt, GET_FORCE_NEWER));
            sb.st_mtime = gmt_mktime(fan);

            ftp_trace("get -n: remote file: %s", ctime(&ft));
            ftp_trace("get -n: local file: %s\n", ctime(&sb.st_mtime));

            if(sb.st_mtime >= ft && ft != (time_t)-1) {
                if(test(opt, GET_VERBOSE)) {
									char* sp = shortpath(dest, 30, gvLocalHomeDir);
                    ftp_err(_(
                        "Local file '%s' is newer than remote, skipping...\n"),
                            sp);
									stats_file(STATS_SKIP, 0);
									free(sp);
								}
                return 0;
            }
        } else if(!test(opt, GET_RESUME)) {
            if(!get_owbatch && !gvSighupReceived) {
                struct tm *fan = gmtime(&sb.st_mtime);
                time_t ft = ftp_filetime(fi->path, test(opt, GET_FORCE_NEWER));
                int a;
                char *e;

                sb.st_mtime = gmt_mktime(fan);
                e = xstrdup(ctime(&sb.st_mtime));
								char* sp = shortpath(dest, 42, gvLocalHomeDir);
                a = ask(ASKYES|ASKNO|ASKUNIQUE|ASKCANCEL|ASKALL|ASKRESUME,
                        ASKRESUME,
                        _("Local file '%s' exists\nLocal: %lld bytes, %sRemote: %lld bytes, %sOverwrite?"),
                        sp,
                        (unsigned long long) sb.st_size, e ? e : "unknown date\n",
                        ftp_filesize(fi->path), ctime(&ft));
								free(sp);
                free(e);
                if(a == ASKCANCEL) {
                    get_quit = true;
                    return 0;
                }
                else if(a == ASKNO)
                    return 0;
                else if(a == ASKUNIQUE)
                    mkunique = true;
                else if(a == ASKALL) {
                    get_owbatch = true;
                }
                else if(a == ASKRESUME)
                    opt |= GET_RESUME; /* for this file only */
                /* else a == ASKYES */
            }
        }
        if(test(opt, GET_RESUME))
            how = getResume;
    }

    if(mkunique) {
        char* newdest = make_unique_filename(dest);
        free(dest);
        dest = newdest;
    }

    /* the file doesn't exist or we choosed to overwrite it, or changed dest */

    if(rislink(fi) && test(opt, GET_NO_DEREFERENCE)) {
        /* remove any existing destination */
        unlink(dest);
        ftp_err(_("symlinking '%s' to '%s'\n"), dest, fi->link);
        if(symlink(fi->link, dest) != 0)
            perror(dest);
        ret = 0;
    }
    else {
        r = do_the_get(fi->path, dest, how, opt);

        if(r == 0) {
			stats_file(STATS_SUCCESS, ftp->ti.total_size);
            ret = 0;
            if(test(opt, GET_PRESERVE))
                get_preserve_attribs(fi, dest);
            if(test(opt, GET_CHMOD)) {
                mode_t m = rfile_getmode(fi);
                m = mode_adjust(m, cmod);
                if(chmod(dest, m) != 0)
                    perror(dest);
            }
            if(test(opt, GET_CHGRP)) {
                if(chown(dest, -1, group_change) != 0)
                    perror(dest);
            }
            if(test(opt, GET_DELETE_AFTER)) {
                bool dodel = false;
								char* sp = shortpath(fi->path, 42, ftp->homedir);
                if(!test(opt, GET_FORCE)
                   && !get_delbatch && !gvSighupReceived)
                {
                    int a = ask(ASKYES|ASKNO|ASKCANCEL|ASKALL, ASKYES,
                                _("Delete remote file '%s'?"), sp);
                    if(a == ASKALL) {
                        get_delbatch = true;
                        dodel = true;
                    }
                    else if(a == ASKCANCEL)
                        get_quit = true;
                    else if(a != ASKNO)
                        dodel = true;
                } else
                    dodel = true;

                if(dodel) {
                    ftp_unlink(fi->path);
                    if(ftp->code == ctComplete)
                        fprintf(stderr, _("%s: deleted\n"), sp);
                    else
                        fprintf(stderr, _("error deleting '%s': %s\n"),
															  sp, ftp_getreply(false));
                }
								free(sp);
            }
        } else {
			stats_file(STATS_FAIL, 0);
			ret = -1;
		}
    }

    free(dest);
    return ret;
}
Exemplo n.º 7
0
void vgetty_rings(int *rings_wanted)
     {

     if (strlen(cvd.rings.d.p) != 0)

          if (strncmp((char*) cvd.rings.d.p, "/", 1) == 0)
               {
               char ring_file_name[VOICE_BUF_LEN];
               FILE *ring_file;

               sprintf(ring_file_name, "%s.%s", (char*) cvd.rings.d.p, DevID);
               ring_file = fopen(ring_file_name, "r");

               if (ring_file != NULL)
                    {
                    fscanf(ring_file, "%d", rings_wanted);
                    fclose(ring_file);
                    lprintf(L_JUNK,
                     "%s: read number of rings (%d) from file %s",
                     program_name, *rings_wanted, ring_file_name);
                    }
               else
                    {
                    sprintf(ring_file_name, "%s", (char*) cvd.rings.d.p);
                    ring_file = fopen(ring_file_name, "r");

                    if (ring_file != NULL)
                         {
                         fscanf(ring_file, "%d", rings_wanted);
                         fclose(ring_file);
                         lprintf(L_JUNK,
                          "%s: read number of rings (%d) from file %s",
                          program_name, *rings_wanted, ring_file_name);
                         };

                    };

               }
          else
               {
               *rings_wanted = atoi(cvd.rings.d.p);
               lprintf(L_JUNK, "%s: number of rings (%d) was set directly",
                program_name, *rings_wanted);
               };

     if (strlen(cvd.message_flag_file.d.p) != 0)
          {
          char flag_file_name[VOICE_BUF_LEN];
          FILE *flag_file;

          make_path(flag_file_name, cvd.voice_dir.d.p,
           cvd.message_flag_file.d.p);
          flag_file = fopen(flag_file_name, "r");

          if (flag_file != NULL)
               {
               *rings_wanted -= cvd.toll_saver_rings.d.i;
               fclose(flag_file);
               lprintf(L_JUNK, "%s: decremented number of rings (%d) by %d",
                program_name, *rings_wanted, cvd.toll_saver_rings.d.i);
               };

          };

     if (*rings_wanted < 2)
          {
          lprintf(L_WARN,
           "%s: number of rings (%d) too small, reseting to 2",
           program_name, *rings_wanted);
          *rings_wanted = 2;
          };

     }
Exemplo n.º 8
0
int WorkerBee::cp_r(const std::string &source, const std::string &dest) {
  make_path(dirname(strdup(dest.c_str()))); 
  return cp(source, dest);
}
Exemplo n.º 9
0
int vfu_get_dir_name( const char *prompt, VString &target, int should_exist )
{ 
  int res = -1;
  /*
  #ifdef _TARGET_UNIX_
  leaveok(stdscr, FALSE);
  #endif
  */
  VArray dir_list;
   
  say1(prompt); 
  say2(""); 
  
  int pos = 0; 
  int page = 0;
  int ch = 0; 
  
  int insert = 1;
  int firsthit = 1;
  
  pos = str_len( target );

  //------------------------------------------------------------------
  
  con_cshow();
  say2( target, firsthit ? cINPUT2 : cINPUT );
  while(1) 
    {
    int mx = con_max_x() - 1;
    VString target_out = target;
    if ( (pos < page) || (pos+1 > page + mx) || (page > 0 && pos == page) ) 
      page = pos - mx / 2;
    if ( page < 0 ) page = 0;

    str_trim_left( target_out, page );
    str_sleft( target_out, mx );
    str_pad( target_out, -mx );
    if ( page > 0 )
      str_set_ch( target_out, 0, '<' );
    if ( str_len( target ) - page > mx )
      str_set_ch( target_out, mx-1, '>' );
    
    say2( target_out, firsthit ? cINPUT2 : cINPUT );
    con_xy( pos-page+1, con_max_y() );

    
    if (ch == 0) ch = con_getch();
    if (ch == '\\') ch = '/'; /* dos hack :)) */
    if ( ch == '/' && str_find( target, '/' ) == -1 && target[0] == '~' )
      {
      target = tilde_expand( target );
      str_fix_path( target );
      pos = str_len( target );
      ch = 0;
      }
      
    if ((ch == 8 || ch == KEY_BACKSPACE) && pos > 0) 
      { 
      pos--; 
      str_del( target, pos, 1 );
      } 
    else
    if (ch == KEY_CTRL_A && str_len( target ) > 0)
      {
      int z = str_len( target )-1;
      if ( str_get_ch(target, z) == '/' ) z--;
      while ( z > 0 && str_get_ch(target,z) != '/' ) z--;
      z++;
      str_sleft(target,z);
      pos = z;
      }
    else
    if ( ch == 9 && str_len( target ) > 0)
      { 
      int z; 
      dir_list.undef();
      VString dmain; /* main/base path */
      VString dtail; /* item that should be expanded/glob */
      
      dmain = str_file_path( target );
      dtail = str_file_name_ext( target );
      
      /*
      int lastslash = str_rfind(target, '/');
      if ( lastslash == -1 ) 
        {
        dmain = "";
        dtail = target;
        }
      else
        {
        dmain = target;
        dtail = target;
        str_sleft( dmain, lastslash+1 );
        str_trim_left( dtail, lastslash+1 );
        }
      */
      
      __glob_gdn( dmain, dtail, dir_list );
  
      z = dir_list.count()-1;
      if (dir_list.count()) 
        {
        if ( dir_list.count() > 1)
          {
          int mc = 0; /* match count        */
          int mi = 0; /* match letter index */
          while(4)
            {
            mc = 0;
            int li; /* counter */
            for ( li = 0; li < dir_list.count(); li++ )
              {
              if ( str_get_ch( dir_list[ 0], mi ) == 
                   str_get_ch( dir_list[li], mi ) )
                mc++;
              }
            if ( mc != dir_list.count() )
              break;
            mi++;
            }
          target.setn( dmain + dir_list[0], str_len( dmain ) + mi );
          pos = str_len( target );
          say2( target, cINPUT );
          con_xy( pos+1, con_max_y() );
          
          vfu_beep();
          ch = con_getch();
          if ( ch != 9 ) { dir_list.undef(); continue; }
          dir_list.sort();
          con_chide();
          z = vfu_menu_box( 10, 5, "Complete...", &dir_list );
          con_cshow();
          ch = 0;
          }
        else
          ch = 0;
        if ( z != -1 )
          {
          while( str_len( target ) > 0 && target[-1] != '/' )
            str_chop( target );
          target += dir_list[z];
          }
        
        pos = str_len( target );
        
        dir_list.undef();
        if (ch != 0) continue;
        }
      else
        { /* no match found -- cannot complete */
        vfu_beep();
        }
      } 
    else 
    if (ch == 13)
      { 
      res = 1;
      break; 
      } 
    else 
    if (ch == 27) 
      { 
      target = "";
      res = 0;
      break; 
      } 
    if (ch == KEY_CTRL_U)
      { 
      target = "";
      pos = 0;
      }
    else
    if (ch == KEY_CTRL_X)
      {
        char t[MAX_PATH];
        if ( target[0] == '~' )
          target = tilde_expand( target );
        expand_path( target, t );
        str_fix_path( t );
        target = t;
        pos = str_len( target );
      }
    else 
    if (ch >= 32 && ch <= 255 ) // && pos < 70) 
      { 
      if (firsthit) 
        {
        target = "";
        pos = 0;
        }
      if (!insert) str_del( target, pos, 1 );
      str_ins_ch( target, pos, ch );
      pos++;
      } else
    if( ch == KEY_LEFT  )
      {
      if (pos > 0)
        pos--;
      } else
    if( ch == KEY_RIGHT )
      {
      if (pos < str_len( target ))
        pos++;
      } else
    if ( ch == KEY_IC   ) insert = !insert; else
    if ( ch == KEY_HOME ) pos = 0; else
    if ( ch == KEY_END  ) pos = str_len(target); else
    if ( ch == KEY_DC  && pos < str_len(target) ) 
       str_del( target, pos, 1 ); else
    if ( ch == KEY_NPAGE || ch == KEY_PPAGE )
      {
      con_chide();
      int zz = vfu_hist_menu( 5, 5, ( ch == KEY_PPAGE ) ? "Dir Entry History" : "ChDir History", 
                              ( ch == KEY_PPAGE ) ? HID_GETDIR : HID_CHDIR );
      con_cshow();
      if (zz != -1)
        {
        const char* pc = vfu_hist_get( ( ch == KEY_PPAGE ) ? HID_GETDIR : HID_CHDIR, zz );
        if ( pc )
          {
          target = pc;
          pos = str_len( target );
          }
        }
      }
    ch = 0; 
    firsthit = 0;
    }
  con_chide();
  
  //------------------------------------------------------------------
  str_cut_spc( target );
  if ( res == 1 && target[0] == '~' )
    {
    target = tilde_expand( target );
    str_fix_path( target );
    }
/*  
  if ( target.len() > 0 )
    { 
    // well this tmp is kind of s... ama k'vo da pravi chovek :)
    // FIXME: dos version?
    if ( __ExpandGetDirName && target[0] != '/'
       #ifdef _TARGET_GO32_
       && !( target[1] == ':' && target[2] == '/' )
       #endif
       )
      target = CPath + target;
    StrFixPath( target ); // add trailing slash if not exist
    } 
*/    
  /*
  #ifdef _TARGET_UNIX_
  leaveok(stdscr, TRUE);
  #endif
  */
  if ( res == 1 && str_len( target ) > 0 && should_exist && !dir_exist( target ))
    {
    vfu_beep();
    int ch = tolower( vfu_ask( "Directory does not exist! Create? "
                               "( ENTER=Yes, ESC=cancel )",
                               "\033\rcC" ));
    if ( ch == 27 ) 
      {
      res = 0;
      target = ""; 
      }
    else
    if ( ch == 13 )
       if (make_path( target ))
         {
         if(tolower(
            vfu_ask( "Cannot create path! ( ESC=cancel, C=continue-anyway )", 
            "\033Cc" )) == 27)
            {
            res = 0;
            target = "";
            }
         }
    }
  
  say1(" "); 
  say2(" "); 
  if ( str_len( target ) > 0)
    {
    str_fix_path( target );
    vfu_hist_add( HID_GETDIR, target );
    }
    
  str_cut_spc( target );
  
  ASSERT( res == 0 || res == 1 );
  return res;
} 
Exemplo n.º 10
0
/******************************************************************************
* extract_files: extract and restore files from binary. 
*
* @param hwnd: handle to window 
*
******************************************************************************/
static int 
extract_files(HWND hwnd)
{
    char *unix_style_work_dir_path, *command = NULL;
    char *work_dir_path;
    int command_length = 0;
    char *pch1, *pch2, *pch3;
    int i, j;

    log_message("Base extraction path: %s\n", temp_dir_path);

    /* Create the path to the work directory */
    if (g_user_path == NULL)
    {
        work_dir_path = allocate_string_buffer(strlen(temp_dir_path) + strlen(work_dir_basename) + RANDOM_STRING_LEN + strlen(DIRSEPSTR));
       
        if (work_dir_path == NULL)
        {
            fclose(g_logFile);
            if (g_console_install == FALSE || g_nosplash == FALSE)
            {
                sprintf(msg_box_string, "%s%s%s", "Error extracting files\nUnable to allocate memory\n\n", "See the log file at:\n\n", sfx_log_file);
                MessageBox(hwnd, msg_box_string, NULL, MB_OK);
                SendMessage(hwnd, WM_DESTROY, 0, 0);
            }
            exit(20);
        }

        if (g_env_var_path == NULL)
        {
            strcpycat(temp_dir_path, work_dir_basename, work_dir_path);
            srand(time(NULL));
            generate_random_string(work_dir_path, strlen(work_dir_path), RANDOM_STRING_LEN);
        }
        else
        {
            strcpy(work_dir_path, temp_dir_path);
        }
        strcat(work_dir_path, DIRSEPSTR);
    }
    else
    {
       log_message("User path: %s\n", g_user_path);

        if (g_user_path[strlen(g_user_path) - 1] != '\\')
        {
            work_dir_path = allocate_string_buffer(strlen(g_user_path) + strlen(DIRSEPSTR));
            if (work_dir_path == NULL)
            {
                fclose(g_logFile);
                if (g_console_install == FALSE || g_nosplash == FALSE)
                {
                    sprintf(msg_box_string, "%s%s%s", "Error extracting files\nUnable to allocate memory\n\n", "See the log file at:\n\n", sfx_log_file);
                    MessageBox(hwnd, msg_box_string, NULL, MB_OK);
                    SendMessage(hwnd, WM_DESTROY, 0, 0);
                }
                exit(21);
            }
            strcpycat(g_user_path, DIRSEPSTR, work_dir_path);
        }
        else
        {
            work_dir_path = g_user_path;
        }
    }

    log_message("Extraction path: %s\n", work_dir_path);

    /* Create the work directory */
    if (!file_exists (work_dir_path))
        if (make_path (work_dir_path, 0777) != 0)
        {
            log_message("Could not create directory: %s\n", work_dir_path);
            fclose(g_logFile);
            if (g_console_install == FALSE || g_nosplash == FALSE)
            {
                sprintf(msg_box_string, "%s%s%s", "Error extracting files\nUnable to create directory\n\n", "See the log file at:\n\n", sfx_log_file);
                MessageBox(hwnd, msg_box_string, NULL, MB_OK);
                SendMessage(hwnd, WM_DESTROY, 0, 0);
            }
        exit(22);
        }

    /* Create unix style work dir path */
    unix_style_work_dir_path = replace_sub_string(work_dir_path, DIRSEPSTR, "/");
    if (unix_style_work_dir_path == NULL)
    {
        log_message("Could not allocate memory for directory path\n");
        fclose(g_logFile);
        if (g_console_install == FALSE || g_nosplash == FALSE)
        {
            sprintf(msg_box_string, "%s%s%s", "Error extracting files\nUnable to allocate memory\n\n", "See the log file at:\n\n", sfx_log_file);
            MessageBox(hwnd, msg_box_string, NULL, MB_OK);
            SendMessage(hwnd, WM_DESTROY, 0, 0);
        }
        exit(23);
    }

    log_message("Extracting bundles ...\n");

    /* Process bundles */
    for (i = 0; i < P2_SFX_NUM_BUNDLES; i++)
    {
        char *installer_dir_path;

        installer_dir_path = allocate_string_buffer(strlen(work_dir_path) + strlen(bundles[i].path));
        if (installer_dir_path == NULL)
        {
            fclose(g_logFile);
            if (g_console_install == FALSE || g_nosplash == FALSE)
            {
                sprintf(msg_box_string, "%s%s%s", "Error extracting files\nUnable to allocate memory\n\n", "See the log file at:\n\n", sfx_log_file);
                MessageBox(hwnd, msg_box_string, NULL, MB_OK);
                SendMessage(hwnd, WM_DESTROY, 0, 0);
            }
            exit(24);
        }

        /* Create path to file */
        strcpycat(work_dir_path, bundles[i].path, installer_dir_path);
        for (j = 0; j < bundles[i].num_file_descs; j++)
        {
            P2_SFX_FILE_DESC *file_desc = &(bundles[i].files[j]);

            if (write_file_desc(file_desc, installer_dir_path))
            {
                fclose(g_logFile);
                if (g_console_install == FALSE || g_nosplash == FALSE)
                {
                    sprintf(msg_box_string, "%s%s%s", "Error extracting files\nPossibly check available disk space.\n\n", "See the log file at:\n\n", sfx_log_file);
                    MessageBox(hwnd, msg_box_string, NULL, MB_OK);
                    SendMessage(hwnd, WM_DESTROY, 0, 0);
                }
                exit(25);
            }
        }
        free(installer_dir_path);

        /* Process commands */
        for (j = 0; j < bundles[i].num_commands; j++)
        {
            char *setupexe;

            setupexe = NULL;

            /* Check to see if command contains setup */
            pch3 = strstr(bundles[i].commands[j], SETUP);

            if (pch3 != NULL)
            {
                if (g_console_install == FALSE)
                {          
                    setupexe = replace_sub_string(bundles[i].commands[j], SETUP, GUI_SETUP_COMMAND);
                }
                else
                {
                    setupexe = replace_sub_string(bundles[i].commands[j], SETUP, CONSOLE_SETUP_COMMAND);
                }
            }

            /* If the command contains setup.exe and there is no user path 
               or if it is any other command that doesn't contain setup */
            if ((setupexe != NULL && g_user_path == NULL) ||
                 setupexe == NULL)
            {
                char * tmp;
                int string_length;

                /* Substitute windows style path */
                if (setupexe == NULL)
                {
                    pch1 = replace_sub_string(bundles[i].commands[j], WINDOWS_BASE_PATH, work_dir_path);
                }
                else
                {
                    pch1 = replace_sub_string(setupexe, WINDOWS_BASE_PATH, work_dir_path);
                }

                if (pch1 == NULL)
                {
                    log_message("Error: Failed to allocate memory for windows path string\n");
                    fclose(g_logFile);
                    if (g_console_install == FALSE || g_nosplash == FALSE)
                    {
                        sprintf(msg_box_string, "%s%s%s", "Error extracting files\nUnable to allocate memory\n\n", "See the log file at:\n\n", sfx_log_file);
                        MessageBox(hwnd, msg_box_string, NULL, MB_OK);
                        SendMessage(hwnd, WM_DESTROY, 0, 0);
                    }
                    exit(26);
                }

                /* Substitute unix style path */
                pch2 = replace_sub_string(pch1, UNIX_BASE_PATH, unix_style_work_dir_path);
                free(pch1);

                if (pch2 == NULL)
                {
                    log_message("Error: Failed to allocate memory for unix path string\n");
                    fclose(g_logFile);
                    if (g_console_install == FALSE || g_nosplash == FALSE)
                    {
                        sprintf(msg_box_string, "%s%s%s", "Error extracting files\nUnable to allocate memory\n\n", "See the log file at:\n\n", sfx_log_file);
                        MessageBox(hwnd, msg_box_string, NULL, MB_OK);
                        SendMessage(hwnd, WM_DESTROY, 0, 0);
                    }
                    exit(27);
                }

                if (setupexe != NULL)
                {
                    char * install_once = INSTALL_ONCE;
                    char * install_log = INSTALL_LOG;
                    char * dash_data = DASH_DATA;

                    string_length = strlen(pch2) + strlen(install_once) + strlen(dash_data) + (4 * strlen("\"")) + 1;
                    string_length += strlen(install_log) + strlen(base_log_dir) + strlen(timestamp_log_dir) + 1;
                    tmp = allocate_string_buffer(string_length);
                    if (tmp == NULL)
                    {
                        log_message("Error: Failed to allocate memory for implicit arguments\n");
                        fclose(g_logFile);
                        if (g_console_install == FALSE || g_nosplash == FALSE)
                        {
                            sprintf(msg_box_string, "%s%s%s", "Error extracting files\nUnable to allocate memory\n\n", "See the log file at:\n\n", sfx_log_file);
                            MessageBox(hwnd, msg_box_string, NULL, MB_OK);
                            SendMessage(hwnd, WM_DESTROY, 0, 0);
                        }
                        exit(28);
                    }
                    strcpy(tmp, pch2);
                    strcat(tmp, install_once);
                    strcat(tmp, install_log);
                    strcat(tmp, "\"");
                    strcat(tmp, base_log_dir);
                    strcat(tmp, "\"");
                    strcat(tmp, dash_data);
                    strcat(tmp, "\"");
                    strcat(tmp, timestamp_log_dir);
                    strcat(tmp, "\"");

                    free(pch2); 
                    pch2 = tmp;
                }

                /* Create command with g_args */
                if (setupexe != NULL && g_args != NULL)
                {
                    string_length = strlen(pch2) + strlen(g_args) + 2;
                    tmp = allocate_string_buffer(string_length);

                    if (tmp == NULL)
                    {
                        log_message("Error: Failed to allocate memory for command with arguments");
                        fclose(g_logFile);
                        if (g_console_install == FALSE || g_nosplash == FALSE)
                        {
                            sprintf(msg_box_string, "%s%s%s", "Error extracting files\nUnable to allocate memory\n\n", "See the log file at:\n\n", sfx_log_file);
                            MessageBox(hwnd, msg_box_string, NULL, MB_OK);
                            SendMessage(hwnd, WM_DESTROY, 0, 0);
                        }
                        exit(29);
                    }
                    strcpy(tmp, pch2);
                    strcat(tmp, " ");
                    strcat(tmp, g_args);
                    free(pch2); 
                    pch2 = tmp;
                }

                if (setupexe != NULL)
                {
                    string_length = strlen(pch2) + strlen(VM_ARGS) + 
                                    strlen(VM_ARG_FILE) + strlen(timestamp_log_dir) + 3;
                    tmp = allocate_string_buffer(string_length);

                    if (tmp == NULL)
                    {
                        log_message("Error: Failed to allocate memory for vm args");
                        fclose(g_logFile);
                        if (g_console_install == FALSE || g_nosplash == FALSE)
                        {
                            sprintf(msg_box_string, "%s%s%s", "Error extracting files\nUnable to allocate memory\n\n", "See the log file at:\n\n", sfx_log_file);
                            MessageBox(hwnd, msg_box_string, NULL, MB_OK);
                            SendMessage(hwnd, WM_DESTROY, 0, 0);
                        }
                        exit(29);
                    }

                    strcpy(tmp, pch2);
                    strcat(tmp, VM_ARGS);
                    strcat(tmp, "\"");
                    strcat(tmp, timestamp_log_dir);
                    strcat(tmp, VM_ARG_FILE);
                    strcat(tmp, "\"");
                    free(pch2); 
                    pch2 = tmp;
                }

                /* Execute command */
                log_message("Executing command: %s\n", pch2);

                if (setupexe == NULL)
                {
                    /* All non-setup commands use CreateProcess */
                    if(start_process(pch2))
                    {
                        log_message("Error: Failed to execute %s\n", pch2);
                        fclose(g_logFile);
                        if (g_console_install == FALSE || g_nosplash == FALSE)
                        {
                            sprintf(msg_box_string, "%s%s%s", "Error extracting files\nCommand failure\n\n", "See the log file at:\n\n", sfx_log_file);
                            MessageBox(hwnd, msg_box_string, NULL, MB_OK);
                            SendMessage(hwnd, WM_DESTROY, 0, 0);
                        }
                        exit(30);
                    }
                }
                else
                {
                    /* Split the command into a "command" and "argument" format */
                    char * exestring = allocate_string_buffer(strlen(pch2));
                    char * cmdargs = allocate_string_buffer(strlen(pch2));
                    HINSTANCE return_value;

                    tmp = strstr(pch2, ".exe");
                    tmp += (strlen(".exe") + 1);
                    strncpy(exestring, pch2, strlen(pch2) - strlen(tmp));
                    exestring[strlen(pch2) - strlen(tmp)] = 0;
                    strcpy(cmdargs, tmp);

                    log_message("Installer command = %s\n", exestring);
                    log_message("Installer arguments = %s\n", cmdargs);

                    return_value = ShellExecute(NULL, "open", exestring, cmdargs, NULL, SW_SHOWNORMAL);

                    if ((int)return_value <= 32)
                    {
                        log_message("Error: ShellExecute returned a value of %d\n", (int)return_value);
                        fclose(g_logFile);
                        if (g_console_install == FALSE || g_nosplash == FALSE)
                        {
                            sprintf(msg_box_string, "%s%s%s", "Error extracting files\nCommand failure\n\n", "See the log file at:\n\n", sfx_log_file);
                            MessageBox(hwnd, msg_box_string, NULL, MB_OK);
                            SendMessage(hwnd, WM_DESTROY, 0, 0);
                        }
                        exit(31);
                    }
                    
                }

                free(pch2);
            }
        }
    }

    if (g_console_install == FALSE || g_nosplash == FALSE)
    {
        SendMessage(hwnd, WM_DESTROY, 0, 0);
    } 

    return 0;
}
Exemplo n.º 11
0
/** Build the chroot at the path **/
bool WorkerBee::build_chroot(const std::string &path, uid_t user, gid_t group, string_set &executables, string_set &extra_dirs) {
  // Make the root path
  make_path(strdup(path.c_str()));
  string_set already_copied;
  std::string full_path;
  
  // The base directories  
  string_set base_dirs;
  base_dirs.insert("bin");
  base_dirs.insert("usr");
  base_dirs.insert("var");
  base_dirs.insert("lib");
  base_dirs.insert("home");
  base_dirs.insert("etc");
  
  // Add the extra directories requested
  for (string_set::iterator dir = extra_dirs.begin(); dir != extra_dirs.end(); ++dir) base_dirs.insert(dir->c_str());
  
  for (string_set::iterator dir = base_dirs.begin(); dir != base_dirs.end(); ++dir) {
    if ((*dir->c_str()) == '/') full_path = path + *dir; else full_path = path + '/' + *dir;
    
    // Make the paths
    make_path(full_path.c_str());
  }
  
  // Build the root libraries
  for (string_set::iterator executable = executables.begin(); executable != executables.end(); ++executable) {
    // If we are pointed at an absolute path to a binary
    // then find the linked libraries of the executable
    // If it's not found, then find it, then look up the libraries
    std::string res_bin;
    if (abs_path(*executable))
      res_bin = *executable;
    else {
      res_bin = find_binary(*executable);
    }
    
    // The libraries for the resolved binary 
    bee_files_set *s_libs = libs_for(res_bin);
    
    // collect the libraries and copy them to the full path of the chroot
    for (bee_files_set::iterator bf = s_libs->begin(); bf != s_libs->end(); ++bf) {
      BeeFile bee = *bf;
      std::string s (bee.file_path());
      
      // Don't copy if the file is already copied
      if (already_copied.count(s)) {
      } else {
        // If it is a symlink, then make a symlink, otherwise copy the file
        // If the library starts with a '/' then don't add one, otherwise, do
        // i.e. if libs/hi.so.1 turns into full_path/libs/hi.so.1 otherwise libs.so.1 turns into full_path/libs.so.1
        if (s.c_str()[0] == '/') full_path = path + s.c_str(); else full_path = path + '/' + s.c_str();
        
        if (bee.is_link()) {
          // make symlink
          make_path(dirname(strdup(full_path.c_str()))); 
          if (symlink(bee.sym_origin().c_str(), full_path.c_str())) {
            fprintf(stderr, "Could not make a symlink: %s to %s because %s\n", bee.sym_origin().c_str(), full_path.c_str(), strerror(errno));
          }
        } else {
          // Copy the file (recursively)
          cp_r(s, full_path);
        }
        // Change the permissions to match the original file
        struct stat file_stats = bee.file_stats();
        mode_t mode = file_stats.st_mode;
  			
  			if (chown(full_path.c_str(), user, group) != 0) {
  			  fprintf(stderr, "Could not change owner of '%s' to %i\n", full_path.c_str(), user);
  			}
  			
        if (chmod(full_path.c_str(), mode) != 0) {
          fprintf(stderr, "Could not change permissions to '%s' %o\n", full_path.c_str(), mode);
        }
        // Add it to the already_copied set and move on
        already_copied.insert(s);
      }
    }
    
    // Copy the executables and make them executable
    std::string bin_path = path + '/' + res_bin;
    cp_r(res_bin.c_str(), bin_path.c_str());
    
    if (chown(bin_path.c_str(), user, group) != 0) {
		  fprintf(stderr, "Could not change owner of '%s' to %i\n", bin_path.c_str(), user);
		}
		
    if (chmod(bin_path.c_str(), S_IREAD|S_IEXEC|S_IXGRP|S_IRGRP|S_IWRITE)) {
      fprintf(stderr, "Could not change permissions to '%s' make it executable\n", bin_path.c_str());
    }
		
  }
  return true;
}
Exemplo n.º 12
0
/******************************************************************************
* WinMain: Entry point
*
* @param hInstance
* @param hPrevInstance
* @param lpCmdLine
* @param nCmdShow
* 
* @return 
******************************************************************************/
int WINAPI 
WinMain(HINSTANCE hInstance, 
                  HINSTANCE hPrevInstance,
                  LPSTR lpCmdLine, 
                  int nCmdShow)
{
    int argc = 0;
    char **argv;
    int i;
    char *nosplash_string = "-nosplash ";
    int arg_length = 0;
    char filename[MAX_PATH];
    char time[MAX_PATH];
    SYSTEMTIME sys_time;
    DWORD return_value;

    /* Get command line args */

    if(*lpCmdLine != 0)
    {
        argc = __argc;
        argv = __argv;
    }

    for (i = 1; i < argc; i++)
    {
        if (strstr(argv[i], "-?") != NULL ||
            strstr(argv[i], "-help") != NULL ||
            strstr(argv[i], "--help") != NULL ||
            strstr(argv[i], "-h") != NULL)
        {
            MessageBox(NULL, helpString, "Help", MB_OK);
            exit(0);
        }
    }

    /* Get user home directory */
    return_value = GetEnvironmentVariable("userprofile", home_dir_path, MAX_PATH);

    if (return_value == 0)
    {
        MessageBox(NULL, "Extraction error: could not obtain user directory", NULL, MB_OK);
        exit(1);
    }

    /* Create log file */
    GetSystemTime(&sys_time);
    return_value = GetTimeFormat(MAKELCID(LANG_USER_DEFAULT, SORT_DEFAULT), 0, NULL, NULL, time, MAX_PATH);
    if (return_value == 0) 
    {
        MessageBox(NULL, "Extraction error: Invalid timestamp information received from the OS\n", NULL, MB_OK);
        exit(2);
    }

    strcpy(base_log_dir, home_dir_path);
    strcat(base_log_dir, DIRSEPSTR);
    strcat(base_log_dir, LOG_DIRECTORY);

    strcpy(timestamp_log_dir, base_log_dir);

    sprintf(timestamp, "%04d%02d%02d%02d%02d%02d", sys_time.wYear,sys_time.wMonth,sys_time.wDay,sys_time.wHour,sys_time.wMinute,sys_time.wSecond);
    strcat(timestamp_log_dir, DIRSEPSTR);
    strcat(timestamp_log_dir, LOGS_DIR);
    strcat(timestamp_log_dir, DIRSEPSTR);
    strcat(timestamp_log_dir, timestamp);

    if (!file_exists(timestamp_log_dir))
    {
        if (make_path(timestamp_log_dir, 0777) != 0)
        {
            sprintf(msg_box_string, "Extraction error: could not create log directory\n\n%s", timestamp_log_dir);
            MessageBox(NULL, msg_box_string, NULL, MB_OK);
            exit(2);
        }
    }

    strcpy(sfx_log_file, timestamp_log_dir);
    strcat(sfx_log_file, DIRSEPSTR);

    strcat(sfx_log_file, LOG_FILE);
    g_logFile = fopen(sfx_log_file, "a+");

    if(g_logFile == NULL || ferror(g_logFile))
    {
        sprintf(msg_box_string, "Extraction error: could not create log file\n\n%s", sfx_log_file);
        MessageBox(NULL, msg_box_string, NULL, MB_OK);
        exit(3);
    }

    /* Logging is available from this point forward */

    /* Log timestamp */
    log_message("------------------------------------\n");
    log_message("Installation timestamp: %d-%d-%d, %s\n",
                sys_time.wYear, sys_time.wMonth, sys_time.wDay, time);


    log_message("Raw command line: %s\n", lpCmdLine);
    
    return_value = GetModuleFileName(NULL, filename, MAX_PATH);

    if (return_value == 0)
    {
        char *errorString;

        FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_ALLOCATE_BUFFER,
                      NULL,
                      GetLastError(),
                      0,
                      errorString,
                      64,
                      NULL);
        log_message("Error getting module information: %s\n", errorString);
        fclose(g_logFile);
        sprintf(msg_box_string, "Extraction error. See the following file\n\n%s", sfx_log_file);
        MessageBox(NULL, msg_box_string, NULL, MB_OK);
        exit(4);
    }

    for (i = 0; i < argc; i++)
    {
        if (strcmp(argv[i], "-x") == 0)
        {
            if (i + 1 < argc)
            {
                g_user_path = argv[i + 1];
            }
            else
            {
                log_message("-x option requires a path to be provided\n");
                log_message("%s -x <path>\n", filename);
                fclose(g_logFile);
                sprintf(msg_box_string, "Extraction error. See the following file\n\n%s", sfx_log_file);
                MessageBox(NULL, msg_box_string, NULL, MB_OK);
                exit(5);
            }
            /* Uncomment this if no splash is desired during -x install */
            /* g_nosplash = TRUE; */
            break;
        }
    }

    /* Check to see if user used -x */
    if (g_user_path != NULL && strlen(g_user_path) <= MAX_PATH)
    {
        strcpy(temp_dir_path, g_user_path);
        if (!file_exists (g_user_path))
            if (make_path (g_user_path, 0777) != 0)
            {
                log_message("Could not create directory: %s\n", g_user_path);
                fclose(g_logFile);
                sprintf(msg_box_string, "Extraction error. See the following file\n\n%s", sfx_log_file);
                MessageBox(NULL, msg_box_string, NULL, MB_OK);
                exit(6);
            }
    }
    else if (g_user_path != NULL)
    {
        /* We only accept paths that are MAX_PATH in length */
        log_message("Error: path provided with -x option is invalid \"%s\"\n", g_user_path);
        log_message("Note: path cannot exceed %d characters\n", MAX_PATH);
        fclose(g_logFile);
        sprintf(msg_box_string, "Extraction error. See the following file\n\n%s", sfx_log_file);
        MessageBox(NULL, msg_box_string, NULL, MB_OK);
        exit(7);
    }
    else
    {
        int ret_val;

        ret_val = GetEnvironmentVariable(TEMP_PATH_ENV, temp_dir_path, MAX_PATH);

        /* Find the directory to the tmp directory */
        if (ret_val == 0 || ret_val > MAX_PATH)
        {
            if (GetTempPath (MAX_PATH, temp_dir_path) == 0)
            {
                log_message("Error: Could not find temporary directory to extract files\n");
                fclose(g_logFile);
                sprintf(msg_box_string, "Extraction error. See the following file\n\n%s", sfx_log_file);
                MessageBox(NULL, msg_box_string, NULL, MB_OK);
                exit(8);
            }
        }
        /* The user supplied a path via environment variable */
        else
        {
            g_env_var_path = temp_dir_path;
            /* temp_dir_path already contains the path; no need to copy it */
            log_message("Temporary path obtained from \"%s\" environment variable: \"%s\"\n", TEMP_PATH_ENV, temp_dir_path);
        }
    }

    /* Check to see if there are arguments to pass to setup; only valid
       if the user didn't specify an installation path (if they 
       specified a path that means we won't be calling setup) */
    if (argc > 0 && g_user_path == NULL)
    {
        short nosplash_set = FALSE;
        short installsilent_set = FALSE;
        short installconsole_set = FALSE;
        short installlocation_set = FALSE;

        /* Allocate memory for argument string */
        for (i = 0; i < argc; i++)
        {
            arg_length += strlen(argv[i]);

            /* Add one more for the space in between args*/
            arg_length++;
        }

        /* Allocate space for an extra -nosplash and extra space if -console is
           used instead of -install.console or -install.silent */
        arg_length += strlen(nosplash_string) + strlen(".console") + strlen(".location");

        g_args = allocate_string_buffer(arg_length);

        if (g_args == NULL)
        {
            log_message("Error: Couldn't allocate memory for arguments: %d\n", arg_length);
            fclose(g_logFile);
            sprintf(msg_box_string, "Extraction error. See the following file\n\n%s", sfx_log_file);
            MessageBox(NULL, msg_box_string, NULL, MB_OK);
            exit(9);
        }

        /* Add the arguments to the g_args string */
        for (i = 1; i < argc; i++)
        {
            log_message("argv[%d] = %s\n", i, argv[i]);

            if (((strstr(argv[i], "-install.silent") != NULL) ||
                  (strstr(argv[i], "-silent") != NULL)) &&
                installsilent_set == FALSE &&
                installconsole_set == FALSE)
            {
                g_console_install = TRUE;
                installsilent_set = TRUE;
                if (nosplash_set == FALSE)
                {
                    nosplash_set = TRUE;
                    strcat(g_args, nosplash_string);
                }
                strcat(g_args, "-install.silent ");
            }
            else if (((strstr(argv[i], "-install.console") != NULL) || 
                      (strstr(argv[i], "-console") != NULL)) &&
                     installconsole_set == FALSE &&
                     installsilent_set == FALSE)
            {
                g_console_install = TRUE;
                installconsole_set = TRUE;
                if (nosplash_set == FALSE)
                {
                    nosplash_set = TRUE;
                    strcat(g_args, nosplash_string);
                }
                strcat(g_args, "-install.console ");
            }
            else if (((strstr(argv[i], "-install.location") != NULL) || 
                      (strstr(argv[i], "-location") != NULL))&&
                     installlocation_set == FALSE)
            {
                char * pch = NULL;

                pch = strtok(argv[i], "=");
                if (pch != NULL)
                {
                    pch = strtok(NULL, "=");
                    if (pch != NULL)
                    {
                        installlocation_set = TRUE;
                        strcat(g_args, "-install.location=");
                        strcat(g_args, pch);
                        strcat(g_args, " ");
                    }
                }
                if (pch == NULL)
                {
                    strcat(g_args, argv[i]);
                    strcat(g_args, " ");
                }
            }
            else if (strstr(argv[i], "-nosplash") != NULL &&
                     nosplash_set == FALSE)
            {
                nosplash_set = TRUE;
                g_nosplash = TRUE;
                strcat(g_args, nosplash_string);
            }
            else
            {
                strcat(g_args, argv[i]);
                strcat(g_args, " ");
            }
        }
        log_message("arguments list: %s\n", g_args);
    }
    
    return (extract_files_app(hInstance, hPrevInstance, nCmdShow));
}
Exemplo n.º 13
0
void op_ospath()
{
 /* Stack:

     |================================|=============================|
     |            BEFORE              |           AFTER             |
     |================================|=============================|
 top |  Key                           | Information                 |
     |--------------------------------|-----------------------------| 
     |  Pathname string               |                             |
     |================================|=============================|

 Key values:           Action                             Returns
     0  OS_PATHNAME    Test if valid pathname             True/False
     1  OS_FILENAME    Test if valid filename             True/False
                       or directory file record name
     2  OS_EXISTS      Test if file exists                True/False
     3  OS_UNIQUE      Make a unique file name            Name
     4  OS_FULLPATH    Return full pathname               Name
     5  OS_DELETE      Delete file                        Success/Failure
     6  OS_CWD         Get current working directory      Pathname
     7  OS_DTM         Return date/time modified          DTM value
     8  OS_FLUSH_CACHE Flush DH file cache                -
     9  OS_CD          Change working directory           Success/Failure
    10  OS_MAPPED_NAME Map a directory file name          Mapped name
    11  OS_OPEN        Check if path is an open file      True/False
    12  OS_DIR         Return content of directory        Filenames
    13  OS_MKDIR       Make a directory                   True/False
    14  OS_MKPATH      Make a directory path              True/False

 Pathnames with lengths outside the range 1 to MAX_PATHNAME_LEN return
 0 regardless of the action key.

 */

 long int status = 0;
 short int key;
 DESCRIPTOR * descr;
 char path[MAX_PATHNAME_LEN+1];
 short int path_len;
 char name[MAX_PATHNAME_LEN+1];
 char * p;
 char * q;
 STRING_CHUNK * head;
 int file_id;
 FILE_ENTRY * fptr;
 struct stat stat_buff;
 DIR * dfu;
 struct dirent * dp;
 long int n;

 /* Get action key */

 descr = e_stack - 1;
 GetInt(descr);
 key = (short int)(descr->data.value);
 k_pop(1);

 /* Get pathname */

 descr = e_stack - 1;
 path_len = k_get_c_string(descr, path, MAX_PATHNAME_LEN);
 k_dismiss();
 if (path_len < 0) goto set_status;
#ifdef CASE_INSENSITIVE_FILE_SYSTEM
 UpperCaseString(path);
#endif

 switch(key)
  {
   case OS_PATHNAME:     /* Test if valid pathname */
      p = path;
      if (*p == '/') p++;

      do {
          q = strchr(p, '/');
          if (q != NULL) *q = '\0';
          if (!valid_name(p)) goto set_status;
          p = q + 1;
         } while(q != NULL);
      status = 1;


      break;

   case OS_FILENAME:     /* Test if valid pathname */
      status = (long int)valid_name(path);
      break;

   case OS_EXISTS:     /* Test if file exists */
      status = !access(path, 0);
      break;

   case OS_UNIQUE:  /* Make unique file name. Path variable holds directory name */
      n = (time(NULL) * 10) & 0xFFFFFFFL;
      do {
          sprintf(name, "%s\\D%07lX", path, n);
          n--;
         } while(!access(name, 0));
      sprintf(name, "D%07lX", n);
      k_put_c_string(name, e_stack);
      e_stack++;
      goto exit_op_pathinfo;

   case OS_FULLPATH:     /* Expand path to full OS pathname */
      fullpath(name, path);
      k_put_c_string(name, e_stack);
      e_stack++;
      goto exit_op_pathinfo;

   case OS_DELETE:
      flush_dh_cache();
      status = (long int)delete_path(path);
      break;

   case OS_CWD:
      (void)getcwd(name, MAX_PATHNAME_LEN);
#ifdef CASE_INSENSITIVE_FILE_SYSTEM
      UpperCaseString(name);
#endif
      k_put_c_string(name, e_stack);
      e_stack++;
      goto exit_op_pathinfo;

   case OS_DTM:
      if (stat(path, &stat_buff) == 0) status = stat_buff.st_mtime;
      break;

   case OS_FLUSH_CACHE:
      flush_dh_cache();
      break;

   case OS_CD:
      status = attach(path);
      break;

   case OS_MAPPED_NAME:    /* Map a directory file record name */
      (void)map_t1_id(path, strlen(path), name);
      k_put_c_string(name, e_stack);
      e_stack++;
      goto exit_op_pathinfo;

   case OS_OPEN:
      fullpath(name, path);
      for(file_id = 1; file_id <= sysseg->used_files; file_id++)
       {
        fptr = FPtr(file_id);
        if ((fptr->ref_ct != 0)
          && (strcmp((char *)(fptr->pathname), name) == 0))
         {
          status = TRUE;
          break;
         }
       }
      break;

   case OS_DIR:
      head = NULL;
      ts_init(&head, 1024);
      if ((dfu = opendir(path)) != NULL)
       {
        if (path[path_len-1] == DS) path[path_len-1] = '\0';

        while((dp = readdir(dfu)) != NULL)
         {
          if (strcmp(dp->d_name, ".") == 0) continue;
          if (strcmp(dp->d_name, "..") == 0) continue;

          sprintf(name, "%s%c%s", path, DS, dp->d_name);
          if (stat(name, &stat_buff)) continue;

          strcpy(name+1, dp->d_name);
#ifdef CASE_INSENSITIVE_FILE_SYSTEM
          UpperCaseString(name+1);
#endif
          if (stat_buff.st_mode & S_IFDIR)
           {
            name[0] = 'D';
            if (head != NULL) ts_copy_byte(FIELD_MARK);
            ts_copy_c_string(name);
           }
          else if (stat_buff.st_mode & S_IFREG)
           {
            name[0] = 'F';
            if (head != NULL) ts_copy_byte(FIELD_MARK);
            ts_copy_c_string(name);
           }
         }

        closedir(dfu);
       }
      ts_terminate();
      InitDescr(e_stack, STRING);
      (e_stack++)->data.str.saddr = head;
      goto exit_op_pathinfo;      

   case OS_MKDIR:
      status = !MakeDirectory(path);
      break;

   case OS_MKPATH:
      status = make_path(path);
      break;
       
   default:
      k_error(sysmsg(1010));
  }

set_status:

 /* Set status value on stack */

 InitDescr(e_stack, INTEGER);
 (e_stack++)->data.value = status;

exit_op_pathinfo:
 return;
}
Exemplo n.º 14
0
/**
 * Update all the MetaData and art on an "item-changed" event
 **/
void MetaPanel::update( input_item_t *p_item )
{
    if( !p_item )
    {
        clear();
        return;
    }

    /* Don't update if you are in edit mode */
    if( b_inEditMode ) return;
    p_input = p_item;

    char *psz_meta;
#define UPDATE_META( meta, widget ) {                                   \
    psz_meta = input_item_Get##meta( p_item );                          \
    widget->setText( !EMPTY_STR( psz_meta ) ? qfu( psz_meta ) : "" );   \
    free( psz_meta ); }

#define UPDATE_META_INT( meta, widget ) {           \
    psz_meta = input_item_Get##meta( p_item );      \
    if( !EMPTY_STR( psz_meta ) )                    \
        widget->setValue( atoi( psz_meta ) ); }     \
    free( psz_meta );

    /* Name / Title */
    psz_meta = input_item_GetTitleFbName( p_item );
    if( psz_meta )
    {
        title_text->setText( qfu( psz_meta ) );
        free( psz_meta );
    }
    else
        title_text->setText( "" );

    /* URL / URI */
    psz_meta = input_item_GetURI( p_item );
    if( !EMPTY_STR( psz_meta ) )
         emit uriSet( qfu( psz_meta ) );
    free( psz_meta );

    /* Other classic though */
    UPDATE_META( Artist, artist_text );
    UPDATE_META( Genre, genre_text );
    UPDATE_META( Copyright, copyright_text );
    UPDATE_META( Album, collection_text );
    UPDATE_META( Description, description_text );
    UPDATE_META( Language, language_text );
    UPDATE_META( NowPlaying, nowplaying_text );
    UPDATE_META( Publisher, publisher_text );
    UPDATE_META( EncodedBy, encodedby_text );

    UPDATE_META( Date, date_text );

    QString trackposition( "%1/%2" );
    psz_meta = input_item_GetTrackNum( p_item );
    trackposition = trackposition.arg( psz_meta );
    free( psz_meta );
    psz_meta = input_item_GetTrackTotal( p_item );
    trackposition = trackposition.arg( psz_meta );
    free( psz_meta );
    tracknumber_text->setText( trackposition );

//    UPDATE_META( Setting, setting_text );
//    UPDATE_META_INT( Rating, rating_text );

    /* URL */
    psz_meta = input_item_GetURL( p_item );
    if( !EMPTY_STR( psz_meta ) )
    {
        QString newURL = qfu(psz_meta);
        if( currentURL != newURL )
        {
            currentURL = newURL;
            lblURL->setText( "<a href='" + currentURL + "'>" +
                             currentURL.remove( QRegExp( ".*://") ) + "</a>" );
        }
    }
    free( psz_meta );
#undef UPDATE_META_INT
#undef UPDATE_META

    // If a artURL is available as a local file, directly display it !

    QString file;
    char *psz_art = input_item_GetArtURL( p_item );
    if( psz_art )
    {
        char *psz = make_path( psz_art );
        free( psz_art );
        file = qfu( psz );
        free( psz );
    }

    art_cover->showArtUpdate( file );
    art_cover->setItem( p_item );
}
Exemplo n.º 15
0
hid_device * HID_API_EXPORT hid_open_path(const char *path)
{
  	int i;
	hid_device *dev = NULL;
	CFIndex num_devices;
	
	dev = new_hid_device();

	/* Set up the HID Manager if it hasn't been done */
	if (hid_init() < 0)
		return NULL;

	/* give the IOHIDManager a chance to update itself */
	process_pending_events();

	CFSetRef device_set = IOHIDManagerCopyDevices(hid_mgr);
	
	num_devices = CFSetGetCount(device_set);
	IOHIDDeviceRef *device_array = calloc(num_devices, sizeof(IOHIDDeviceRef));
	CFSetGetValues(device_set, (const void **) device_array);	
	for (i = 0; i < num_devices; i++) {
		char cbuf[BUF_LEN];
		size_t len;
		IOHIDDeviceRef os_dev = device_array[i];
		
		len = make_path(os_dev, cbuf, sizeof(cbuf));
		if (!strcmp(cbuf, path)) {
			// Matched Paths. Open this Device.
			IOReturn ret = IOHIDDeviceOpen(os_dev, kIOHIDOptionsTypeNone);
			if (ret == kIOReturnSuccess) {
				char str[32];

				free(device_array);
				CFRelease(device_set);
				dev->device_handle = os_dev;
				
				/* Create the buffers for receiving data */
				dev->max_input_report_len = (CFIndex) get_max_report_length(os_dev);
				dev->input_report_buf = calloc(dev->max_input_report_len, sizeof(uint8_t));
				
				/* Create the Run Loop Mode for this device.
				   printing the reference seems to work. */
				sprintf(str, "HIDAPI_%p", (void*)os_dev);
				dev->run_loop_mode = 
					CFStringCreateWithCString(NULL, str, kCFStringEncodingASCII);
				
				/* Attach the device to a Run Loop */
				IOHIDDeviceRegisterInputReportCallback(
					os_dev, dev->input_report_buf, dev->max_input_report_len,
					&hid_report_callback, dev);
				IOHIDManagerRegisterDeviceRemovalCallback(hid_mgr, hid_device_removal_callback, NULL);
				
				/* Start the read thread */
				pthread_create(&dev->thread, NULL, read_thread, dev);

				/* Wait here for the read thread to be initialized. */
				pthread_barrier_wait(&dev->barrier);
				
				return dev;
			}
			else {
				goto return_error;
			}
		}
	}

return_error:
	free(device_array);
	CFRelease(device_set);
	free_hid_device(dev);
	return NULL;
}
Exemplo n.º 16
0
bool dh_create_file(
   char path[],
   short int group_size,   /* -ve sets default */
   long int min_modulus,   /* -ve sets default */
   long int big_rec_size,  /* -ve sets default */
   short int merge_load,   /* -ve sets default */
   short int split_load,   /* -ve sets default */
   unsigned long int flags,
   short int version)      /* -ve sets default */
{
 bool status = FALSE;
 char primary_subfile[MAX_PATHNAME_LEN+1];
 char overflow_subfile[MAX_PATHNAME_LEN+1];
 bool primary_subfile_created = FALSE;
 bool overflow_subfile_created = FALSE;
 OSFILE fu = INVALID_FILE_HANDLE;
 struct DH_HEADER header;
 int header_bytes;
 int group_size_bytes;
 long int group;
 double file_size;

 dh_err = 0;
 process.os_error = 0;

 /* Validate arguments */

 if (group_size < 0)
  {
   group_size = DEFAULT_GROUP_SIZE;
  }
 else if ((group_size < 1) || (group_size > MAX_GROUP_SIZE))
  {
   dh_err = DHE_ILLEGAL_GROUP_SIZE;
   goto exit_dh_create_file;
  }
 group_size_bytes = group_size * DH_GROUP_MULTIPLIER;

 if (min_modulus < 1)
  {
   min_modulus = DEFAULT_MIN_MODULUS;
  }
 else if (min_modulus < 1)
  {
   dh_err = DHE_ILLEGAL_MIN_MODULUS;
   goto exit_dh_create_file;
  }

 if (big_rec_size < 0)
  {
   big_rec_size = (long)((group_size_bytes) * 0.8);
  }
 else if (big_rec_size > group_size_bytes - BLOCK_HEADER_SIZE)
  {
   big_rec_size = group_size_bytes - BLOCK_HEADER_SIZE;
  }

 if (merge_load < 0)
  {
   merge_load = DEFAULT_MERGE_LOAD;
  }
 else if (merge_load > 99)
  {
   dh_err = DHE_ILLEGAL_MERGE_LOAD;
   goto exit_dh_create_file;
  }

 if (split_load < 0)
  {
   split_load = DEFAULT_SPLIT_LOAD;
  }
 else if (split_load <= merge_load)
  {
   dh_err = DHE_ILLEGAL_SPLIT_LOAD;
   goto exit_dh_create_file;
  }

 /* !!FILE_VERSION!! */
 if (version < 0)
  {
   version = DH_VERSION;
  }
 else if (version > DH_VERSION)
  {
   dh_err = DHE_VERSION;
   goto exit_dh_create_file;
  }

 header_bytes = DHHeaderSize(version, group_size_bytes);

 if (version < 2)
  {
   /* Check if file exceeds 2Gb */

   file_size = (((double)group_size_bytes) * min_modulus) + header_bytes;
   if (file_size > (unsigned long)0x80000000L)
    {
     dh_err = DHE_SIZE;
     goto exit_dh_create_file;
    }
  }

 /* Check if directory to hold subfiles exists */

 if (access(path, 0) == 0)
  {
   dh_err = DHE_FILE_EXISTS;
   goto exit_dh_create_file;
  }

 /* Create directory */

 if (!make_path(path))
  {
   dh_err = DHE_CREATE_DIR_ERR;
   process.os_error = OSError;
   goto exit_dh_create_file;
  }

 /* Create primary subfile */

 sprintf(primary_subfile, "%s%c~0", path, DS);
 fu = dio_open(primary_subfile, DIO_NEW);

 if (!ValidFileHandle(fu))
  {
   dh_err = DHE_CREATE0_ERR; 
   process.os_error = OSError;
   goto exit_dh_create_file;   
  }

 primary_subfile_created = TRUE;

 /* Write primary subfile header */

 memset((char *)&header, 0, sizeof(header));
 header.magic = DH_PRIMARY;
 header.file_version = (u_char)version;
 header.group_size = group_size_bytes;
 header.flags = (unsigned short int)(flags & DHF_CREATE);
 header.params.modulus = min_modulus;
 header.params.min_modulus = min_modulus;
 header.params.big_rec_size = big_rec_size;
 header.params.split_load = split_load;
 header.params.merge_load = merge_load;
 header.params.load_bytes = 0;
 header.params.extended_load_bytes = 0;
 header.params.free_chain = 0;
 header.creation_timestamp = qmtime();
 header.record_count = 1;   /* Actually zero, see dh_fmt.h */

 /* Calculate mod_value as next power of two >= min_modulus */

 for (header.params.mod_value = 1;
      header.params.mod_value < min_modulus;
      header.params.mod_value <<= 1) {}

 memset(dh_buffer, 0, header_bytes);
 memcpy(dh_buffer, (char *)(&header), sizeof(header));
 if (Write(fu, dh_buffer, header_bytes) < 0)
  {
   dh_err = DHE_PSFH_WRITE_ERROR;
   process.os_error = OSError;
   goto exit_dh_create_file;
  }

 /* Initialise data groups */

 memset(dh_buffer, 0, group_size_bytes);
 ((DH_BLOCK *)(dh_buffer))->used_bytes = BLOCK_HEADER_SIZE;
 ((DH_BLOCK *)(dh_buffer))->block_type = DHT_DATA;

 for (group = 1; group <= min_modulus; group++)
  {
   if (Write(fu, dh_buffer, group_size_bytes) < 0)
    {
     dh_err = DHE_INIT_DATA_ERROR;
     process.os_error = OSError;
     goto exit_dh_create_file;
    }
  }

 CloseFile(fu);
 fu = INVALID_FILE_HANDLE;

 /* Create overflow subfile */

 sprintf(overflow_subfile, "%s%c~1", path, DS);
 fu = dio_open(overflow_subfile, DIO_NEW);

 if (!ValidFileHandle(fu))
  {
   dh_err = DHE_CREATE1_ERR; 
   process.os_error = OSError;
   goto exit_dh_create_file;
  }

 /* Write overflow subfile header */

 memset((char *)(&header), 0 , sizeof(header));
 header.magic = DH_OVERFLOW;
 header.group_size = group_size_bytes;

 memset(dh_buffer, 0, header_bytes);
 memcpy(dh_buffer, (char *)(&header), sizeof(header));

 if (Write(fu, dh_buffer, header_bytes) < 0)
  {
   dh_err = DHE_OSFH_WRITE_ERROR;
   process.os_error = OSError;
   goto exit_dh_create_file;
  }

 CloseFile(fu);
 fu = INVALID_FILE_HANDLE;

 status = TRUE;

exit_dh_create_file:
 if (status == FALSE)
  {
   if (ValidFileHandle(fu)) CloseFile(fu);

   if (primary_subfile_created) remove(primary_subfile);

   if (overflow_subfile_created) remove(overflow_subfile);
  }

 return status;
}
Exemplo n.º 17
0
static void construct_digraph(lua_State* L, pgfgd_SyntacticDigraph* d)
{
  d->internals = (pgfgd_SyntacticDigraph_internals*) calloc(1, sizeof(pgfgd_SyntacticDigraph_internals));
  d->internals->state = L;
  
  // Create the options table:
  d->options = make_option_table(L, GRAPH_INDEX, 0);

  // Create the vertex table
  init_vertex_array(&d->vertices, lua_rawlen(L, VERTICES_INDEX));

  // Create the vertices
  int i;
  for (i=0; i<d->vertices.length; i++) {
    pgfgd_Vertex* v  = (pgfgd_Vertex*) calloc(1, sizeof(pgfgd_Vertex));

    // Push the vertex onto the Lua stack:
    lua_rawgeti(L, VERTICES_INDEX, i+1);
    
    // Fill v with information:
    v->name  = make_string_from(L, "name");
    v->shape = make_string_from(L, "shape");
    v->kind  = make_string_from(L, "kind");
    
    // Options:
    v->options = make_option_table(L, VERTICES_INDEX, i+1);
    
    // Index:
    v->array_index = i;
    
    // Setup pos field
    lua_getfield(L, -1, "pos");
    make_coordinate(L, &v->pos);
    lua_pop(L, 1);

    // Setup path array:
    lua_getfield(L, -1, "path");
    v->path = make_path(L);
    lua_pop(L, 1); 

    // Pop the vertex
    lua_pop(L, 1);
    
    d->vertices.array[i] = v;
  }

  // Construct the edges:
  init_edge_array(&d->syntactic_edges, lua_rawlen(L, EDGES_INDEX));

  int edge_index;
  for (edge_index = 0; edge_index < d->syntactic_edges.length; edge_index++) {
    pgfgd_Edge* e = (pgfgd_Edge*) calloc(1, sizeof(pgfgd_Edge));

    lua_rawgeti(L, EDGES_INDEX, edge_index+1);
    
    e->direction = make_string_from(L, "direction");      
    e->options = make_option_table(L, EDGES_INDEX, edge_index+1);
    
    // Index:
    e->array_index = edge_index;

    // Compute the tail vertex index:
    lua_getfield(L, -1, "tail");
    lua_gettable(L, VERTICES_INDEX);
    e->tail = d->vertices.array[lua_tointeger(L, -1) - 1];
    lua_pop(L, 1);

    lua_getfield(L, -1, "head");
    lua_gettable(L, VERTICES_INDEX);
    e->head = d->vertices.array[lua_tointeger(L, -1) - 1];
    lua_pop(L, 1);
    
    // Fill path:
    e->path = make_empty_path(L);
    e->path->length = -1; // Means that a default path should be created.
    
    // Pop the edge form the Lua stack:
    lua_pop(L, 1);
      
    d->syntactic_edges.array[edge_index] = e;
  }
}
Exemplo n.º 18
0
/**
   The real implementation of wildcard expansion is in this
   function. Other functions are just wrappers around this one.

   This function traverses the relevant directory tree looking for
   matches, and recurses when needed to handle wildcrards spanning
   multiple components and recursive wildcards.

   Because this function calls itself recursively with substrings,
   it's important that the parameters be raw pointers instead of wcstring,
   which would be too expensive to construct for all substrings.
 */
static int wildcard_expand_internal(const wchar_t *wc,
                                    const wchar_t *base_dir,
                                    expand_flags_t flags,
                                    std::vector<completion_t> &out,
                                    std::set<wcstring> &completion_set,
                                    std::set<file_id_t> &visited_files
                                   )
{

    /* Points to the end of the current wildcard segment */
    const wchar_t *wc_end;

    /* Variables for traversing a directory */
    DIR *dir;

    /* The result returned */
    int res = 0;

    /* Length of the directory to search in */
    size_t base_len;

    /* Variables for testing for presense of recursive wildcards */
    const wchar_t *wc_recursive;
    bool is_recursive;

    /* Slightly mangled version of base_dir */
    const wchar_t *dir_string;

    //  debug( 3, L"WILDCARD_EXPAND %ls in %ls", wc, base_dir );

    if (is_main_thread() ? reader_interrupted() : reader_thread_job_is_stale())
    {
        return -1;
    }

    if (!wc || !base_dir)
    {
        debug(2, L"Got null string on line %d of file %s", __LINE__, __FILE__);
        return 0;
    }

    if (flags & ACCEPT_INCOMPLETE)
    {
        /*
           Avoid excessive number of returned matches for wc ending with a *
        */
        size_t len = wcslen(wc);
        if (len && (wc[len-1]==ANY_STRING))
        {
            wchar_t * foo = wcsdup(wc);
            foo[len-1]=0;
            int res = wildcard_expand_internal(foo, base_dir, flags, out, completion_set, visited_files);
            free(foo);
            return res;
        }
    }

    /*
      Initialize various variables
    */

    dir_string = base_dir[0]==L'\0'?L".":base_dir;

    if (!(dir = wopendir(dir_string)))
    {
        return 0;
    }

    wc_end = wcschr(wc,L'/');
    base_len = wcslen(base_dir);

    /*
      Test for recursive match string in current segment
    */
    wc_recursive = wcschr(wc, ANY_STRING_RECURSIVE);
    is_recursive = (wc_recursive && (!wc_end || wc_recursive < wc_end));

    /*
      Is this segment of the wildcard the last?
    */
    if (!wc_end)
    {
        /*
          Wildcard segment is the last segment,

          Insert all matching files/directories
        */
        if (wc[0]=='\0')
        {
            /*
              The last wildcard segment is empty. Insert everything if
              completing, the directory itself otherwise.
            */
            if (flags & ACCEPT_INCOMPLETE)
            {
                wcstring next;
                while (wreaddir(dir, next))
                {
                    if (next[0] != L'.')
                    {
                        wcstring long_name = make_path(base_dir, next);

                        if (test_flags(long_name.c_str(), flags))
                        {
                            wildcard_completion_allocate(out,
                                                         long_name,
                                                         next,
                                                         L"",
                                                         flags);
                        }
                    }
                }
            }
            else
            {
                res = 1;
                insert_completion_if_missing(base_dir, out, completion_set);
            }
        }
        else
        {
            /*
              This is the last wildcard segment, and it is not empty. Match files/directories.
            */
            wcstring next;
            while (wreaddir(dir, next))
            {
                const wchar_t * const name = next.c_str();
                if (flags & ACCEPT_INCOMPLETE)
                {

                    const wcstring long_name = make_path(base_dir, next);

                    /*
                      Test for matches before stating file, so as to minimize the number of calls to the much slower stat function
                    */
                    std::vector<completion_t> test;
                    if (wildcard_complete(name,
                                          wc,
                                          L"",
                                          0,
                                          test,
                                          0))
                    {
                        if (test_flags(long_name.c_str(), flags))
                        {
                            wildcard_completion_allocate(out,
                                                         long_name,
                                                         name,
                                                         wc,
                                                         flags);

                        }
                    }
                }
                else
                {
                    if (wildcard_match2(name, wc, true))
                    {
                        const wcstring long_name = make_path(base_dir, next);
                        int skip = 0;

                        if (is_recursive)
                        {
                            /*
                              In recursive mode, we are only
                              interested in adding files -directories
                              will be added in the next pass.
                            */
                            struct stat buf;
                            if (!wstat(long_name, &buf))
                            {
                                skip = S_ISDIR(buf.st_mode);
                            }
                        }
                        if (! skip)
                        {
                            insert_completion_if_missing(long_name, out, completion_set);
                        }
                        res = 1;
                    }
                }
            }
        }
    }

    if (wc_end || is_recursive)
    {
        /*
          Wilcard segment is not the last segment.  Recursively call
          wildcard_expand for all matching subdirectories.
        */

        /*
          wc_str is the part of the wildcarded string from the
          beginning to the first slash
        */
        wchar_t *wc_str;

        /*
          new_dir is a scratch area containing the full path to a
          file/directory we are iterating over
        */
        wchar_t *new_dir;

        /*
          The maximum length of a file element
        */
        long ln=MAX_FILE_LENGTH;
        char * narrow_dir_string = wcs2str(dir_string);

        /*
          In recursive mode, we look through the directory twice. If
          so, this rewind is needed.
        */
        rewinddir(dir);

        if (narrow_dir_string)
        {
            /*
               Find out how long the filename can be in a worst case
               scenario
            */
            ln = pathconf(narrow_dir_string, _PC_NAME_MAX);

            /*
              If not specified, use som large number as fallback
            */
            if (ln < 0)
                ln = MAX_FILE_LENGTH;
            free(narrow_dir_string);
        }
        new_dir= (wchar_t *)malloc(sizeof(wchar_t)*(base_len+ln+2));

        wc_str = wc_end?wcsndup(wc, wc_end-wc):wcsdup(wc);

        if ((!new_dir) || (!wc_str))
        {
            DIE_MEM();
        }

        wcscpy(new_dir, base_dir);

        wcstring next;
        while (wreaddir(dir, next))
        {
            const wchar_t *name = next.c_str();

            /*
              Test if the file/directory name matches the whole
              wildcard element, i.e. regular matching.
            */
            int whole_match = wildcard_match2(name, wc_str, true);
            int partial_match = 0;

            /*
               If we are doing recursive matching, also check if this
               directory matches the part up to the recusrive
               wildcard, if so, then we can search all subdirectories
               for matches.
            */
            if (is_recursive)
            {
                const wchar_t *end = wcschr(wc, ANY_STRING_RECURSIVE);
                wchar_t *wc_sub = wcsndup(wc, end-wc+1);
                partial_match = wildcard_match2(name, wc_sub, true);
                free(wc_sub);
            }

            if (whole_match || partial_match)
            {
                struct stat buf;
                char *dir_str;
                int stat_res;
                int new_res;

                wcscpy(&new_dir[base_len], name);
                dir_str = wcs2str(new_dir);

                if (dir_str)
                {
                    stat_res = stat(dir_str, &buf);
                    free(dir_str);

                    if (!stat_res)
                    {
                        // Insert a "file ID" into visited_files
                        // If the insertion fails, we've already visited this file (i.e. a symlink loop)
                        // If we're not recursive, insert anyways (in case we loop back around in a future recursive segment), but continue on; the idea being that literal path components should still work
                        const file_id_t file_id(buf.st_dev, buf.st_ino);
                        if (S_ISDIR(buf.st_mode) && (visited_files.insert(file_id).second || ! is_recursive))
                        {
                            size_t new_len = wcslen(new_dir);
                            new_dir[new_len] = L'/';
                            new_dir[new_len+1] = L'\0';

                            /*
                              Regular matching
                            */
                            if (whole_match)
                            {
                                const wchar_t *new_wc = L"";
                                if (wc_end)
                                {
                                    new_wc=wc_end+1;
                                    /*
                                      Accept multiple '/' as a single direcotry separator
                                    */
                                    while (*new_wc==L'/')
                                    {
                                        new_wc++;
                                    }
                                }

                                new_res = wildcard_expand_internal(new_wc,
                                                                   new_dir,
                                                                   flags,
                                                                   out,
                                                                   completion_set,
                                                                   visited_files);

                                if (new_res == -1)
                                {
                                    res = -1;
                                    break;
                                }
                                res |= new_res;

                            }

                            /*
                              Recursive matching
                            */
                            if (partial_match)
                            {

                                new_res = wildcard_expand_internal(wcschr(wc, ANY_STRING_RECURSIVE),
                                                                   new_dir,
                                                                   flags | WILDCARD_RECURSIVE,
                                                                   out,
                                                                   completion_set,
                                                                   visited_files);

                                if (new_res == -1)
                                {
                                    res = -1;
                                    break;
                                }
                                res |= new_res;

                            }
                        }
                    }
                }
            }
        }

        free(wc_str);
        free(new_dir);
    }
    closedir(dir);

    return res;
}
Exemplo n.º 19
0
/**
 * Update all the MetaData and art on an "item-changed" event
 **/
void MetaPanel::update( input_item_t *p_item )
{
    if( !p_item )
    {
        clear();
        return;
    }

    /* Don't update if you are in edit mode */
    if( b_inEditMode ) return;
    else p_input = p_item;

    char *psz_meta;
#define UPDATE_META( meta, widget ) {               \
    psz_meta = input_item_Get##meta( p_item );      \
    if( !EMPTY_STR( psz_meta ) )                    \
        widget->setText( qfu( psz_meta ) );         \
    else                                            \
        widget->setText( "" ); }                    \
    free( psz_meta );

#define UPDATE_META_INT( meta, widget ) {           \
    psz_meta = input_item_Get##meta( p_item );      \
    if( !EMPTY_STR( psz_meta ) )                    \
        widget->setValue( atoi( psz_meta ) ); }     \
    free( psz_meta );

    /* Name / Title */
    psz_meta = input_item_GetTitleFbName( p_item );
    if( psz_meta )
    {
        title_text->setText( qfu( psz_meta ) );
        free( psz_meta );
    }
    else
        title_text->setText( "" );

    /* URL / URI */
    psz_meta = input_item_GetURL( p_item );
    if( !EMPTY_STR( psz_meta ) )
        emit uriSet( qfu( psz_meta ) );
    else
    {
        free( psz_meta );
        psz_meta = input_item_GetURI( p_item );
        if( !EMPTY_STR( psz_meta ) )
            emit uriSet( qfu( psz_meta ) );
    }
    free( psz_meta );

    /* Other classic though */
    UPDATE_META( Artist, artist_text );
    UPDATE_META( Genre, genre_text );
    UPDATE_META( Copyright, copyright_text );
    UPDATE_META( Album, collection_text );
    UPDATE_META( Description, description_text );
    UPDATE_META( Language, language_text );
    UPDATE_META( NowPlaying, nowplaying_text );
    UPDATE_META( Publisher, publisher_text );
//    UPDATE_META( Setting, setting_text );
//FIXME this is wrong if has Publisher and EncodedBy fields
    UPDATE_META( EncodedBy, publisher_text );

    UPDATE_META( Date, date_text );
    UPDATE_META( TrackNum, seqnum_text );
//    UPDATE_META_INT( Rating, rating_text );

#undef UPDATE_META_INT
#undef UPDATE_META

    // If a artURL is available as a local file, directly display it !

    QString file;
    char *psz_art = input_item_GetArtURL( p_item );
    if( psz_art )
    {
        char *psz = make_path( psz_art );
        free( psz_art );
        file = qfu( psz );
        free( psz );
    }

    art_cover->showArtUpdate( file );

}
Exemplo n.º 20
0
// ======================================================
	void simppoll::OnOK()
// ======================================================
{
CString str,full,info;
char	tmp[MAX_PATH],path[MAX_PATH];
char	eofchr[]={0,0};
time_t	oldsecs;
int		errorcode,zone,net,node,point;

OLDPKTHDR   po;   // groesse jeweils 58 bytes
NEWPKTHDR   *pn;
FILE		*fp;

	m_edit.GetWindowText(str);
    trim_all(str);

	int ret=expand_address(str,full,info,1,1,0,errorcode);
	if (!ret)	
		ERR_MSG_RET("W_NOFSFIM");

	CFido xx;
	xx=PS full;

	make_path(tmp,gc.OutboundPath,xx.GetAsDir(0));

	if (!access(tmp,0))
		ERR_MSG2_RET("M_PSAE",full);

	time(&oldsecs);
	str.Format("%08X",oldsecs);

	_mkdir(tmp);
	make_path(path,tmp,str);

	// now fill pkt-structure

	get_first_aka(&zone,&net,&node,&point);
	pn = (NEWPKTHDR *)&po;
	memset(pn,0,sizeof(NEWPKTHDR));

	pn->product	= 0;
	pn->rev_lev	= 0;
	pn->subver	= 2;
	pn->version	= 2;
	pn->ozone 	= zone;	  // main aka
	pn->onet 	= net;
	pn->onode 	= node;
	pn->opoint 	= point;
  	pn->dzone 	= xx.zone; // remote aka
	pn->dnet 	= xx.net;
	pn->dnode 	= xx.node;
	pn->dpoint 	= xx.point;

	fp=fopen(path,"wb");
	if (!fp)	
		ERR_MSG2_RET("E_CANTCREATEDUMMY",path);

	fwrite(pn,sizeof(NEWPKTHDR),1,fp);
	fwrite(eofchr,2,1,fp);
	fclose(fp);

	gMailer.ShowWindow(SW_SHOWNORMAL);
	gMailer.GraphicalStatusDisplay(1);

	CDialog::OnOK();
}
Exemplo n.º 21
0
struct hid_device_info  HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id)
{
	libusb_device **devs;
	libusb_device *dev;
	libusb_device_handle *handle;
	ssize_t num_devs;
	int i = 0;
	
	struct hid_device_info *root = NULL; // return object
	struct hid_device_info *cur_dev = NULL;
	
	setlocale(LC_ALL,"");
	
	if (!initialized)
		hid_init();

	num_devs = libusb_get_device_list(NULL, &devs);
	if (num_devs < 0)
		return NULL;
	while ((dev = devs[i++]) != NULL) {
		struct libusb_device_descriptor desc;
		struct libusb_config_descriptor *conf_desc = NULL;
		int j, k;
		int interface_num = 0;

		int res = libusb_get_device_descriptor(dev, &desc);
		unsigned short dev_vid = desc.idVendor;
		unsigned short dev_pid = desc.idProduct;
		
		/* HID's are defined at the interface level. */
		if (desc.bDeviceClass != LIBUSB_CLASS_PER_INTERFACE)
			continue;

		res = libusb_get_active_config_descriptor(dev, &conf_desc);
		if (res < 0)
			libusb_get_config_descriptor(dev, 0, &conf_desc);
		if (conf_desc) {
			for (j = 0; j < conf_desc->bNumInterfaces; j++) {
				const struct libusb_interface *intf = &conf_desc->interface[j];
				for (k = 0; k < intf->num_altsetting; k++) {
					const struct libusb_interface_descriptor *intf_desc;
					intf_desc = &intf->altsetting[k];
					if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID) {
						interface_num = intf_desc->bInterfaceNumber;

						/* Check the VID/PID against the arguments */
						if ((vendor_id == 0x0 && product_id == 0x0) ||
						    (vendor_id == dev_vid && product_id == dev_pid)) {
							struct hid_device_info *tmp;

							/* VID/PID match. Create the record. */
							tmp = calloc(1, sizeof(struct hid_device_info));
							if (cur_dev) {
								cur_dev->next = tmp;
							}
							else {
								root = tmp;
							}
							cur_dev = tmp;
							
							/* Fill out the record */
							cur_dev->next = NULL;
							cur_dev->path = make_path(dev, interface_num);
							
							res = libusb_open(dev, &handle);

							if (res >= 0) {
								/* Serial Number */
								if (desc.iSerialNumber > 0)
									cur_dev->serial_number =
										get_usb_string(handle, desc.iSerialNumber);

								/* Manufacturer and Product strings */
								if (desc.iManufacturer > 0)
									cur_dev->manufacturer_string =
										get_usb_string(handle, desc.iManufacturer);
								if (desc.iProduct > 0)
									cur_dev->product_string =
										get_usb_string(handle, desc.iProduct);

#ifdef INVASIVE_GET_USAGE
							/*
							This section is removed because it is too
							invasive on the system. Getting a Usage Page
							and Usage requires parsing the HID Report
							descriptor. Getting a HID Report descriptor
							involves claiming the interface. Claiming the
							interface involves detaching the kernel driver.
							Detaching the kernel driver is hard on the system
							because it will unclaim interfaces (if another
							app has them claimed) and the re-attachment of
							the driver will sometimes change /dev entry names.
							It is for these reasons that this section is
							#if 0. For composite devices, use the interface
							field in the hid_device_info struct to distinguish
							between interfaces. */
								int detached = 0;
								unsigned char data[256];
							
								/* Usage Page and Usage */
								res = libusb_kernel_driver_active(handle, interface_num);
								if (res == 1) {
									res = libusb_detach_kernel_driver(handle, interface_num);
									if (res < 0)
										LOG("Couldn't detach kernel driver, even though a kernel driver was attached.");
									else
										detached = 1;
								}
								res = libusb_claim_interface(handle, interface_num);
								if (res >= 0) {
									/* Get the HID Report Descriptor. */
									res = libusb_control_transfer(handle, LIBUSB_ENDPOINT_IN|LIBUSB_RECIPIENT_INTERFACE, LIBUSB_REQUEST_GET_DESCRIPTOR, (LIBUSB_DT_REPORT << 8)|interface_num, 0, data, sizeof(data), 5000);
									if (res >= 0) {
										unsigned short page=0, usage=0;
										/* Parse the usage and usage page
										   out of the report descriptor. */
										get_usage(data, res,  &page, &usage);
										cur_dev->usage_page = page;
										cur_dev->usage = usage;
									}
									else
										LOG("libusb_control_transfer() for getting the HID report failed with %d\n", res);

									/* Release the interface */
									res = libusb_release_interface(handle, interface_num);
									if (res < 0)
										LOG("Can't release the interface.\n");
								}
								else
									LOG("Can't claim interface %d\n", res);

								/* Re-attach kernel driver if necessary. */
								if (detached) {
									res = libusb_attach_kernel_driver(handle, interface_num);
									if (res < 0)
										LOG("Couldn't re-attach kernel driver.\n");
								}
#endif /*******************/

								libusb_close(handle);
							}
							/* VID/PID */
							cur_dev->vendor_id = dev_vid;
							cur_dev->product_id = dev_pid;

							/* Release Number */
							cur_dev->release_number = desc.bcdDevice;
							
							/* Interface Number */
							cur_dev->interface_number = interface_num;
						}
					}
				} /* altsettings */
			} /* interfaces */
			libusb_free_config_descriptor(conf_desc);
		}
	}

	libusb_free_device_list(devs, 1);

	return root;
}
Exemplo n.º 22
0
/*****************************************************************************
 * ItemChange: Playlist item change callback
 *****************************************************************************/
static int ItemChange( vlc_object_t *p_this, const char *psz_var,
                       vlc_value_t oldval, vlc_value_t newval, void *param )
{
    VLC_UNUSED(psz_var); VLC_UNUSED(oldval); VLC_UNUSED(newval);
    char           psz_tmp[MAX_LENGTH];
    char           psz_notify[MAX_LENGTH];
    char           *psz_title;
    char           *psz_artist;
    char           *psz_album;
    char           *psz_arturl;
    input_thread_t *p_input = playlist_CurrentInput( (playlist_t*)p_this );
    intf_thread_t  *p_intf  = param;
    intf_sys_t     *p_sys   = p_intf->p_sys;

    if( !p_input )
        return VLC_SUCCESS;

    if( p_input->b_dead )
    {
        /* Not playing anything ... */
        vlc_object_release( p_input );
        return VLC_SUCCESS;
    }

    /* Wait a tad so the meta has been fetched
     * FIXME that's awfully wrong */
    msleep( 10000 );

    /* Playing something ... */
    input_item_t *p_input_item = input_GetItem( p_input );
    psz_title = input_item_GetTitleFbName( p_input_item );

    /* We need at least a title */
    if( EMPTY_STR( psz_title ) )
    {
        free( psz_title );
        vlc_object_release( p_input );
        return VLC_SUCCESS;
    }

    psz_artist = input_item_GetArtist( p_input_item );
    psz_album = input_item_GetAlbum( p_input_item );

    if( !EMPTY_STR( psz_artist ) )
    {
        if( !EMPTY_STR( psz_album ) )
            snprintf( psz_tmp, MAX_LENGTH, "<b>%s</b>\n%s\n[%s]",
                      psz_title, psz_artist, psz_album );
        else
            snprintf( psz_tmp, MAX_LENGTH, "<b>%s</b>\n%s",
                      psz_title, psz_artist );
    }
    else
        snprintf( psz_tmp, MAX_LENGTH, "<b>%s</b>", psz_title );

    free( psz_title );
    free( psz_artist );
    free( psz_album );

    GdkPixbuf *pix = NULL;
    psz_arturl = input_item_GetArtURL( p_input_item );
    vlc_object_release( p_input );

    if( psz_arturl )
    {
        char *psz = make_path( psz_arturl );
        free( psz_arturl );
        psz_arturl = psz;
    }

    if( psz_arturl )
    { /* scale the art to show it in notify popup */
        GError *p_error = NULL;
        pix = gdk_pixbuf_new_from_file_at_scale( psz_arturl,
                                                 72, 72, TRUE, &p_error );
    }
    else /* else we show state-of-the art logo */
    {
        /* First try to get an icon from the current theme. */
        GtkIconTheme* p_theme = gtk_icon_theme_get_default();
        pix = gtk_icon_theme_load_icon( p_theme, "vlc", 72, 0, NULL);

        if( !pix )
        {
        /* Load icon from share/ */
            GError *p_error = NULL;
            char *psz_pixbuf;
            char *psz_data = config_GetDataDir();
            if( asprintf( &psz_pixbuf, "%s/icons/48x48/vlc.png", psz_data ) >= 0 )
            {
                pix = gdk_pixbuf_new_from_file( psz_pixbuf, &p_error );
                free( psz_pixbuf );
            }
            free( psz_data );
        }
    }

    free( psz_arturl );

    /* we need to replace '&' with '&amp;' because '&' is a keyword of
     * notification-daemon parser */
    const int i_len = strlen( psz_tmp );
    int i_notify = 0;
    for( int i = 0; i < i_len && i_notify < ( MAX_LENGTH - 5 ); i++ )
    { /* we use MAX_LENGTH - 5 because if the last char of psz_tmp is '&'
       * we will need 5 more characters: 'amp;\0' .
       * however that's unlikely to happen because the last char is '\0' */
        if( psz_tmp[i] != '&' )
        {
            psz_notify[i_notify] = psz_tmp[i];
        }
        else
        {
            strcpy( &psz_notify[i_notify], "&amp;" );
            i_notify += 4;
        }
        i_notify++;
    }
    psz_notify[i_notify] = '\0';

    vlc_mutex_lock( &p_sys->lock );

    Notify( p_this, psz_notify, pix, p_intf );

    vlc_mutex_unlock( &p_sys->lock );

    return VLC_SUCCESS;
}
Exemplo n.º 23
0
static int sync_meta(csiebox_server *server, int conn_fd, csiebox_protocol_meta *meta)/*{{{*/
{
	char full_path[PATH_MAX];
	recv_message(conn_fd, full_path, sizeof(full_path));
	// make a short path
	char *client_path = make_path(full_path);
	char *cur_dir = get_user_homedir(server, server->client[conn_fd]);
	if (chdir(cur_dir) == -1) {
		fprintf(stderr, "change to user directory error\n");
		return 0;
	}
	// start to traverse
	int file_check = 0;
	char *object = strtok(client_path, "/");
	while(object != NULL){
		strcat(cur_dir, "/");
		strcat(cur_dir, object);
		struct stat object_stat;
		memset(&object_stat, 0, sizeof(object_stat));
		int open_success = lstat(cur_dir, &object_stat);
		// if file not exist
		if (open_success == -1){
			if (S_ISDIR(meta->message.body.stat.st_mode)) {
				mkdir(cur_dir, meta->message.body.stat.st_mode);
				fprintf(stderr, "sync meta : create dir\n");
				// dir utime
				struct utimbuf meta_time;
				memset(&meta_time, 0, sizeof(meta_time));
				meta_time.actime = meta->message.body.stat.st_atime;
				meta_time.modtime = meta->message.body.stat.st_mtime;
				utime(cur_dir, &meta_time);
				fprintf(stderr, "create dir\n");
			}
			if (S_ISREG(meta->message.body.stat.st_mode)) {
				int fd = creat(cur_dir, meta->message.body.stat.st_mode);
				// file utime
				struct utimbuf meta_time;
				memset(&meta_time, 0, sizeof(meta_time));
				meta_time.actime = meta->message.body.stat.st_atime;
				meta_time.modtime = meta->message.body.stat.st_mtime;
				utime(cur_dir, &meta_time);
				fprintf(stderr, "sync meta : create file\n");
				close(fd);
				file_check = 1;
			}
			if (S_ISLNK(meta->message.body.stat.st_mode)) {
				fprintf(stderr, "sync meta : is symbolic link\n");
				file_check = 1;
			}
			object = strtok(NULL, "/");
		}
		// file exist
		else {
			// is directory
			if (S_ISDIR(object_stat.st_mode)){
				if (chdir(cur_dir) == -1) {
					fprintf(stderr, "chdir error\n");
					return 0;
				}
			}
			else {
			// is file
				// file chmod
				chmod(cur_dir, meta->message.body.stat.st_mode);
				chown(cur_dir, meta->message.body.stat.st_uid, meta->message.body.stat.st_gid);
				// check if is same
				uint8_t content_hash[MD5_DIGEST_LENGTH];
				memset(content_hash, 0, sizeof(content_hash));
				md5_file(cur_dir, content_hash);
				if (memcmp(content_hash, meta->message.body.hash, MD5_DIGEST_LENGTH) != 0) file_check = 1;
				// file utime
				struct utimbuf meta_time;
				memset(&meta_time, 0, sizeof(meta_time));
				meta_time.actime = meta->message.body.stat.st_atime;
				meta_time.modtime = meta->message.body.stat.st_mtime;
				utime(cur_dir, &meta_time);
			}
			object = strtok(NULL, "/");
			// dir chmod
			if (object == NULL) {
				chmod(cur_dir, meta->message.body.stat.st_mode);
				chown(cur_dir, meta->message.body.stat.st_uid, meta->message.body.stat.st_gid);
				struct utimbuf meta_time;
				// dir utime
				memset(&meta_time, 0, sizeof(meta_time));
				meta_time.actime = meta->message.body.stat.st_atime;
				meta_time.modtime = meta->message.body.stat.st_mtime;
				utime(cur_dir, &meta_time);
			}
		}
	}
	// send back message
	csiebox_protocol_header header;
	memset(&header, 0, sizeof(header));
	header.res.magic = CSIEBOX_PROTOCOL_MAGIC_RES;
	header.res.op = CSIEBOX_PROTOCOL_OP_SYNC_META;
	header.res.status = (file_check == 1)? CSIEBOX_PROTOCOL_STATUS_MORE : CSIEBOX_PROTOCOL_STATUS_OK;
	header.res.datalen = 0;
	send_message(conn_fd, &header, sizeof(header));
	fprintf(stderr, "sync meta : success\n");

	return 1;
}/*}}}*/
Exemplo n.º 24
0
static void
handle_packet_in( uint64_t datapath_id, uint32_t transaction_id,
                  uint32_t buffer_id, uint16_t total_len,
                  uint16_t in_port, uint8_t reason, const buffer *data,
                  void *user_data ) {
    assert( in_port != 0 );
    assert( data != NULL );
    assert( user_data != NULL );

    sliceable_switch *sliceable_switch = user_data;

    debug( "Packet-In received ( datapath_id = %#" PRIx64 ", transaction_id = %#" PRIx32 ", "
           "buffer_id = %#" PRIx32 ", total_len = %u, in_port = %u, reason = %#x, "
           "data_len = %zu ).", datapath_id, transaction_id, buffer_id,
           total_len, in_port, reason, data->length );

    if ( in_port > OFPP_MAX && in_port != OFPP_LOCAL ) {
        error( "Packet-In from invalid port ( in_port = %u ).", in_port );
        return;
    }

    const port_info *port = lookup_port( sliceable_switch->switches, datapath_id, in_port );
    if ( port == NULL ) {
        debug( "Ignoring Packet-In from unknown port." );
        return;
    }

    packet_info packet_info = get_packet_info( data );
    const uint8_t *src = packet_info.eth_macsa;
    const uint8_t *dst = packet_info.eth_macda;

    if ( !port->external_link || port->switch_to_switch_reverse_link ) {
        if ( !port->external_link
                && port->switch_to_switch_link
                && port->switch_to_switch_reverse_link
                && !is_ether_multicast( dst )
                && lookup_fdb( sliceable_switch->fdb, src, &datapath_id, &in_port ) ) {
            debug( "Found a Packet-In from switch-to-switch link." );
        }
        else {
            debug( "Ignoring Packet-In from non-external link." );
            return;
        }
    }

    uint16_t vid = VLAN_NONE;
    if ( packet_type_eth_vtag( data ) ) {
        vid = packet_info.vlan_vid;
    }

    if ( !update_fdb( sliceable_switch->fdb, src, datapath_id, in_port ) ) {
        return;
    }

    char match_str[ 1024 ];
    struct ofp_match match;
    set_match_from_packet( &match, in_port, 0, data );
    match_to_string( &match, match_str, sizeof( match_str ) );

    uint16_t slice = lookup_slice( datapath_id, in_port, vid, src );
    if ( slice == SLICE_NOT_FOUND ) {
        warn( "No slice found ( dpid = %#" PRIx64 ", vid = %u, match = [%s] ).", datapath_id, vid, match_str );
        goto deny;
    }

    int action = filter( datapath_id, in_port, slice, data );
    switch ( action ) {
    case ALLOW:
        debug( "Filter: ALLOW ( dpid = %#" PRIx64 ", slice = %#x, match = [%s] ).", datapath_id, slice, match_str );
        goto allow;
    case DENY:
        debug( "Filter: DENY ( dpid = %#" PRIx64 ", slice = %#x, match = [%s] ).", datapath_id, slice, match_str );
        goto deny;
    case LOCAL:
        debug( "Filter: LOCAL ( dpid = %#" PRIx64 ", slice = %#x, match = [%s] ).", datapath_id, slice, match_str );
        goto local;
    default:
        error( "Undefined filter action ( action = %#x ).", action );
        goto deny;
    }

allow:
    {
        uint16_t out_port;
        uint64_t out_datapath_id;

        if ( lookup_fdb( sliceable_switch->fdb, dst, &out_datapath_id, &out_port ) ) {
            // Host is located, so resolve path and send flowmod
            if ( ( datapath_id == out_datapath_id ) && ( in_port == out_port ) ) {
                debug( "Input port and out port are the same ( datapath_id = %#" PRIx64 ", port = %u ).",
                       datapath_id, in_port );
                return;
            }

            uint16_t out_vid = vid;
            bool found = get_port_vid( slice, out_datapath_id, out_port, &out_vid );
            if ( found == false ) {
                uint16_t out_slice = lookup_slice_by_mac( dst );
                if ( out_slice != slice ) {
                    debug( "Destination is on different slice ( slice = %#x, out_slice = %#x ).",
                           slice, out_slice );
                    goto deny;
                }
            }

            make_path( sliceable_switch, datapath_id, in_port, vid, out_datapath_id, out_port, out_vid, data );
        } else {
            if ( lookup_path( datapath_id, match, PRIORITY ) != NULL ) {
                teardown_path( datapath_id, match, PRIORITY );
            }

            // Host's location is unknown, so flood packet
            flood_packet( datapath_id, in_port, slice, data, sliceable_switch->switches );
        }
        return;
    }

deny:
    {
        // Drop packets for a certain period
        discard_packet_in( datapath_id, in_port, data, DISCARD_DURATION_DENY );
        return;
    }

local:
    {
        // Redirect to controller's local IP stack
        redirect( datapath_id, in_port, data );
        return;
    }
}
Exemplo n.º 25
0
FCITX_EXPORT_API
FILE *FcitxXDGGetFile(const char *fileName, char **path, const char *mode, size_t len, char **retFile)
{
    char* buf = NULL;
    size_t i;
    FILE *fp = NULL;

    /* check absolute path */

    if (strlen(fileName) > 0 && fileName[0] == '/') {
        if (mode)
            fp = fopen(fileName, mode);

        if (retFile)
            *retFile = strdup(fileName);

        return fp;
    }

    if (len <= 0)
        return NULL;

    if (!mode && retFile) {
        asprintf(retFile, "%s/%s", path[0], fileName);

        return NULL;
    }

    if (strlen(fileName) == 0) {
        if (retFile)
            asprintf(retFile, "%s", path[0]);
        if (strchr(mode, 'w') || strchr(mode, 'a')) {
            make_path(path[0]);
        }
        return NULL;
    }

    for (i = 0; i < len; i++) {
        asprintf(&buf, "%s/%s", path[i], fileName);

        fp = fopen(buf, mode);

        if (fp)
            break;

        free(buf);
        buf = NULL;
    }

    if (!fp) {
        if (strchr(mode, 'w') || strchr(mode, 'a')) {
            asprintf(&buf, "%s/%s", path[0], fileName);

            char *dirc = strdup(buf);
            char *dir = dirname(dirc);
            make_path(dir);
            fp = fopen(buf, mode);
            free(dirc);
        }
    }

    if (retFile)
        *retFile = buf;
    else if (buf)
        free(buf);

    return fp;
}
Exemplo n.º 26
0
/**
 * Walk directory tree and call given callback function to process each file/directory.
 *
 * @param start_dir path to the directory to walk recursively
 * @param options the options specifying how to walk the directory tree
 */
int find_file(file_t* start_dir, find_file_options* options)
{
	dir_entry *dirs_stack = NULL; /* root of the dir_list */
	dir_iterator* it;
	int level = 1;
	int max_depth = options->max_depth;
	int flags = options->options;
	dir_entry* entry;
	file_t file;

	if(max_depth < 0 || max_depth >= MAX_DIRS_DEPTH) {
		max_depth = MAX_DIRS_DEPTH;
	}

	/* skip the directory if max_depth == 0 */
	if(max_depth == 0) {
		return 0;
	}

	memset(&file, 0, sizeof(file));

	if((start_dir->mode & FILE_IFDIR) == 0) {
		errno = ENOTDIR;
		return -1;
	}

	/* check if we should descend into the root directory */
	if((flags & (FIND_WALK_DEPTH_FIRST | FIND_SKIP_DIRS)) == 0) {
		if(!options->call_back(start_dir, options->call_back_data))
			return 0;
	}

	it = (dir_iterator*)malloc(MAX_DIRS_DEPTH * sizeof(dir_iterator));
	if(!it) return 0;

	/* push root directory into dirs_stack */
	it[0].left = 1;
	it[0].prev_dir = rsh_strdup(start_dir->path);
	it[1].prev_dir = NULL;
	if(!it[0].prev_dir) {
		errno = ENOMEM;
		return -1;
	}
	entry = dir_entry_insert(&dirs_stack, NULL, 0);
	if(!entry) {
		free(it[0].prev_dir);
		free(it);
		errno = ENOMEM;
		return -1;
	}

	while(!(options->options & FIND_CANCEL)) {
		dir_entry *dir, **insert_at;
		char* dir_path;
		DIR *dp;
		struct dirent *de;

		/* walk back */
		while((--level) >= 0 && it[level].left <= 0) free(it[level+1].prev_dir);
		if(level < 0) break;
		assert(dirs_stack != NULL);
		/* on the first cycle: level == 0, stack[0] == 0; */

		dir = dirs_stack; /* take last dir from the list */
		dirs_stack = dirs_stack->next; /* remove last dir from the list */
		it[level].left--;

		dir_path = (!dir->filename ? rsh_strdup(it[level].prev_dir) :
			make_path(it[level].prev_dir, dir->filename) );
		dir_entry_free(dir);
		if(!dir_path) continue;

		level++;
		it[level].left = 0;
		it[level].prev_dir = dir_path;

		if((flags & (FIND_WALK_DEPTH_FIRST | FIND_SKIP_DIRS))
			== FIND_WALK_DEPTH_FIRST) {
			rsh_file_cleanup(&file);
			file.path = dir_path;
			/* check if we should skip the directory */
			if(!options->call_back(&file, options->call_back_data))
				continue;
		}

		/* read dir */
		dp = opendir(dir_path);
		if(dp == NULL) continue;

		insert_at = &dirs_stack;

		while((de = readdir(dp)) != NULL) {
			int res;
			/* skip "." and ".." dirs */
			if(de->d_name[0] == '.' && (de->d_name[1] == 0 ||
				(de->d_name[1] == '.' && de->d_name[2] == 0 )))
				continue;

			if( !(file.path = make_path(dir_path, de->d_name)) ) continue;

			res  = rsh_file_stat2(&file, USE_LSTAT);
			/* process */
			if(res >= 0) {
				if((file.mode & FILE_IFDIR) &&
					(flags & (FIND_WALK_DEPTH_FIRST | FIND_SKIP_DIRS))) res = 1;
				else {
					/* handle file by callback function */
					res = options->call_back(&file, options->call_back_data);
				}

				/* if file is a directory and we need to walk it */
				if((file.mode & FILE_IFDIR) && res && level < max_depth) {
					/* don't go deeper if max_depth reached */

					/* add directory to dirs_stack */
					if(dir_entry_insert(insert_at, de->d_name, file.mode)) {
						/* if really added */
						insert_at = &((*insert_at)->next);
						it[level].left++;
					}
				}
			} else if (options->options & FIND_LOG_ERRORS) {
				log_file_error(file.path);
			}
			rsh_file_cleanup(&file);
			free(file.path);
		}
		closedir(dp);

		if(it[level].left > 0) level++;
	}
	assert(dirs_stack == NULL);

	free(it);
	return 0;
}
Exemplo n.º 27
0
void qlevel_save(STRING *filename)
{
	STRING *file = "#256";
	make_path(file, filename);
	
	STRING *backup = "#256";
	str_cpy(backup, file);
	str_cat(backup, ".bak");
	file_delete(backup);
	file_rename(file, backup);
	
	ini_write_int(file, "Level Information", "EntityCount", 0);
	ini_write_int(file, "Level Information", "LightCount", 0);
	ini_write_int(file, "Level Information", "FogCount", 0);
	
	int countEntity = 0;
	int countLight = 0;
	int countFog = 0;
	
	STRING *section = "#64";
	for(you = ent_next(NULL); you != NULL; you = ent_next(you))
	{
		switch(you->group)
		{
			case GROUP_LEVEL:
				str_cpy(section, "Entity ");
				str_cat(section, str_for_int(NULL, countEntity));
				
				ini_write_string(file, section, "Model", you->type);
				ini_write_int(file, section, "ActionCount", 0);
				int actionCount = 0;
				STRING *actionName = "#64";
				ActionInformation *entry;
				for(entry = list_first(you->string1); entry != NULL; entry = list_next(you->string1, entry))
				{
					str_cpy(actionName, "Action");
					str_cat(actionName, str_for_int(NULL, actionCount));
					ini_write_string(file, section, actionName, _str(entry->actionname));
					actionCount++;
				}
				ini_write_int(file, section, "ActionCount", actionCount);
				
				ini_write_float(file, section, "X", you->x);
				ini_write_float(file, section, "Y", you->y);
				ini_write_float(file, section, "Z", you->z);
				ini_write_float(file, section, "Pan", cycle(you->pan, 0, 360));
				ini_write_float(file, section, "Tilt", cycle(you->tilt, 0, 360));
				ini_write_float(file, section, "Roll", cycle(you->roll, 0, 360));
				ini_write_float(file, section, "ScaleX", you->scale_x);
				ini_write_float(file, section, "ScaleY", you->scale_y);
				ini_write_float(file, section, "ScaleZ", you->scale_z);
				ini_write_float(file, section, "Lightrange", you->lightrange);

				countEntity++;
				break;
		}
	}
	
	ini_write_int(file, "Level Information", "EntityCount", countEntity);
	ini_write_int(file, "Level Information", "LightCount", countLight);
	ini_write_int(file, "Level Information", "FogCount", countFog);
}
Exemplo n.º 28
0
struct hid_device_info  HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id)
{
	struct hid_device_info *root = NULL; // return object
	struct hid_device_info *cur_dev = NULL;
	CFIndex num_devices;
	int i;
	
	setlocale(LC_ALL,"");

	/* Set up the HID Manager if it hasn't been done */
	if (hid_init() < 0)
		return NULL;
	
	/* give the IOHIDManager a chance to update itself */
	process_pending_events();

	/* Get a list of the Devices */
	CFSetRef device_set = IOHIDManagerCopyDevices(hid_mgr);

	/* Convert the list into a C array so we can iterate easily. */	
	num_devices = CFSetGetCount(device_set);
	IOHIDDeviceRef *device_array = calloc(num_devices, sizeof(IOHIDDeviceRef));
	CFSetGetValues(device_set, (const void **) device_array);

	/* Iterate over each device, making an entry for it. */	
	for (i = 0; i < num_devices; i++) {
		unsigned short dev_vid;
		unsigned short dev_pid;
		#define BUF_LEN 256
		wchar_t buf[BUF_LEN];
		char cbuf[BUF_LEN];

		IOHIDDeviceRef dev = device_array[i];

        if (!dev) {
            continue;
        }
		dev_vid = get_vendor_id(dev);
		dev_pid = get_product_id(dev);

		/* Check the VID/PID against the arguments */
		if ((vendor_id == 0x0 && product_id == 0x0) ||
		    (vendor_id == dev_vid && product_id == dev_pid)) {
			struct hid_device_info *tmp;
			size_t len;

		    	/* VID/PID match. Create the record. */
			tmp = malloc(sizeof(struct hid_device_info));
			if (cur_dev) {
				cur_dev->next = tmp;
			}
			else {
				root = tmp;
			}
			cur_dev = tmp;

			// Get the Usage Page and Usage for this device.
			cur_dev->usage_page = get_int_property(dev, CFSTR(kIOHIDPrimaryUsagePageKey));
			cur_dev->usage = get_int_property(dev, CFSTR(kIOHIDPrimaryUsageKey));

			/* Fill out the record */
			cur_dev->next = NULL;
			len = make_path(dev, cbuf, sizeof(cbuf));
			cur_dev->path = strdup(cbuf);

			/* Serial Number */
			get_serial_number(dev, buf, BUF_LEN);
			cur_dev->serial_number = dup_wcs(buf);

			/* Manufacturer and Product strings */
			get_manufacturer_string(dev, buf, BUF_LEN);
			cur_dev->manufacturer_string = dup_wcs(buf);
			get_product_string(dev, buf, BUF_LEN);
			cur_dev->product_string = dup_wcs(buf);
			
			/* VID/PID */
			cur_dev->vendor_id = dev_vid;
			cur_dev->product_id = dev_pid;

			/* Release Number */
			cur_dev->release_number = get_int_property(dev, CFSTR(kIOHIDVersionNumberKey));

			/* Interface Number (Unsupported on Mac)*/
			cur_dev->interface_number = -1;
		}
	}
	
	free(device_array);
	CFRelease(device_set);
	
	return root;
}
Exemplo n.º 29
0
/* Load M3U file into plist.  Return the number of items read. */
static int plist_load_m3u (struct plist *plist, const char *fname,
		const char *cwd, const int load_serial)
{
	FILE *file;
	char *line;
	int last_added = -1;
	int after_extinf = 0;
	int added = 0;

	if (!(file = fopen(fname, "r"))) {
		error ("Can't open playlist file: %s",
				strerror(errno));
		return 0;
	}

	if (flock(fileno(file), LOCK_SH) == -1)
		logit ("Can't flock() the playlist file: %s", strerror(errno));

	while ((line = read_line(file))) {
		if (!strncmp(line, "#EXTINF:", sizeof("#EXTINF:")-1)) {
			char *comma;
			char *num_err;
			char time_text[10] = "";
			int time_sec;

			if (after_extinf) {
				error ("Broken M3U file: double "
						"#EXTINF.");
				free (line);
				plist_delete (plist, last_added);
				return added;
			}

			/* Find the comma */
			comma = strchr (line + (sizeof("#EXTINF:") - 1), ',');
			if (!comma) {
				error ("Broken M3U file: no comma "
						"in #EXTINF.");
				free (line);
				return added;
			}

			/* Get the time string */
			time_text[sizeof(time_text)-1] = 0;
			strncpy (time_text, line + sizeof("#EXTINF:") - 1,
					MIN(comma - line - (sizeof("#EXTINF:")
						- 1), sizeof(time_text)));
			if (time_text[sizeof(time_text)-1]) {
				error ("Broken M3U file: "
						"wrong time.");
				free (line);
				return added;
			}

			/* Extract the time */
			time_sec = strtol (time_text, &num_err, 10);
			if (*num_err) {
				error ("Broken M3U file: "
						"time is not a number.");
				free (line);
				return added;
			}

			after_extinf = 1;
			last_added = plist_add (plist, NULL);
			plist_set_title_tags (plist, last_added, comma + 1);

			if (*time_text)
				plist_set_item_time (plist, last_added,
						time_sec);
		}
		else if (line[0] != '#') {
			char path[2*PATH_MAX];

			strip_string (line);
			if (strlen(line) <= PATH_MAX) {
				make_path (path, sizeof(path), cwd, line);

				if (plist_find_fname(plist, path) == -1) {
					if (after_extinf)
						plist_set_file (plist,
								last_added,
								path);
					else
						plist_add (plist, path);
					added++;
				}
				else if (after_extinf)
					plist_delete (plist, last_added);
			}
			else if (after_extinf)
				plist_delete (plist, last_added);

			after_extinf = 0;
		}
		else if (load_serial && !strncmp(line, "#MOCSERIAL: ",
					sizeof("#MOCSERIAL: ") - 1)) {
			char *serial_str = line + sizeof("#MOCSERIAL: ") - 1;

			if (serial_str[0]) {
				char *err;
				long serial;

				serial = strtol (serial_str, &err, 0);
				if (!*err) {
					plist_set_serial (plist, serial);
					logit ("Got MOCSERIAL tag with serial %d",
							(int)serial);
				}
			}
		}
		free (line);
	}

	if (flock(fileno(file), LOCK_UN) == -1)
		logit ("Can't flock() (unlock) the playlist file: %s",
				strerror(errno));
	fclose (file);

	return added;
}
Exemplo n.º 30
0
int use_toolkit(char *url, char *toolkit_id, t_toolkit_options *options) {
	t_url_toolkit *toolkit;
	t_toolkit_rule *rule;
	bool condition_met, replaced = false;
	int result, skip = 0;
	char *file, *qmark, *header;
	regmatch_t pmatch[REGEXEC_NMATCH];
	struct stat fileinfo;

	if (options == NULL) {
		return UT_ERROR;
	}

	options->new_url = NULL;

	if ((toolkit = find_toolkit(toolkit_id, options->url_toolkit)) == NULL) {
		return UT_ERROR;
	}

	rule = toolkit->toolkit_rule;
	while (rule != NULL) {
		condition_met = false;

		/* Skip lines
		 */
		if (skip > 0) {
			skip--;
			rule = rule->next;
			continue;
		}

		/* Condition
		 */
		switch (rule->condition) {
			case tc_none:
				/* None
				 */
				condition_met = true;
				break;
			case tc_match:
				/* Match
				 */
				if (regexec(&(rule->pattern), url, REGEXEC_NMATCH, pmatch, 0) == 0) {
					condition_met = true;
				}
				if (rule->neg_match) {
					condition_met = (condition_met == false);
				}
				break;
			case tc_header:
				/* Header
				 */
				if ((header = get_http_header(rule->header, options->http_headers)) == NULL) {
					break;
				}
				if (regexec(&(rule->pattern), header, REGEXEC_NMATCH, pmatch, 0) == 0) {
					condition_met = true;
				}
				if (rule->neg_match) {
					condition_met = (condition_met == false);
				}
				break;
			case tc_request_uri:
				/* Request URI
				 */
				if (valid_uri(url, false) == false) {
					break;
				}
				if ((file = make_path(options->website_root, url)) == NULL) {
					return UT_ERROR;
				}

				if ((qmark = strchr(file, '?')) != NULL) {
					*qmark = '\0';
				}
				url_decode(file);

				if (stat(file, &fileinfo) != -1) {
					switch (rule->value) {
						case IU_EXISTS:
							if (S_ISDIR(fileinfo.st_mode) || S_ISREG(fileinfo.st_mode)) {
								condition_met = true;
							}
							break;
						case IU_ISFILE:
							if (S_ISREG(fileinfo.st_mode)) {
								condition_met = true;
							}
							break;
						case IU_ISDIR:
							if (S_ISDIR(fileinfo.st_mode)) {
								condition_met = true;
							}
							break;
					}
				}

				free(file);
				break;
#ifdef ENABLE_SSL
			case tc_use_ssl:
				/* Client connections uses SSL?
				 */
				condition_met = options->use_ssl;
				break;
#endif
		}

		/* Condition not met
		 */
		if (condition_met == false) {
			rule = rule->next;
			continue;
		}

		/* Operation
		 */
		switch (rule->operation) {
			case to_none:
				/* None
				 */
				break;
			case to_rewrite:
				/* Rewrite
				 */
				if (rule->neg_match) {
					if ((options->new_url = strdup(rule->parameter)) == NULL) {
						return UT_ERROR;
					}
				} else if (do_rewrite(url, &(rule->pattern), pmatch, rule->parameter, &(options->new_url), rule->match_loop) == -1) {
					if (options->new_url != NULL) {
						free(options->new_url);
						options->new_url = NULL;
					}
					return UT_ERROR;
				}
				if (options->new_url != NULL) {
					if (replaced) {
						free(url);
					}
					url = options->new_url;
					replaced = true;
				} else if (replaced) {
					options->new_url = url;
				}
				break;
			case to_sub:
				/* Subroutine
				 */
				if (++(options->sub_depth) > MAX_SUB_DEPTH) {
					return UT_ERROR;
				}

				if ((result = use_toolkit(url, rule->parameter, options)) == UT_ERROR) {
					if (options->new_url != NULL) {
						free(options->new_url);
						options->new_url = NULL;
					}
					return UT_ERROR;
				}
				options->sub_depth--;

				if (options->new_url != NULL) {
					if (replaced) {
						free(url);
					}
					url = options->new_url;
					replaced = true;
				} else if (replaced) {
					options->new_url = url;
				}

				if (result != UT_RETURN) {
					return result;
				}
				break;
			case to_expire:
				/* Send Expire HTTP header
				 */
				options->expire = rule->value;
				break;
			case to_skip:
				/* Skip
				 */
				skip = rule->value;
				break;
			case to_deny_access:
				/* Deny access
				 */
				return UT_DENY_ACCESS;
			case to_redirect:
				/* Redirect client
				 */
				if (rule->neg_match) {
					if ((options->new_url = strdup(rule->parameter)) == NULL) {
						return UT_ERROR;
					}
				} else if (do_rewrite(url, &(rule->pattern), pmatch, rule->parameter, &(options->new_url), rule->match_loop) == -1) {
					if (options->new_url != NULL) {
						free(options->new_url);
						options->new_url = NULL;
					}
					return UT_ERROR;
				}
				if (options->new_url != NULL) {
					if (replaced) {
						free(url);
					}
					return UT_REDIRECT;
				} else if (replaced) {
					options->new_url = url;
				}
				break;
			case to_fastcgi:
				/* Use FastCGI server
				 */
				options->fastcgi_server = rule->parameter;
				break;
			case to_ban:
				/* Ban client
				 */
				options->ban = rule->value;
				break;
			case to_replace:
				/* Replace URL
				 */
				if (replaced) {
					free(url);
				}
				if ((options->new_url = strdup(rule->parameter)) == NULL) {
					return UT_ERROR;
				}
				break;
		}

		/* Flow
		 */
		switch (rule->flow) {
			case tf_continue:
				/* Continue
				 */
				break;
			case tf_exit:
				/* Exit
				 */
				return UT_EXIT;
			case tf_return:
				/* Return
				 */
				return UT_RETURN;
		}

		rule = rule->next;
	}

	return UT_RETURN;
}