int main(int argc, char* argv[])
{
    // a global variable defined in errno.h that's "set by system 
    // calls and some library functions [to a nonzero value]
    // in the event of an error to indicate what went wrong"
    errno = 0;

    // default to a random port
    int port = 0;

    // usage
    const char* usage = "Usage: server [-p port] /path/to/root";

    // parse command-line arguments
    int opt;
    while ((opt = getopt(argc, argv, "hp:")) != -1)
    {
        switch (opt)
        {
            // -h
            case 'h':
                printf("%s\n", usage);
                return 0;

            // -p port
            case 'p':
                port = atoi(optarg);
                break;
        }
    }

    // ensure port is a non-negative short and path to server's root is specified
    if (port < 0 || port > SHRT_MAX || argv[optind] == NULL || strlen(argv[optind]) == 0)
    {
        // announce usage
        printf("%s\n", usage);

        // return 2 just like bash's builtins
        return 2;
    }

    // start server
    start(port, argv[optind]);

    // listen for SIGINT (aka control-c)
    signal(SIGINT, handler);

    // accept connections one at a time
    while (true)
    {
        // reset server's state
        reset();

        // wait until client is connected
        if (connected())
        {
            // parse client's HTTP request
            ssize_t octets = parse();
            if (octets == -1)
            {
                continue;
            }

            // extract request's request-line
            // http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html
            const char* haystack = request;
            char* needle = strstr(haystack, "\r\n");
            if (needle == NULL)
            {
                error(400);
                continue;
            }
            else if (needle - haystack + 2 > LimitRequestLine)
            {
                error(414);
                continue;
            }   
            char line[needle - haystack + 2 + 1];
            strncpy(line, haystack, needle - haystack + 2);
            line[needle - haystack + 2] = '\0';

            // log request-line
            printf("%s", line);

            // TODO: validate request-line
			// if request-line is CRLF respond to the browser with:	
			if (strcmp("\r\n", line) == 0)
	        {
		        error(400);
                continue;
	        }
			
			// extract HTTP-version from request-line
	        char* HTTP_version = "HTTP/1.1";
			char* HTTP_version_CRLF =  strrchr(line, 'H');
			
			char http_ver[strlen(HTTP_version) + 1];
            strncpy( http_ver, HTTP_version_CRLF, strlen(HTTP_version) );
            http_ver[strlen(HTTP_version)] = '\0';
			
			// extract method from request-line
			int method_len = strlen(line) - strlen(strchr(line, ' ')) ;
	        char method[method_len + 1];
			strncpy( method, &line[0], method_len );
            method[method_len] = '\0';
			//printf("method !%s! %i\n", method, method_len);
			
			// extract request-target from request-line
			int request_target_len = strlen(strchr(line, ' ')) - strlen(strrchr(line, ' ')) - 1;
	        char request_target[request_target_len + 1];
	
	        for (int i = method_len + 1; i < method_len + request_target_len + 1; i++)
	        {
		        if (line[i] == ' ')
		        {
			        break;
		        }
			    request_target[i - method_len - 1] = line[i];
	        }	
	        request_target[request_target_len ] = '\0';
			
			// extract absolute-path from request-target
			char absolute_path[100];
	        strcpy(absolute_path, request_target);
	        int size = strlen(request_target);
	        for (int i = 0; i < size ; i++)
	        {
		        if (request_target[i] == '?' || request_target[i] == ' ')
		        {
			        absolute_path[i] = '\0';
			        break;
		        }
			    absolute_path[i] = request_target[i];		
	        }
	        //printf("absolute_path !%s! \n", absolute_path);
			
			// request-line is consistent with these rules,
            // and respond to the browser with:			
			if (strcasestr("GET", method) == NULL)
	        {
	            error(405);
                continue;
	        }
			
			if (request_target[0] != '/')
	        {
		        error(501);
                continue;
	        }
			
			if (strchr(request_target, '"') != NULL)
	        {
		        error(400);
                continue;
	        }
			
			
			if (strcmp("HTTP/1.1", http_ver) != 0)
	        {
		        error(505);
                continue;
	        }
			
			if (strchrnul(absolute_path, '.') == NULL)
	        {
		        error(501);
                continue;
	        }	
			
			// TODO: extract query from request-target
            //char query[] = "TODO";	
	        char query[100];
	
	        if (strchr(request_target, '?') != NULL)
	        {
                strncpy(query, &request_target[strlen(absolute_path) + 1],
		        strlen(request_target) -  strlen(absolute_path) + 1);
	        }
	        else
	        {
		        strncpy(query, &request_target[strlen(absolute_path) ],
		        strlen(request_target) -  strlen(absolute_path) );
	        }
	
	        query[strlen(request_target) -  strlen(absolute_path) ] = '\0';
	
	        //printf("query !%s! \n", query);

            // TODO: concatenate root and absolute-path
            //char path[] = "TODO";
			char absolute_path_buffer[100];
			char root_buffer[100];

            /* Copy the first string into the variable */
            strcpy(root_buffer, root);
			strcpy(absolute_path_buffer, absolute_path);
			//printf("absolute_path!%s!\n", absolute_path);
			
			char* path = strcat(root_buffer, absolute_path_buffer);
			//printf("root!%s!\n", root);
			//printf("path!%s!\n", path);

            // TODO: ensure path exists
			if (access(path, F_OK) == -1)
            {
                stop();
            }
            
            // TODO: ensure path is readable
			if (access(path, R_OK) == -1)
            {
                stop();
            }
 
            // TODO: extract path's extension
            //char extension[] = "TODO";			
			char* ext_buffer =  strrchr(path, '.');			
			char extension[strlen(ext_buffer)];
            strncpy( extension, &ext_buffer[1], strlen(HTTP_version) );
            extension[strlen(HTTP_version)] = '\0';	

            // dynamic content
            if (strcasecmp("php", extension) == 0)
            {
                // open pipe to PHP interpreter
                char* format = "QUERY_STRING=\"%s\" REDIRECT_STATUS=200 SCRIPT_FILENAME=\"%s\" php-cgi";
                char command[strlen(format) + (strlen(path) - 2) + (strlen(query) - 2) + 1];
                sprintf(command, format, query, path);
                file = popen(command, "r");
                if (file == NULL)
                {
                    error(500);
                    continue;
                }

                // load file
                ssize_t size = load();
                if (size == -1)
                {
                    error(500);
                    continue;
                }

                // subtract php-cgi's headers from body's size to get content's length
                haystack = body;
                needle = memmem(haystack, size, "\r\n\r\n", 4);
                if (needle == NULL)
                {
                    error(500);
                    continue;
                }
                size_t length = size - (needle - haystack + 4);

                // respond to client
                if (dprintf(cfd, "HTTP/1.1 200 OK\r\n") < 0)
                {
                    continue;
                }
                if (dprintf(cfd, "Connection: close\r\n") < 0)
                {
                    continue;
                }
                if (dprintf(cfd, "Content-Length: %i\r\n", length) < 0)
                {
                    continue;
                }
                if (write(cfd, body, size) == -1)
                {
                    continue;
                }
            }

            // static content
            else
            {
                // look up file's MIME type
                const char* type = lookup(extension);
                if (type == NULL)
                {
                    error(501);
                    continue;
                }

                // open file
                file = fopen(path, "r");
                if (file == NULL)
                {
                    error(500);
                    continue;
                }

                // load file
                ssize_t length = load();
                if (length == -1)
                {
                    error(500);
                    continue;
                }

                // TODO: respond to client				
				if (dprintf(cfd, "HTTP/1.1 200 OK\r\n") < 0)
                {
                    continue;
                }
                if (dprintf(cfd, "Connection: close\r\n") < 0)
                {
                    continue;
                }
                if (dprintf(cfd, "Content-Length: %i\r\n", length) < 0)
                {
                    continue;
                }
                if (dprintf(cfd, "Content-Type: %s\r\n", type) < 0)
                {
                    continue;
                }
				// respond with CRLF
                if (dprintf(cfd, "\r\n") < 0)
                {
                    continue;
                }
				
				if (write(cfd, body, length) == -1)
                {
                     continue;
                }

                
				
            }
      
            // announce OK
            printf("\033[32m");
            printf("HTTP/1.1 200 OK");
            printf("\033[39m\n");
        }
    }
}
Exemplo n.º 2
0
Arquivo: unix.c Projeto: rdparker/core
void Unix_FindV6InterfaceInfo(void)
{
    FILE *pp = NULL;
    char buffer[CF_BUFSIZE];

/* Whatever the manuals might say, you cannot get IPV6
   interface configuration from the ioctls. This seems
   to be implemented in a non standard way across OSes
   BSDi has done getifaddrs(), solaris 8 has a new ioctl, Stevens
   book shows the suggestion which has not been implemented...
*/

    CfOut(cf_verbose, "", "Trying to locate my IPv6 address\n");

    switch (VSYSTEMHARDCLASS)
    {
    case cfnt:
        /* NT cannot do this */
        return;

    case irix:
    case irix4:
    case irix64:

        if ((pp = cf_popen("/usr/etc/ifconfig -a", "r")) == NULL)
        {
            CfOut(cf_verbose, "", "Could not find interface info\n");
            return;
        }

        break;

    case hp:

        if ((pp = cf_popen("/usr/sbin/ifconfig -a", "r")) == NULL)
        {
            CfOut(cf_verbose, "", "Could not find interface info\n");
            return;
        }

        break;

    case aix:

        if ((pp = cf_popen("/etc/ifconfig -a", "r")) == NULL)
        {
            CfOut(cf_verbose, "", "Could not find interface info\n");
            return;
        }

        break;

    default:

        if ((pp = cf_popen("/sbin/ifconfig -a", "r")) == NULL)
        {
            CfOut(cf_verbose, "", "Could not find interface info\n");
            return;
        }

    }

/* Don't know the output format of ifconfig on all these .. hope for the best*/

    while (!feof(pp))
    {
        fgets(buffer, CF_BUFSIZE - 1, pp);

        if (ferror(pp))         /* abortable */
        {
            break;
        }

        if (strcasestr(buffer, "inet6"))
        {
            Item *ip, *list = NULL;
            char *sp;

            list = SplitStringAsItemList(buffer, ' ');

            for (ip = list; ip != NULL; ip = ip->next)
            {
                for (sp = ip->name; *sp != '\0'; sp++)
                {
                    if (*sp == '/')     /* Remove CIDR mask */
                    {
                        *sp = '\0';
                    }
                }

                if (IsIPV6Address(ip->name) && (strcmp(ip->name, "::1") != 0))
                {
                    CfOut(cf_verbose, "", "Found IPv6 address %s\n", ip->name);
                    AppendItem(&IPADDRESSES, ip->name, "");
                    NewClass(ip->name);
                }
            }

            DeleteItemList(list);
        }
    }

    cf_pclose(pp);
}
Exemplo n.º 3
0
static int
scan_src_file_cb(const char *fpath,const struct stat *sb,
			int tflag,struct FTW *ftwbuf)
{
    //record file to list
	src_f_list *n_file = NULL,*n_file_old = NULL;
	int fd = -1;
	char *index_str = NULL;
	switch(tflag)
	{
	case FTW_D:
		break;
	case FTW_F:
		n_file = (src_f_list *)malloc(sizeof(src_f_list));
		bzero(n_file,sizeof(src_f_list));
		n_file->node = NULL;
		n_file->f_p_len = strlen(fpath) + 1;
		n_file->f_path = (char *)malloc(n_file->f_p_len);
		bzero(n_file->f_path,n_file->f_p_len);
		memcpy(n_file->f_path,fpath,n_file->f_p_len - 1);
		n_file->req_count = 0;
		n_file->f_size = (intmax_t)(sb->st_size);
		if(max_file_size < n_file->f_size)
			max_file_size = n_file->f_size;
		n_file->f_data = (uint8_t *)malloc(n_file->f_size);
		bzero(n_file->f_data,n_file->f_size);
		if((fd = open(fpath,O_RDONLY,0)) < 0) {
			perror("open");
			return -1;
		}
		read(fd,n_file->f_data,n_file->f_size);
		if(NULL == s_list) {
			s_list = n_file;
			regist_delete_call_back(s_list,s_list_free);
			regist_match_call_back(s_list,s_list_match);
		} else
			sl_node_insert_tail_absolute(s_list,n_file);
		//check the file if a index.html we ignore the case
		index_str = strcasestr(n_file->f_path,"/index.html");
		#define	INDEX_NAME_LEN 11
		if(NULL != index_str && index_str[INDEX_NAME_LEN] == '\0') {
			n_file_old = n_file;
			n_file = (src_f_list *)malloc(sizeof(src_f_list));
			bzero(n_file,sizeof(src_f_list));
			n_file->node = NULL;
			n_file->f_p_len = n_file_old->f_p_len - INDEX_NAME_LEN;
			n_file->f_path = (char *)malloc(n_file->f_p_len);
			bzero(n_file->f_path,n_file->f_p_len);
			memcpy(n_file->f_path,n_file_old->f_path,n_file->f_p_len - 1);
			n_file->req_count = n_file_old->req_count;
			n_file->f_size = n_file_old->f_size;
			n_file->f_data = (uint8_t *)malloc(n_file->f_size);
			bzero(n_file->f_data,n_file->f_size);
			memcpy(n_file->f_data,n_file_old->f_data,n_file->f_size);
			sl_node_insert_tail_absolute(s_list,n_file);
		}
		#undef	INDEX_NAME_LEN
		close(fd);
		break;
	case FTW_DNR:
		break;
	case FTW_NS:
		break;
	case FTW_SL:
		break;
	case FTW_SLN:
		break;
	default:
		break;
	}
	return 0;
}
Exemplo n.º 4
0
static int common_exec(struct ast_channel *chan, struct ast_flags *flags,
	int volfactor, const int fd, struct spy_dtmf_options *user_options,
	const char *mygroup, const char *myenforced, const char *spec, const char *exten,
	const char *context, const char *mailbox, const char *name_context)
{
	char nameprefix[AST_NAME_STRLEN];
	char exitcontext[AST_MAX_CONTEXT] = "";
	signed char zero_volume = 0;
	int waitms;
	int res;
	int num_spyed_upon = 1;
	struct ast_channel_iterator *iter = NULL;

	if (ast_test_flag(flags, OPTION_EXIT)) {
		const char *c;
		ast_channel_lock(chan);
		if ((c = pbx_builtin_getvar_helper(chan, "SPY_EXIT_CONTEXT"))) {
			ast_copy_string(exitcontext, c, sizeof(exitcontext));
		} else if (!ast_strlen_zero(ast_channel_macrocontext(chan))) {
			ast_copy_string(exitcontext, ast_channel_macrocontext(chan), sizeof(exitcontext));
		} else {
			ast_copy_string(exitcontext, ast_channel_context(chan), sizeof(exitcontext));
		}
		ast_channel_unlock(chan);
	}

	if (ast_channel_state(chan) != AST_STATE_UP)
		ast_answer(chan);

	ast_set_flag(ast_channel_flags(chan), AST_FLAG_SPYING); /* so nobody can spy on us while we are spying */

	waitms = 100;

	for (;;) {
		struct ast_autochan *autochan = NULL, *next_autochan = NULL;
		struct ast_channel *prev = NULL;

		if (!ast_test_flag(flags, OPTION_QUIET) && num_spyed_upon) {
			res = ast_streamfile(chan, "beep", ast_channel_language(chan));
			if (!res)
				res = ast_waitstream(chan, "");
			else if (res < 0) {
				ast_clear_flag(ast_channel_flags(chan), AST_FLAG_SPYING);
				break;
			}
			if (!ast_strlen_zero(exitcontext)) {
				char tmp[2];
				tmp[0] = res;
				tmp[1] = '\0';
				if (!ast_goto_if_exists(chan, exitcontext, tmp, 1))
					goto exit;
				else
					ast_debug(2, "Exit by single digit did not work in chanspy. Extension %s does not exist in context %s\n", tmp, exitcontext);
			}
		}

		/* Set up the iterator we'll be using during this call */
		if (!ast_strlen_zero(spec)) {
			iter = ast_channel_iterator_by_name_new(spec, strlen(spec));
		} else if (!ast_strlen_zero(exten)) {
			iter = ast_channel_iterator_by_exten_new(exten, context);
		} else {
			iter = ast_channel_iterator_all_new();
		}

		if (!iter) {
			res = -1;
			goto exit;
		}

		res = ast_waitfordigit(chan, waitms);
		if (res < 0) {
			iter = ast_channel_iterator_destroy(iter);
			ast_clear_flag(ast_channel_flags(chan), AST_FLAG_SPYING);
			break;
		}
		if (!ast_strlen_zero(exitcontext)) {
			char tmp[2];
			tmp[0] = res;
			tmp[1] = '\0';
			if (!ast_goto_if_exists(chan, exitcontext, tmp, 1)) {
				iter = ast_channel_iterator_destroy(iter);
				goto exit;
			} else {
				ast_debug(2, "Exit by single digit did not work in chanspy. Extension %s does not exist in context %s\n", tmp, exitcontext);
			}
		}

		/* reset for the next loop around, unless overridden later */
		waitms = 100;
		num_spyed_upon = 0;

		for (autochan = next_channel(iter, autochan, chan);
		     autochan;
			 prev = autochan->chan, ast_autochan_destroy(autochan),
		     autochan = next_autochan ? next_autochan : 
				next_channel(iter, autochan, chan), next_autochan = NULL) {
			int igrp = !mygroup;
			int ienf = !myenforced;

			if (autochan->chan == prev) {
				ast_autochan_destroy(autochan);
				break;
			}

			if (ast_check_hangup(chan)) {
				ast_autochan_destroy(autochan);
				break;
			}

			if (ast_test_flag(flags, OPTION_BRIDGED) && !ast_bridged_channel(autochan->chan)) {
				continue;
			}

			if (ast_check_hangup(autochan->chan) || ast_test_flag(ast_channel_flags(autochan->chan), AST_FLAG_SPYING)) {
				continue;
			}

			if (mygroup) {
				int num_groups = 0;
				int num_mygroups = 0;
				char dup_group[512];
				char dup_mygroup[512];
				char *groups[NUM_SPYGROUPS];
				char *mygroups[NUM_SPYGROUPS];
				const char *group = NULL;
				int x;
				int y;
				ast_copy_string(dup_mygroup, mygroup, sizeof(dup_mygroup));
				num_mygroups = ast_app_separate_args(dup_mygroup, ':', mygroups,
					ARRAY_LEN(mygroups));

				/* Before dahdi scan was part of chanspy, it would use the "GROUP" variable 
				 * rather than "SPYGROUP", this check is done to preserve expected behavior */
				if (ast_test_flag(flags, OPTION_DAHDI_SCAN)) {
					group = pbx_builtin_getvar_helper(autochan->chan, "GROUP");
				} else {
					group = pbx_builtin_getvar_helper(autochan->chan, "SPYGROUP");
				}

				if (!ast_strlen_zero(group)) {
					ast_copy_string(dup_group, group, sizeof(dup_group));
					num_groups = ast_app_separate_args(dup_group, ':', groups,
						ARRAY_LEN(groups));
				}

				for (y = 0; y < num_mygroups; y++) {
					for (x = 0; x < num_groups; x++) {
						if (!strcmp(mygroups[y], groups[x])) {
							igrp = 1;
							break;
						}
					}
				}
			}

			if (!igrp) {
				continue;
			}
			if (myenforced) {
				char ext[AST_CHANNEL_NAME + 3];
				char buffer[512];
				char *end;

				snprintf(buffer, sizeof(buffer) - 1, ":%s:", myenforced);

				ast_copy_string(ext + 1, ast_channel_name(autochan->chan), sizeof(ext) - 1);
				if ((end = strchr(ext, '-'))) {
					*end++ = ':';
					*end = '\0';
				}

				ext[0] = ':';

				if (strcasestr(buffer, ext)) {
					ienf = 1;
				}
			}

			if (!ienf) {
				continue;
			}

			if (!ast_test_flag(flags, OPTION_QUIET)) {
				char peer_name[AST_NAME_STRLEN + 5];
				char *ptr, *s;

				strcpy(peer_name, "spy-");
				strncat(peer_name, ast_channel_name(autochan->chan), AST_NAME_STRLEN - 4 - 1);
				if ((ptr = strchr(peer_name, '/'))) {
					*ptr++ = '\0';
					for (s = peer_name; s < ptr; s++) {
						*s = tolower(*s);
					}
					if ((s = strchr(ptr, '-'))) {
						*s = '\0';
					}
				}

				if (ast_test_flag(flags, OPTION_NAME)) {
					const char *local_context = S_OR(name_context, "default");
					const char *local_mailbox = S_OR(mailbox, ptr);
					if (local_mailbox) {
						res = ast_app_sayname(chan, local_mailbox, local_context);
					} else {
						res = -1;
					}
				}
				if (!ast_test_flag(flags, OPTION_NAME) || res < 0) {
					int num;
					if (!ast_test_flag(flags, OPTION_NOTECH)) {
						if (ast_fileexists(peer_name, NULL, NULL) > 0) {
							res = ast_streamfile(chan, peer_name, ast_channel_language(chan));
							if (!res) {
								res = ast_waitstream(chan, "");
							}
							if (res) {
								ast_autochan_destroy(autochan);
								break;
							}
						} else {
							res = ast_say_character_str(chan, peer_name, "", ast_channel_language(chan));
						}
					}
					if (ptr && (num = atoi(ptr))) {
						ast_say_digits(chan, num, "", ast_channel_language(chan));
					}
				}
			}

			res = channel_spy(chan, autochan, &volfactor, fd, user_options, flags, exitcontext);
			num_spyed_upon++;

			if (res == -1) {
				ast_autochan_destroy(autochan);
				iter = ast_channel_iterator_destroy(iter);
				goto exit;
			} else if (res == -2) {
				res = 0;
				ast_autochan_destroy(autochan);
				iter = ast_channel_iterator_destroy(iter);
				goto exit;
			} else if (res > 1 && spec) {
				struct ast_channel *next;

				snprintf(nameprefix, AST_NAME_STRLEN, "%s/%d", spec, res);

				if ((next = ast_channel_get_by_name_prefix(nameprefix, strlen(nameprefix)))) {
					next_autochan = ast_autochan_setup(next);
					next = ast_channel_unref(next);
				} else {
					/* stay on this channel, if it is still valid */
					if (!ast_check_hangup(autochan->chan)) {
						next_autochan = ast_autochan_setup(autochan->chan);
					} else {
						/* the channel is gone */
						next_autochan = NULL;
					}
				}
			} else if (res == 0 && ast_test_flag(flags, OPTION_EXITONHANGUP)) {
				ast_autochan_destroy(autochan);
				iter = ast_channel_iterator_destroy(iter);
				goto exit;
			}
		}

		iter = ast_channel_iterator_destroy(iter);

		if (res == -1 || ast_check_hangup(chan))
			break;
		if (ast_test_flag(flags, OPTION_STOP) && !next_autochan) {
			break;
		}
	}
exit:

	ast_clear_flag(ast_channel_flags(chan), AST_FLAG_SPYING);

	ast_channel_setoption(chan, AST_OPTION_TXGAIN, &zero_volume, sizeof(zero_volume), 0);

	return res;
}
Exemplo n.º 5
0
static int frame_trace_helper(struct ast_channel *chan, const char *cmd, char *data, const char *value)
{
	struct frame_trace_data *framedata;
	struct ast_datastore *datastore = NULL;
	struct ast_framehook_interface interface = {
		.version = AST_FRAMEHOOK_INTERFACE_VERSION,
		.event_cb = hook_event_cb,
		.destroy_cb = hook_destroy_cb,
	};
	int i = 0;

	if (!chan) {
		ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
		return -1;
	}

	if (!(framedata = ast_calloc(1, sizeof(*framedata)))) {
		return 0;
	}

	interface.data = framedata;

	if (!strcasecmp(data, "black")) {
		framedata->list_type = 1;
	}
	for (i = 0; i < ARRAY_LEN(frametype2str); i++) {
		if (strcasestr(value, frametype2str[i].str)) {
			framedata->values[i] = 1;
		}
	}

	ast_channel_lock(chan);
	i = ast_framehook_attach(chan, &interface);
	if (i >= 0) {
		int *id;
		if ((datastore = ast_channel_datastore_find(chan, &frame_trace_datastore, NULL))) {
			id = datastore->data;
			ast_framehook_detach(chan, *id);
			ast_channel_datastore_remove(chan, datastore);
			ast_datastore_free(datastore);
		}

		if (!(datastore = ast_datastore_alloc(&frame_trace_datastore, NULL))) {
			ast_framehook_detach(chan, i);
			ast_channel_unlock(chan);
			return 0;
		}

		if (!(id = ast_calloc(1, sizeof(int)))) {
			ast_datastore_free(datastore);
			ast_framehook_detach(chan, i);
			ast_channel_unlock(chan);
			return 0;
		}

		*id = i; /* Store off the id. The channel is still locked so it is safe to access this ptr. */
		datastore->data = id;
		ast_channel_datastore_add(chan, datastore);
	}
	ast_channel_unlock(chan);

	return 0;
}
Exemplo n.º 6
0
Arquivo: xim.c Projeto: areslp/fcitx
void* XimCreate(FcitxInstance* instance, int frontendid)
{
    if (ximfrontend != NULL)
        return NULL;
    FcitxXimFrontend* xim = fcitx_utils_malloc0(sizeof(FcitxXimFrontend));
    if (xim == NULL)
        return NULL;

    ximfrontend = xim;

    XIMStyles *input_styles;
    XIMEncodings *encodings;
    char *imname = NULL;
    char *p;

    xim->display = InvokeVaArgs(instance, FCITX_X11, GETDISPLAY);

    if (xim->display == NULL) {
        FcitxLog(FATAL, _("X11 not initialized"));
        free(xim);
        return NULL;
    }

    FcitxAddon* ximaddon = FcitxAddonsGetAddonByName(FcitxInstanceGetAddons(instance), "fcitx-xim");
    xim->x11addon = FcitxAddonsGetAddonByName(FcitxInstanceGetAddons(instance), "fcitx-x11");
    xim->iScreen = DefaultScreen(xim->display);
    xim->owner = instance;
    xim->frontendid = frontendid;

    xim->ximWindow = XCreateSimpleWindow(xim->display, DefaultRootWindow(xim->display), 0, 0, 1, 1, 1, 0, 0);
    if (xim->ximWindow == (Window) NULL) {
        FcitxLog(FATAL, _("Can't Create imWindow"));
        free(xim);
        return NULL;
    }

    if (!imname) {
        imname = getenv("XMODIFIERS");
        if (imname) {
            if (strstr(imname, "@im="))
                imname += 4;
            else {
                FcitxLog(WARNING, _("XMODIFIERS Error."));
                imname = DEFAULT_IMNAME;
            }
        } else {
            FcitxLog(WARNING, _("Please set XMODIFIERS."));
            imname = DEFAULT_IMNAME;
        }
    }
    XimQueueInit(xim);

    if (GetXimConfigDesc() == NULL)
        xim->bUseOnTheSpotStyle = false;
    else {
        FcitxConfigFileDesc* configDesc = GetXimConfigDesc();

        FILE *fp;
        char *file;
        fp = FcitxXDGGetFileUserWithPrefix("conf", "fcitx-xim.config", "r", &file);
        FcitxLog(DEBUG, "Load Config File %s", file);
        free(file);
        if (!fp) {
            if (errno == ENOENT) {
                char *file;
                FILE *fp2 = FcitxXDGGetFileUserWithPrefix("conf", "fcitx-xim.config", "w", &file);
                FcitxLog(DEBUG, "Save Config to %s", file);
                FcitxConfigSaveConfigFileFp(fp2, &xim->gconfig, configDesc);
                free(file);
                if (fp2)
                    fclose(fp2);
            }
        }

        FcitxConfigFile *cfile = FcitxConfigParseConfigFileFp(fp, configDesc);

        FcitxXimFrontendConfigBind(xim, cfile, configDesc);
        FcitxConfigBindSync((FcitxGenericConfig*)xim);

        if (fp)
            fclose(fp);
    }

    input_styles = (XIMStyles *) malloc(sizeof(XIMStyles));
    if (xim->bUseOnTheSpotStyle) {
        input_styles->count_styles = sizeof(OnTheSpot_Styles) / sizeof(XIMStyle) - 1;
        input_styles->supported_styles = OnTheSpot_Styles;
    } else {
        input_styles->count_styles = sizeof(OverTheSpot_Styles) / sizeof(XIMStyle) - 1;
        input_styles->supported_styles = OverTheSpot_Styles;
    }

    encodings = (XIMEncodings *) malloc(sizeof(XIMEncodings));
    encodings->count_encodings = sizeof(zhEncodings) / sizeof(XIMEncoding) - 1;
    encodings->supported_encodings = zhEncodings;

    p = getenv("LC_CTYPE");
    if (!p) {
        p = getenv("LC_ALL");
        if (!p)
            p = getenv("LANG");
    }
    if (p) {
        if (!strcasestr(strLocale, p)) {
            strcat(strLocale, ",");
            strcat(strLocale, p);
        }
    }

    xim->ims = IMOpenIM(xim->display,
                        IMModifiers, "Xi18n",
                        IMServerWindow, xim->ximWindow,
                        IMServerName, imname,
                        IMLocale, strLocale,
                        IMServerTransport, "X/",
                        IMInputStyles, input_styles,
                        IMEncodingList, encodings,
                        IMProtocolHandler, XimProtocolHandler,
                        IMFilterEventMask, KeyPressMask | KeyReleaseMask,
                        NULL);

    free(input_styles);
    free(encodings);

    if (xim->ims == (XIMS) NULL) {
        FcitxLog(ERROR, _("Start XIM error. Another XIM daemon named %s is running?"), imname);
        free(xim);
        FcitxInstanceEnd(instance);
        return NULL;
    }

    FcitxModuleAddFunction(ximaddon, XimConsumeQueue);

    return xim;
}
Exemplo n.º 7
0
int main (int argc, char** argv) {

  struct option cmd_options[] = {{"help", 0, NULL, CMD_HELP},
                                 {"version", 0, NULL, CMD_VERSION},
                                 {"jp4", 0, NULL, CMD_JP4},
                                 {"jpeg", 0, NULL, CMD_JPEG},
                                 {"dng", 0, NULL, CMD_DNG},
                                 {"pgm", 0, NULL, CMD_PGM},
                                 {"stdout", 0, NULL, CMD_STDOUT},
                                 {"gui", 0, NULL, CMD_GUI},
                                 {"frames", 1, NULL, CMD_N_FRAMES},
                                 {"shift", 1, NULL, CMD_BAYER_SHIFT},
                                 {"jpeg-quality", 1, NULL, CMD_JPEG_QUALITY},
                                 {"no-dng-rotation", 0, NULL, CMD_DISABLE_DNG_ROTATION},
                                 {0, 0, 0, 0}};
  int option = 0;
  int option_index;

  bool save_jp4 = false;
  bool save_dng = false;
  bool save_pgm = false;
  bool save_jpeg = false;
  bool disable_dng_rotations = false;

  bool save_to_stdout = false;

  bool gui = false;
  long int n_frames = 0;
  int bayer_shift = -1;
  unsigned int jpeg_quality = 100;

  opterr = 0;

  while ((option = getopt_long(argc, argv, "hv", cmd_options, &option_index)) != -1) {
    switch (option) {
    case CMD_HELP:
      help(argv[0]);
      exit(0);
    case CMD_VERSION:
      version(argv[0]);
      exit(0);
    case CMD_JP4:
      save_jp4 = true;
      break;
    case CMD_JPEG:
      save_jpeg = true;
      break;
    case CMD_JPEG_QUALITY:
      jpeg_quality = atoi(optarg);
      if (jpeg_quality < 1 || jpeg_quality > 100) {
        fprintf(stderr, "Wrong JPEG quality factor, should be between 1 and 100.\n");
        exit(1);
      }
      break;
    case CMD_DISABLE_DNG_ROTATION:
      disable_dng_rotations = true;
      break;
    case CMD_DNG:
      save_dng = true;
      break;
    case CMD_PGM:
      save_pgm = true;
      break;
    case CMD_STDOUT:
      save_to_stdout = true;
      break;
    case CMD_GUI:
      gui = true;
      break;
    case CMD_N_FRAMES:
      n_frames = atoi(optarg);
      break;
    case CMD_BAYER_SHIFT:
      bayer_shift = atoi(optarg);
      if (bayer_shift < 0 || bayer_shift > 3) {
        fprintf(stderr, "Ivalid shift mode, shift=[0-3]\n");
        exit(1);
      }
      break;
    default:
      printf("Unknown option.\n\n");
      help(argv[0]);
      exit(1);
    }
  }

  if (argc-optind < 1) {
   help(argv[0]);
   exit(1);
  }

  if (!save_dng && !save_jp4 && !save_pgm && !save_jpeg) {
   help(argv[0]);
   exit(1);
  }

  // Check if sourceFilename is a movie or a single frame
  char* sourceFilename = argv[optind];

  const char* is_jp4 = strcasestr(sourceFilename, ".jp4");
  const char* is_jp46 = strcasestr(sourceFilename, ".jp46");
  bool is_stdin = strcmp(sourceFilename, "-") == 0;

  char frameName[_POSIX_PATH_MAX];

  int n_args = argc-optind;

  if (n_args == 1 && !(is_jp4 || is_jp46) && !save_to_stdout) {
    // use sourceFilename without extension as frame name
    strncpy(frameName, sourceFilename, _POSIX_PATH_MAX);

    char* ext = strrchr(frameName, '.');
    // cut string at extension point
    if (ext) *ext=0;

    char basenameCopy[_POSIX_PATH_MAX];
    strncpy(basenameCopy, frameName, _POSIX_PATH_MAX);
    char* frameFilename = basename(basenameCopy);

    strcat(frameName, "/");
    DIR* dstDir = opendir(frameName);
    if (!dstDir) {
      int res = mkdir(frameName, 0777);
      if (res != 0) {
        fprintf(stderr, "Could not create output directory '%s' (%s).", frameName, strerror(errno));
        exit(1);
      }
    }

    strcat(frameName, frameFilename);

  } else if (n_args >= 2) {
    strncpy(frameName, argv[optind+1], _POSIX_PATH_MAX);
  }

  char jp4FilenameFmt[_POSIX_PATH_MAX];
  char jpegFilenameFmt[_POSIX_PATH_MAX];
  char dngFilenameFmt[_POSIX_PATH_MAX];
  char pgmFilenameFmt[_POSIX_PATH_MAX];

  snprintf(jp4FilenameFmt, _POSIX_PATH_MAX, "%s-%%06d.jp4", frameName);
  snprintf(jpegFilenameFmt, _POSIX_PATH_MAX, "%s-%%06d.jpeg", frameName);
  snprintf(dngFilenameFmt, _POSIX_PATH_MAX, "%s-%%06d.dng", frameName);
  snprintf(pgmFilenameFmt, _POSIX_PATH_MAX, "%s-%%06d.pgm", frameName);

  char jp4Filename[_POSIX_PATH_MAX];
  char jpegFilename[_POSIX_PATH_MAX];
  char dngFilename[_POSIX_PATH_MAX];
  char pgmFilename[_POSIX_PATH_MAX];

  if (is_jp4 || is_jp46 || is_stdin) {

    if ((save_dng && save_pgm) || (save_dng && save_jpeg) || (save_pgm && save_jpeg)) {
        fprintf(stderr, "Cannot choose --stdout and multiple output formats.\n");
        exit(1);
      }

      if (is_stdin)
        snprintf(sourceFilename, _POSIX_PATH_MAX, "/dev/stdin");

      strncpy(jp4Filename, sourceFilename, _POSIX_PATH_MAX);

      char* ext = strrchr(sourceFilename, '.');
      // cut string at extension point
      if (ext) *ext=0;

      if (save_to_stdout) {
        snprintf(jpegFilename,_POSIX_PATH_MAX, "/dev/stdout");
        snprintf(dngFilename, _POSIX_PATH_MAX, "/dev/stdout");
        snprintf(pgmFilename, _POSIX_PATH_MAX, "/dev/stdout");
      } else {
        snprintf(jpegFilename, _POSIX_PATH_MAX, "%s.jpeg", sourceFilename);
        snprintf(dngFilename, _POSIX_PATH_MAX, "%s.dng", sourceFilename);
        snprintf(pgmFilename, _POSIX_PATH_MAX, "%s.pgm", sourceFilename);
      }

      JP4 jp4;
      jp4.open(jp4Filename);

      if (save_dng)
        DNGWriter::write(jp4, dngFilename, bayer_shift, disable_dng_rotations);

      if (save_pgm)
        jp4.writePGM(pgmFilename);

      if (save_jpeg)
        jp4.writeJPEG(jpegFilename, jpeg_quality);

  } else {

    Movie movie;

    if (!movie.open(sourceFilename))
      exit(1);

    // number of frames to convert
    n_frames = n_frames? n_frames: movie.nFrames();

    if (gui)
      fprintf(stdout, "%ld\n", n_frames);
    else
      fprintf(stdout, "#frames: %ld\n", n_frames);
    fflush(stdout);

    unsigned int frame = 0;
    void* frameData = NULL;
    unsigned int frameSize = 0;

    MovieIterator it(&movie, 1, n_frames);

    while (it.hasNext()) {

      it.next(&frame, &frameData, &frameSize);

      snprintf(jp4Filename, _POSIX_PATH_MAX, jp4FilenameFmt, frame);
      snprintf(jpegFilename, _POSIX_PATH_MAX, jpegFilenameFmt, frame);
      snprintf(dngFilename, _POSIX_PATH_MAX, dngFilenameFmt, frame);
      snprintf(pgmFilename, _POSIX_PATH_MAX, pgmFilenameFmt, frame);

      FILE* fd = fopen(jp4Filename, "w");
      if (fd == NULL) {
        fprintf(stderr, "ERROR: Could not open %s for writing. Aborting...\n", jp4Filename);
        return -3;
      }

      fwrite(frameData, frameSize, 1, fd);
      fclose(fd);

      JP4 jp4;
      jp4.open(jp4Filename);

      // convert to DNG
      if (save_dng)
        DNGWriter::write(jp4, dngFilename, bayer_shift, disable_dng_rotations);

      if (save_pgm)
        jp4.writePGM(pgmFilename);

      if (save_jpeg)
        jp4.writeJPEG(jpegFilename, jpeg_quality);

      // remove temporary jp4 file
      if (!save_jp4)
        unlink(jp4Filename);

      if (gui)
        fprintf(stdout, "%d\n", frame);
      else
        fprintf(stdout, "Converting frame %d...\r", frame);
      fflush(stdout);

      frame++;
    }

    fprintf(stdout, "\n");

  }

  return 0;

}
Exemplo n.º 8
0
int lhttpd_packet_handler(CONN *conn, CB_DATA *packet)
{
    char *s = NULL, *end = NULL, *p = NULL, 
         path[HTTP_PATH_MAX], line[HTTP_LINE_MAX];
    int high = 0, low = 0, keepalive = 0;
    struct stat st;

	if(conn)
    {
        if(packet && (s = packet->data) && packet->ndata > 0)
        {
            return conn->push_file(conn, "/tmp/x.txt", 0, 2272);
            end = s + packet->ndata;
            while(*s == 0x20 || *s == '\t')s++;
            if(s < end && strncasecmp(s, "get", 3) == 0)
            {
                s += 3;        
                while(*s == 0x20 || *s == '\t')s++;
                if(*s != '/') goto err;
                p = path;
                p += sprintf(path, "%s", httpd_home);
                while(s < end && *s != 0x20 && *s != '\t' 
                        && *s != '?' && *s != '#' 
                        && p < (path + HTTP_PATH_MAX))
                {
                    URLDECODE(s, end, high, low, p);
                }
                *p = '\0';
                if(s < end && strcasestr(s, "Keep-Alive"))keepalive = 1;
                if(stat(path, &st) != 0) goto not_found;
                if(S_ISDIR(st.st_mode))
                {
                    if(*(p-1) == '/')
                        p += sprintf(p, "index.html");
                    else
                        p += sprintf(p, "/index.html");
                    if(stat(path, &st) != 0) goto not_found;
                }
                if(S_ISREG(st.st_mode) && st.st_size > 0)
                {
                    p = line;
                    p += sprintf(p, "HTTP/1.0 200 OK\r\nContent-Length: %lld\r\n"
                            "Last-Modified:", LL(st.st_size));
                    p += GMTstrdate(st.st_mtime, p);p += sprintf(p, "%s", "\r\n");
                    p += sprintf(p, "Date: ");p += GMTstrdate(time(NULL), p);
                    p += sprintf(p, "\r\n");
                    if(keepalive) p += sprintf(p, "Connection: Keep-Alive\r\n");
                    else p += sprintf(p, "Connection: close\r\n");
                    p += sprintf(p, "Server: lhttpd/%s\r\n\r\n", LHTTPD_VERSION);
                    conn->push_chunk(conn, line, (p - line));
                    conn->push_file(conn, path, 0, st.st_size);
                    if(keepalive) 
                        conn->set_timeout(conn, HTTP_TIMEOUT);
                    else
                        conn->over(conn);
                    return 0;
                }
                else
                {
                    conn->push_chunk(conn, HTTP_FORBIDDEN, strlen(HTTP_FORBIDDEN));
                    return conn->over(conn);
                }
            }
        }
err:
        conn->push_chunk(conn, HTTP_BAD_REQUEST, strlen(HTTP_BAD_REQUEST));
        return conn->over(conn);
not_found:
        conn->push_chunk(conn, HTTP_NOT_FOUND, strlen(HTTP_NOT_FOUND));
        return conn->over(conn);
    }
    return -1;
}
Exemplo n.º 9
0
Arquivo: main.c Projeto: tm512/ispolin
void linktitle (ircclient_t *cl, char *nick, char *host, char *source, char *message)
{
	char *buf, *link, *ttag;
	CURL *c;

	if (source [0] != '#')
		return; // Do not reply to links through private message

	buf = alloca (strlen (message) + 1);
	strncpy (buf, message, strlen (message) + 1); // We don't want to mess up the original

	while (strstr (buf, "http://") || strstr (buf, "https://"))
	{
		// Allocate head and body buffers
		head.data = malloc (1);
		body.data = malloc (1);
		head.len = body.len = 0;

		if (!(link = strstr (buf, "http://"))) // see if we need https
			link = strstr (buf, "https://");

		if (strstr (link, " "))
			strstr (link, " ") [0] = '\0'; // terminate the string at the end of the link

		// Get HEAD of the http request
		c = curl_easy_init ();
		curl_easy_setopt (c, CURLOPT_URL, link);
		curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, writedata);
		curl_easy_setopt (c, CURLOPT_WRITEHEADER, (void*) &head);
		curl_easy_setopt (c, CURLOPT_WRITEDATA, (void*) &body);
		curl_easy_setopt (c, CURLOPT_NOBODY, 1);
		curl_easy_setopt (c, CURLOPT_TIMEOUT, 5);
		curl_easy_setopt (c, CURLOPT_FOLLOWLOCATION, 1);
		curl_easy_perform (c);

		if (!strstr (head.data, "Content-Type: text/html"))
		{
			curl_easy_cleanup (c);
			free (head.data);
			free (body.data);
			return; // According to the web server, this is not an HTML file
		}

		// Get the body of the http request
		curl_easy_setopt (c, CURLOPT_HTTPGET, 1);
		curl_easy_setopt (c, CURLOPT_WRITEHEADER, NULL);
		curl_easy_perform (c);
		curl_easy_cleanup (c);

		// Finally extract the title from the body, if possible
		ttag = strcasestr (body.data, "<title>");

		if (ttag)
		{
			get_title (&link, &ttag);
			irc_privmsg (cl, source, "link title: %s (at %s)", ttag, link);
		}

		free (head.data);
		free (body.data);

		buf = strstr (link + strlen (link) + 1, "\0") + 1;
	}

	return;
}
Exemplo n.º 10
0
int PASCAL WinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/,
				   LPSTR lpCmdLine, int nCmdShow)
{
	ModelLoader* modelLoader;
	bool screenSaver = isScreenSaver();
	int retValue;
	STARTUPINFO startupInfo;
	bool fromConsole = false;

	//HMODULE hThumbs = LoadLibrary("LDViewThumbs.dll");
	//if (hThumbs != NULL)
	//{
	//	PFNDLLREGISTERSERVER pDllRegisterServer =
	//		(PFNDLLREGISTERSERVER)GetProcAddress(hThumbs, "DllRegisterServer");

	//	CoInitialize(NULL);
	//	if (pDllRegisterServer != NULL)
	//	{
	//		pDllRegisterServer();
	//	}
	//}
	memset(&startupInfo, 0, sizeof(startupInfo));
	startupInfo.cb = sizeof(startupInfo);
	GetStartupInfo(&startupInfo);
	if (startupInfo.lpTitle != NULL &&
		stringHasCaseInsensitivePrefix(startupInfo.lpTitle, "command line ")
		&& strcasestr(startupInfo.lpTitle, "ldview") != NULL)
	{
		runningWithConsole();
		fromConsole = true;
	}
#ifdef _DEBUG
	int _debugFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
	_debugFlag |= _CRTDBG_LEAK_CHECK_DF;
	_CrtSetDbgFlag(_debugFlag);
	_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG);
	if (!fromConsole)
	{
		createConsole();
	}
//	MessageBox(NULL, "Attach a debugger now...", "Debug", MB_OK);
#endif // _DEBUG
	bool udok = setupUserDefaults(lpCmdLine, screenSaver,
		isRemovableDrive(hInstance));
	setupLocalStrings();
	if (TCUserDefaults::boolForKey(DEBUG_COMMAND_LINE_KEY, false, false))
	{
		std::string message = "Command Line:\n";

		message += lpCmdLine;
		MessageBox(NULL, message.c_str(), "LDView", MB_OK);
	}
	if (!udok && !TCUserDefaults::longForKey("IniFailureShown", 0, 0))
	{
		UCCHAR message[2048];
		UCSTR iniPath = mbstoucstring(TCUserDefaults::getIniPath());

		sucprintf(message, COUNT_OF(message),
			TCLocalStrings::get(_UC("IniFailure")), iniPath);
		CUIWindow::messageBoxUC(NULL, message, _UC("LDView"), MB_OK);
		delete iniPath;
		TCUserDefaults::setLongForKey(1, "IniFailureShown", false);
	}
	if (screenSaver)
	{
		if (strncasecmp(lpCmdLine, "/p", 2) == 0 ||
			strncasecmp(lpCmdLine, "-p", 2) == 0 ||
			strncasecmp(lpCmdLine, "p", 1) == 0)
		{
			// preview mode
			return doPreview(hInstance, lpCmdLine);
		}
		if (strncasecmp(lpCmdLine, "/c", 2) == 0 ||
			strncasecmp(lpCmdLine, "-c", 2) == 0 ||
			strncasecmp(lpCmdLine, "c", 1) == 0 ||
			strlen(lpCmdLine) == 0)
		{
			SSConfigure *configure;

			configure = new SSConfigure(hInstance);
#ifdef _DEBUG
			_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG);
			createConsole();
#endif // _DEBUG
			configure->run();
			// configure mode
			return 1;
		}
		// This shouldn't be necessary, but I've received a report of a whole
		// bunch of copies of the LDView screensaver running at once.  This
		// might not fix things entirely, but it will at least prevent it
		// from launching multiple times concurrently.
		CreateMutex(NULL, FALSE, "LDView Screensaver");
		if (GetLastError() == ERROR_ALREADY_EXISTS)
		{
			return 0;
		}
	}
#ifdef _LOG_PERFORMANCE
	LARGE_INTEGER frequency;
	if (QueryPerformanceFrequency(&frequency))
	{
		debugPrintf("Frequency: %I64d\n", frequency.QuadPart);
	}
#endif // _LOG_PERFORMANCE
	OleInitialize(NULL);

	//Win7JumpListStuff();

	modelLoader = new ModelLoader(CUIWindow::getLanguageModule(), nCmdShow,
		screenSaver);
	retValue = mainLoop();
	modelLoader->release();
	return retValue;
} // WinMain
Exemplo n.º 11
0
static Boolean
search(char *const query)
{
    const config_t *conf = config();

    Boolean resp = True;
    results_not_found = True;

    if (query_len < conf->section_main->min_query_len) {
        return False;
    }

    if (query[0] == ' ')
        return False;

    GQueue *cache = get_cache();

    int current_query_len = 1;
    str_array_t *query_parts = NULL;

    if (conf->section_main->allow_spaces) {
        query_parts = str_array_new(strdup(query), " ");

        if (
            (query_len > 0 && query[query_len - 1] == ' ')
            || query_parts == NULL
        ) {
            resp = False;
            goto free_query_parts;
        }

        current_query_len = query_parts->length;
    }

    g_list_free(results);
    results = NULL;

    for (int i = 0; i < g_queue_get_length(cache); i++) {
        char *path = g_queue_peek_nth(cache, i);
        Boolean found = True;

        if (current_query_len == 1) {
            char *name = g_path_get_basename(path);

            if (strcasestr(name, query) != NULL) {
                results = g_list_prepend(results, path);
            }

            free(name);
        } else if (current_query_len > 1) {
            for (int i = 0; i < current_query_len; i++) {
                if (strcmp(query_parts->data[i], " ") == 0)
                    continue;

                char *name = g_path_get_basename(
                    path
                );

                if (strstr(name, query_parts->data[i]) == NULL) {
                    found = False;
                    goto finish;
                }

            finish:
                free(name);

                if (! found)
                    break;
            }

            if (found)
                results = g_list_prepend(results, path);
        }
    }

    results_not_found = (g_list_length(results) > 0 ? False : True);

    recent_apps_on_top();

free_query_parts:
    str_array_free(query_parts);

    return resp;
}
Exemplo n.º 12
0
static int Android_ParseFamily( filter_t *p_filter, xml_reader_t *p_xml )
{
    filter_sys_t     *p_sys       = p_filter->p_sys;
    vlc_dictionary_t *p_dict      = &p_sys->family_map;
    vlc_family_t     *p_family    = NULL;
    char             *psz_lc      = NULL;
    int               i_counter   = 0;
    bool              b_bold      = false;
    bool              b_italic    = false;
    const char       *p_node      = NULL;
    int               i_type      = 0;

    while( ( i_type = xml_ReaderNextNode( p_xml, &p_node ) ) > 0 )
    {
        switch( i_type )
        {
        case XML_READER_STARTELEM:
            /*
             * Multiple names can reference the same family in Android. When
             * the first name is encountered we set p_family to the vlc_family_t
             * in the master list matching this name, and if no such family
             * exists we create a new one and add it to the master list.
             * If the master list does contain a family with that name it's one
             * of the font attachments, and the family will end up having embedded
             * fonts and system fonts.
             */
            if( !strcasecmp( "name", p_node ) )
            {
                i_type = xml_ReaderNextNode( p_xml, &p_node );

                if( i_type != XML_READER_TEXT || !p_node || !*p_node )
                {
                    msg_Warn( p_filter, "Android_ParseFamily: empty name" );
                    continue;
                }

                psz_lc = ToLower( p_node );
                if( unlikely( !psz_lc ) )
                    return VLC_ENOMEM;

                if( !p_family )
                {
                    p_family = vlc_dictionary_value_for_key( p_dict, psz_lc );
                    if( p_family == kVLCDictionaryNotFound )
                    {
                        p_family =
                            NewFamily( p_filter, psz_lc, &p_sys->p_families, NULL, NULL );

                        if( unlikely( !p_family ) )
                        {
                            free( psz_lc );
                            return VLC_ENOMEM;
                        }

                    }
                }

                if( vlc_dictionary_value_for_key( p_dict, psz_lc ) == kVLCDictionaryNotFound )
                    vlc_dictionary_insert( p_dict, psz_lc, p_family );
                free( psz_lc );
            }
            /*
             * If p_family has not been set by the time we encounter the first file,
             * it means this family has no name, and should be used only as a fallback.
             * We create a new family for it in the master list with the name "fallback-xx"
             * and later add it to the "default" fallback list.
             */
            else if( !strcasecmp( "file", p_node ) )
            {
                i_type = xml_ReaderNextNode( p_xml, &p_node );

                if( i_type != XML_READER_TEXT || !p_node || !*p_node )
                {
                    ++i_counter;
                    continue;
                }

                if( !p_family )
                    p_family = NewFamily( p_filter, NULL, &p_sys->p_families,
                                          &p_sys->family_map, NULL );

                if( unlikely( !p_family ) )
                    return VLC_ENOMEM;

                switch( i_counter )
                {
                case 0:
                    b_bold = false;
                    b_italic = false;
                    break;
                case 1:
                    b_bold = true;
                    b_italic = false;
                    break;
                case 2:
                    b_bold = false;
                    b_italic = true;
                    break;
                case 3:
                    b_bold = true;
                    b_italic = true;
                    break;
                default:
                    msg_Warn( p_filter, "Android_ParseFamily: too many files" );
                    return VLC_EGENERIC;
                }

                char *psz_fontfile = NULL;
                if( asprintf( &psz_fontfile, "%s/%s", ANDROID_FONT_PATH, p_node ) < 0
                 || !NewFont( psz_fontfile, 0, b_bold, b_italic, p_family ) )
                    return VLC_ENOMEM;

                ++i_counter;
            }
            break;

        case XML_READER_ENDELEM:
            if( !strcasecmp( "family", p_node ) )
            {
                if( !p_family )
                {
                    msg_Warn( p_filter, "Android_ParseFamily: empty family" );
                    return VLC_EGENERIC;
                }

                /*
                 * If the family name has "fallback" in it, add it to the
                 * "default" fallback list.
                 */
                if( strcasestr( p_family->psz_name, FB_NAME ) )
                {
                    vlc_family_t *p_fallback =
                        NewFamily( p_filter, p_family->psz_name,
                                   NULL, &p_sys->fallback_map, FB_LIST_DEFAULT );

                    if( unlikely( !p_fallback ) )
                        return VLC_ENOMEM;

                    p_fallback->p_fonts = p_family->p_fonts;
                }

                return VLC_SUCCESS;
            }
            break;
        }
    }

    msg_Warn( p_filter, "Android_ParseFamily: Corrupt font configuration file" );
    return VLC_EGENERIC;
}
Exemplo n.º 13
0
/**
 * Looks up the current desktop font and converts that to a family name,
 * font size and style flags suitable for passing directly to rufl
 *
 * \param  family	buffer to receive font family
 * \param  family_size	buffer size
 * \param  psize	receives the font size in 1/16 points
 * \param  pstyle	receives the style settings to be passed to rufl
 */
static void
ro_gui_wimp_desktop_font(char *family,
			 size_t family_size,
			 int *psize,
			 rufl_style *pstyle)
{
	rufl_style style = rufl_WEIGHT_400;
	os_error *error;
	int ptx, pty;
	font_f font_handle;
	int used;

	assert(family);
	assert(20 < family_size);
	assert(psize);
	assert(pstyle);

	error = xwimpreadsysinfo_font(&font_handle, NULL);
	if (error) {
		LOG("xwimpreadsysinfo_font: 0x%x: %s", error->errnum, error->errmess);
		ro_warn_user("WimpError", error->errmess);
		goto failsafe;
	}

	if (font_handle == font_SYSTEM) {
		/* Er, yeah; like that's ever gonna work with RUfl */
		goto failsafe;
	}

	error = xfont_read_identifier(font_handle, NULL, &used);
	if (error) {
		LOG("xfont_read_identifier: 0x%x: %s", error->errnum, error->errmess);
		ro_warn_user("MiscError", error->errmess);
		goto failsafe;
	}

	if (family_size < (size_t) used + 1) {
		LOG("desktop font name too long");
		goto failsafe;
	}

	error = xfont_read_defn(font_handle, (byte *) family,
			&ptx, &pty, NULL, NULL, NULL, NULL);
	if (error) {
		LOG("xfont_read_defn: 0x%x: %s", error->errnum, error->errmess);
		ro_warn_user("MiscError", error->errmess);
		goto failsafe;
	}

	for (size_t i = 0; i != (size_t) used; i++) {
		if (family[i] < ' ') {
			family[i] = 0;
			break;
		}
	}

	LOG("desktop font \"%s\"", family);

	if (strcasestr(family, ".Medium"))
		style = rufl_WEIGHT_500;
	else if (strcasestr(family, ".Bold"))
		style = rufl_WEIGHT_700;
	if (strcasestr(family, ".Italic") || strcasestr(family, ".Oblique"))
		style |= rufl_SLANTED;

	char *dot = strchr(family, '.');
	if (dot)
		*dot = 0;

	*psize = max(ptx, pty);
	*pstyle = style;

	LOG("family \"%s\", size %i, style %i", family, *psize, style);

	return;

failsafe:
	strcpy(family, "Homerton");
	*psize = 12*16;
	*pstyle = rufl_WEIGHT_400;
}
Exemplo n.º 14
0
int recherche_nom_rue(char contexte[20]) 
{
	int choix_ok = 0, nb_result = 0	, saisie_ok=0				;
	int choix = NON_TROUVE, test_saisie_char = 0 				;
	char nom_rue[TAILLE_NOM_JONCTION]							;
	char *test, tab_result[NB_JONCTIONS][TAILLE_NOM_JONCTION]	;


	purge(); /*On vide le buffer avant de demander la saisie à l'utilisateur*/
	while(nb_result == 0){
		while (saisie_ok == 0){
			saisie_ok=1;
  			printf("\nEntrez le nom de la voie, sans son type (rue, avenue, boulevard, ...)\nExemple : pour la rue de la Roquette, tapez roquette \nNom du point %s : ", contexte);
  			recup_saisie_user(nom_rue);
  			if (nom_rue[0] == '\0'){
  				saisie_ok=0;
  				printf ("Attention! Vous avez validé en n'ayant fait aucune saisie!\n");
  			}
  			else{
				verif_saisie_numerique(nom_rue, &saisie_ok);
				if (saisie_ok==0) printf("Votre saisie ne doit pas contenir de caractères de type numérique\n");
  			}
		}
		saisie_ok=0;	/*on remet saisie_ok à 0 sinon on part en boucle infinie dans le cas où la recherche ne donne rien*/
		conv_char_speciaux(nom_rue);

		for(int i = 0 ; i < nbjonction ; i++) // boucle de recherche du nom saisie dans liste des rues
		{
			test = strcasestr(tab_jonctions[i].nom, nom_rue) ;
			if(test != NULL)
			{
				nb_result++;
				printf("%-s\n", tab_jonctions[i].nom)		;
				strcpy(tab_result[i], tab_jonctions[i].nom)	;
			}
		}
		if(nb_result == 0) {
				//purge();
				printf("Le nom que vous avez saisi ne correspond à aucune données en mémoire.\nMerci de ressaisir le nom ou de choisir une autre rue.\n\n");
		}
	}
	
	printf("\nEntrez le numéro de jonction correspondant à votre point %s : ", contexte) ;
	while(!choix_ok) // boucle de vérification de la saisie
	{
		test_saisie_char = scanf("%d",&choix) ;
		if(test_saisie_char)
		{
			for(int i = 0 ; i < NB_JONCTIONS ; i++)
			{
				if (choix == atoi(tab_result[i]) && choix != 0) 
				{
					choix_ok = 1 ;
					printf("Vous avez sélectionné : %s\n", tab_result[i]); // affichage du choix
				}
			}
		} else {
			purge();
		}

		if (!choix_ok) 
		{
			printf("Choix erroné. Merci de renseigner un numéro valide : ");
			//printf("%d\n", choix);
		}
	}
	return choix-1;

}
Exemplo n.º 15
0
int main(int argc, char **argv) {

	printf("AiO Screengrabber "PACKAGE_VERSION"\n\n");

	int xres_v,yres_v,xres_o,yres_o,xres,yres,aspect;
	int c,osd_only,video_only,use_osd_res,width,use_png,use_jpg,jpg_quality,no_aspect,use_letterbox;

	// we use fast resize as standard now
	resize = &fast_resize;
	
	osd_only=video_only=use_osd_res=width=use_png=use_jpg=no_aspect=use_letterbox=0;
	jpg_quality=50;
	aspect=1;

	int dst_left = 0, dst_top = 0, dst_width = 0, dst_height = 0;
	
	unsigned char *video, *osd, *output;
	int output_bytes=3;
	
	char filename[256];
	sprintf(filename,"/tmp/screenshot.bmp");
	
	// detect STB
	char buf[256];
	FILE *pipe = fopen("/proc/fb","r");
	if (!pipe)
	{
		printf("No framebuffer, unknown STB .. quit.\n");
		return 1;
	}
	while (fgets(buf,sizeof(buf),pipe))
	{
		if (strcasestr(buf,"VULCAN")) stb_type=VULCAN;
		if (strcasestr(buf,"PALLAS")) stb_type=PALLAS;
		if (strcasestr(buf,"XILLEON")) stb_type=XILLEON;
		if (strcasestr(buf,"BCM7401") || strcasestr(buf,"BCMFB")) stb_type=BRCM7401;
	}
	pclose(pipe);

	if (stb_type == BRCM7401) // All Broadcom Dreamboxes use the same framebuffer string, so fall back to /proc/stb/info/model for detecting DM8000/DM500HD
	{
		pipe = fopen("/proc/stb/info/model", "r");
		if (pipe)
		{
			while (fgets(buf,sizeof(buf),pipe))
			{
				if (strcasestr(buf,"DM500HD"))
				{
					stb_type = BRCM7405;
					break;
				}
			}
			fclose(pipe);
		}
		if (stb_type == BRCM7401)
		{
			pipe = fopen("/proc/cpuinfo","r");
			if (pipe)
			{
				while (fgets(buf, sizeof(buf), pipe))
				{
					if (strcasestr(buf,"Brcm4380 V4.2"))
					{
						stb_type = BRCM7400;
						break;
					}
					else if (strcasestr(buf,"Brcm4380 V4.4"))
					{
						stb_type = BRCM7335;
						break;
					}
				}
				fclose(pipe);
			}
		}
	}

	if (stb_type == UNKNOWN)
	{
		printf("Unknown STB .. quit.\n");
		return 1;
	}
	else
	{
		printf("Detected STB: %s\n", stb_name[stb_type]);
	}
	
	// process command line
	while ((c = getopt (argc, argv, "dhj:lbnopr:v")) != -1)
	{
		switch (c)
		{
			case 'h':
			case '?':
				printf("Usage: grab [commands] [filename]\n\n");
				printf("command:\n");
				printf("-o only grab osd (framebuffer) when using this with png or bmp\n   fileformat you will get a 32bit pic with alphachannel\n");
				printf("-v only grab video\n");
				printf("-d always use osd resolution (good for skinshots)\n");
				printf("-n dont correct 16:9 aspect ratio\n");
				printf("-r (size) resize to a fixed width, maximum: 1920\n");
				printf("-l always 4:3, create letterbox if 16:9\n");
				printf("-b use bicubic picture resize (slow but smooth)\n");
				printf("-j (quality) produce jpg files instead of bmp (quality 0-100)\n");	
				printf("-p produce png files instead of bmp\n");
				printf("-h this help screen\n\n");

				printf("If no command is given the complete picture will be grabbed.\n");
				printf("If no filename is given /tmp/screenshot.[bmp/jpg/png] will be used.\n");
				return 0;
				break;
			case 'o': // OSD only
				osd_only=1;
				video_only=0;	
				break;
			case 'v': // Video only
				video_only=1;
				osd_only=0;
				break;
			case 'd': // always use OSD resolution
				use_osd_res=1;
				no_aspect=1;
				break;
			case 'r': // use given resolution
				width=atoi(optarg);
				if (width > 1920)
				{
					printf("Error: -r (size) ist limited to 1920 pixel !\n");
					return 1;
				}
				break;
			case 'l': // create letterbox
				use_letterbox=1;
				break;
			case 'b': // use bicubic resizing
				resize = &smooth_resize;
				break;			
			case 'p': // use png file format
				use_png=1;
				use_jpg=0;	
				sprintf(filename,"/tmp/screenshot.png");
				break;
			case 'j': // use jpg file format
				use_jpg=1;
				use_png=0;
				jpg_quality=atoi(optarg);
				sprintf(filename,"/tmp/screenshot.jpg");
				break;
			case 'n':
				no_aspect=1;
				break;
		} 
	}
	if (optind < argc) // filename
		sprintf(filename,"%s", argv[optind]);

	int mallocsize=1920*1080;
	if (stb_type == VULCAN || stb_type == PALLAS)
		mallocsize=720*576;
	
	video = (unsigned char *)malloc(mallocsize*3);
	osd = (unsigned char *)malloc(mallocsize*4);	

	if ((stb_type == VULCAN || stb_type == PALLAS) && width > 720)
		mallocsize=width*(width * 0.8 + 1);
	
	output = (unsigned char *)malloc(mallocsize*4);

	// get osd
	if (!video_only)
		getosd(osd,&xres_o,&yres_o);
	
	// get video
	if (!osd_only)
		getvideo(video,&xres_v,&yres_v);
	
	// get aspect ratio
	if (stb_type == VULCAN || stb_type == PALLAS)
	{
		pipe = fopen("/proc/bus/bitstream","r");
		if (pipe)
		{
			while (fgets(buf,sizeof(buf),pipe))
				sscanf(buf,"A_RATIO: %d",&aspect); 
			fclose(pipe);
		}
	} else
	{
		pipe = fopen("/proc/stb/vmpeg/0/aspect", "r");
		if (pipe)
		{
			while (fgets(buf,sizeof(buf), pipe))
				sscanf(buf,"%x",&aspect); 
			fclose(pipe);
		}
		pipe = fopen("/proc/stb/vmpeg/0/dst_width", "r");
		if (pipe)
		{
			while (fgets(buf,sizeof(buf), pipe))
				sscanf(buf,"%x",&dst_width);
			fclose(pipe);
		}
		pipe = fopen("/proc/stb/vmpeg/0/dst_height", "r");
		if (pipe)
		{
			while (fgets(buf,sizeof(buf), pipe))
				sscanf(buf,"%x",&dst_height);
			fclose(pipe);
		}
		pipe = fopen("/proc/stb/vmpeg/0/dst_top", "r");
		if (pipe)
		{
			while (fgets(buf,sizeof(buf), pipe))
				sscanf(buf,"%x",&dst_top);
			fclose(pipe);
		}
		pipe = fopen("/proc/stb/vmpeg/0/dst_left", "r");
		if (pipe)
		{
			while (fgets(buf,sizeof(buf), pipe))
				sscanf(buf,"%x",&dst_left);
			fclose(pipe);
		}
		if (dst_width == 720) dst_width = 0;
		if (dst_height == 576) dst_height = 0;
	}
	
	// resizing
 	if (video_only)
	{
		xres=xres_v;
		yres=yres_v;
	} else if (osd_only)
	{
		xres=xres_o;
		yres=yres_o;
	} else if (xres_o == xres_v && yres_o == yres_v)
	{
		xres=xres_v;
		yres=yres_v;
	} else
	{
		if (xres_v > xres_o && !use_osd_res && (width == 0 || width > xres_o))
		{
			// resize osd to video size
			xres = xres_v;
			yres = yres_v;
		}
		else
		{
			// resize video to osd size
			xres = xres_o;
			yres = yres_o;
		}
		if (dst_top || dst_left || dst_width || dst_height)
		{
			if (dst_width == 0) dst_width = 720;
			if (dst_height == 0) dst_height = 576;
			dst_top *= yres;
			dst_top /= 576;
			dst_height *= yres;
			dst_height /= 576;
			dst_left *= xres;
			dst_left /= 720;
			dst_width *= xres;
			dst_width /= 720;
		}
		else
		{
			dst_width = xres;
			dst_height = yres;
		}
		if (xres_o != xres || yres_o != yres)
		{
			printf("Resizing OSD to %d x %d ...\n", xres, yres);
			resize(osd, output, xres_o, yres_o, xres, yres, 4);
			memcpy(osd, output, xres * yres * 4);
		}
		if (xres_v != dst_width || yres_v != dst_height)
		{
			printf("Resizing Video to %d x %d ...\n", dst_width, dst_height);
			resize(video, output, xres_v, yres_v, dst_width, dst_height, 3);
			memset(video, 0, xres_v * yres_v * 3);
			memcpy(video, output, dst_width * dst_height * 3);
		}
	}
	

	// merge video and osd if neccessary
	if (osd_only)
	{
		memcpy(output,osd,xres*yres*4);
		output_bytes=4;
	}
	else if (video_only)
		memcpy(output,video,xres*yres*3);
	else 
	{
		printf("Merge Video with Framebuffer ...\n");
		combine(output, video, osd, dst_left, dst_top, dst_width ? dst_width : xres, dst_height ? dst_height : yres, xres, yres);
	}

	
	// resize to specific width ?
	if (width)
	{
		printf("Resizing Screenshot to %d x %d ...\n",width,yres*width/xres);
		resize(output,osd,xres,yres,width,(yres*width/xres),output_bytes);
		yres=yres*width/xres;
		xres=width;
		memcpy(output,osd,xres*yres*output_bytes);
	}
	

	// correct aspect ratio
	if (!no_aspect && aspect == 3 && ((float)xres/(float)yres)<1.5)
	{
		printf("Correct aspect ratio to 16:9 ...\n");
		resize(output,osd,xres,yres,xres,yres/1.42,output_bytes);
		yres/=1.42;
		memcpy(output,osd,xres*yres*output_bytes);
	}
	
	
	// use letterbox ?
	if (use_letterbox && xres*0.8 != yres && xres*0.8 <= 1080)
	{
		int yres_neu;
		yres_neu=xres*0.8;
		printf("Create letterbox %d x %d ...\n",xres,yres_neu);		
		if (yres_neu > yres)
		{
			int ofs;
			ofs=(yres_neu-yres)>>1;
			memmove(output+ofs*xres*output_bytes,output,xres*yres*output_bytes);
			memset(output,0,ofs*xres*output_bytes);
			memset(output+ofs*xres*3+xres*yres*output_bytes,0,ofs*xres*output_bytes);
		}
Exemplo n.º 16
0
extern int
get_cpuinfo(uint16_t *p_cpus, uint16_t *p_boards,
	    uint16_t *p_sockets, uint16_t *p_cores, uint16_t *p_threads,
	    uint16_t *p_block_map_size,
	    uint16_t **p_block_map, uint16_t **p_block_map_inv)
{
	enum { SOCKET=0, CORE=1, PU=2, LAST_OBJ=3 };
	hwloc_topology_t topology;
	hwloc_obj_t obj;
	hwloc_obj_type_t objtype[LAST_OBJ];
	unsigned idx[LAST_OBJ];
	int nobj[LAST_OBJ];
	int actual_cpus;
	int macid;
	int absid;
	int actual_boards = 1, depth;
	int i;

	debug2("hwloc_topology_init");
	if (hwloc_topology_init(&topology)) {
		/* error in initialize hwloc library */
		debug("hwloc_topology_init() failed.");
		return 1;
	}

	/* parse all system */
	hwloc_topology_set_flags(topology, HWLOC_TOPOLOGY_FLAG_WHOLE_SYSTEM);

	/* ignores cache, misc */
	hwloc_topology_ignore_type (topology, HWLOC_OBJ_CACHE);
	hwloc_topology_ignore_type (topology, HWLOC_OBJ_MISC);

	/* load topology */
	debug2("hwloc_topology_load");
	if (hwloc_topology_load(topology)) {
		/* error in load hardware topology */
		debug("hwloc_topology_load() failed.");
		hwloc_topology_destroy(topology);
		return 2;
	}

	/* Some processors (e.g. AMD Opteron 6000 series) contain multiple
	 * NUMA nodes per socket. This is a configuration which does not map
	 * into the hardware entities that Slurm optimizes resource allocation
	 * for (PU/thread, core, socket, baseboard, node and network switch).
	 * In order to optimize resource allocations on such hardware, Slurm
	 * will consider each NUMA node within the socket as a separate socket.
	 * You can disable this configuring "SchedulerParameters=Ignore_NUMA",
	 * in which case Slurm will report the correct socket count on the node,
	 * but not be able to optimize resource allocations on the NUMA nodes.
	 */
	objtype[SOCKET] = HWLOC_OBJ_SOCKET;
	objtype[CORE]   = HWLOC_OBJ_CORE;
	objtype[PU]     = HWLOC_OBJ_PU;
	if (hwloc_get_type_depth(topology, HWLOC_OBJ_NODE) >
	    hwloc_get_type_depth(topology, HWLOC_OBJ_SOCKET)) {
		char *sched_params = slurm_get_sched_params();
		if (sched_params &&
		    strcasestr(sched_params, "Ignore_NUMA")) {
			info("Ignoring NUMA nodes within a socket");
		} else {
			info("Considering each NUMA node as a socket");
			objtype[SOCKET] = HWLOC_OBJ_NODE;
		}
		xfree(sched_params);
	}

	/* number of objects */
	depth = hwloc_get_type_depth(topology, HWLOC_OBJ_GROUP);
	if (depth != HWLOC_TYPE_DEPTH_UNKNOWN) {
		actual_boards = MAX(hwloc_get_nbobjs_by_depth(topology, depth),
				    1);
	}
	nobj[SOCKET] = hwloc_get_nbobjs_by_type(topology, objtype[SOCKET]);
	nobj[CORE]   = hwloc_get_nbobjs_by_type(topology, objtype[CORE]);
	/*
	 * Workaround for hwloc
	 * hwloc_get_nbobjs_by_type() returns 0 on some architectures.
	 */
	if ( nobj[SOCKET] == 0 ) {
		debug("get_cpuinfo() fudging nobj[SOCKET] from 0 to 1");
		nobj[SOCKET] = 1;
	}
	if ( nobj[CORE] == 0 ) {
		debug("get_cpuinfo() fudging nobj[CORE] from 0 to 1");
		nobj[CORE] = 1;
	}
	if ( nobj[SOCKET] == -1 )
		fatal("get_cpuinfo() can not handle nobj[SOCKET] = -1");
	if ( nobj[CORE] == -1 )
		fatal("get_cpuinfo() can not handle nobj[CORE] = -1");
	actual_cpus  = hwloc_get_nbobjs_by_type(topology, objtype[PU]);
#if 0
	/* Used to find workaround above */
	info("CORE = %d SOCKET = %d actual_cpus = %d nobj[CORE] = %d",
	     CORE, SOCKET, actual_cpus, nobj[CORE]);
#endif
	nobj[PU]     = actual_cpus/nobj[CORE];  /* threads per core */
	nobj[CORE]  /= nobj[SOCKET];            /* cores per socket */

	debug("CPUs:%d Boards:%u Sockets:%d CoresPerSocket:%d ThreadsPerCore:%d",
	      actual_cpus, actual_boards, nobj[SOCKET], nobj[CORE], nobj[PU]);

	/* allocate block_map */
	*p_block_map_size = (uint16_t)actual_cpus;
	if (p_block_map && p_block_map_inv) {
		*p_block_map     = xmalloc(actual_cpus * sizeof(uint16_t));
		*p_block_map_inv = xmalloc(actual_cpus * sizeof(uint16_t));

		/* initialize default as linear mapping */
		for (i = 0; i < actual_cpus; i++) {
			(*p_block_map)[i]     = i;
			(*p_block_map_inv)[i] = i;
		}
		/* create map with hwloc */
		for (idx[SOCKET]=0; idx[SOCKET]<nobj[SOCKET]; ++idx[SOCKET]) {
			for (idx[CORE]=0; idx[CORE]<nobj[CORE]; ++idx[CORE]) {
				for (idx[PU]=0; idx[PU]<nobj[PU]; ++idx[PU]) {
					/* get hwloc_obj by indexes */
					obj=hwloc_get_obj_below_array_by_type(
					            topology, 3, objtype, idx);
					if (!obj)
						continue;
					macid = obj->os_index;
					absid = idx[SOCKET]*nobj[CORE]*nobj[PU]
					      + idx[CORE]*nobj[PU]
					      + idx[PU];

					if ((macid >= actual_cpus) ||
					    (absid >= actual_cpus)) {
						/* physical or logical ID are
						 * out of range */
						continue;
					}
					debug4("CPU map[%d]=>%d", absid, macid);
					(*p_block_map)[absid]     = macid;
					(*p_block_map_inv)[macid] = absid;
				}
			 }
		}
	}

	hwloc_topology_destroy(topology);

	/* update output parameters */
	*p_cpus    = actual_cpus;
	*p_boards  = actual_boards;
	*p_sockets = nobj[SOCKET];
	*p_cores   = nobj[CORE];
	*p_threads = nobj[PU];

#if DEBUG_DETAIL
	/*** Display raw data ***/
	debug("CPUs:%u Boards:%u Sockets:%u CoresPerSocket:%u ThreadsPerCore:%u",
	      *p_cpus, *p_boards, *p_sockets, *p_cores, *p_threads);

	/* Display the mapping tables */
	if (p_block_map && p_block_map_inv) {
		debug("------");
		debug("Abstract -> Machine logical CPU ID block mapping:");
		debug("AbstractId PhysicalId Inverse");
		for (i = 0; i < *p_cpus; i++) {
			debug3("   %4d      %4u       %4u",
				i, (*p_block_map)[i], (*p_block_map_inv)[i]);
		}
		debug("------");
	}
#endif
	return 0;

}
Exemplo n.º 17
0
char *get_url_title(const char *url) {

	CURL *curl;
	CURLcode code;
	struct mem_buffer mem = {NULL, 0};
	char *temp, *url_title = NULL;
	bool iso = false;

	curl = curl_easy_init();
	if (!curl)
		goto cleanup;

	curl_easy_setopt(curl, CURLOPT_URL, url);
	curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
	curl_easy_setopt(curl, CURLOPT_TIMEOUT, 3L);
	curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_write_memory);
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, &mem);

	code = curl_easy_perform(curl);
	if (code != CURLE_OK) {
		fprintf(stderr, "Error: %s\n", curl_easy_strerror(code));
		goto cleanup;
	}
	if (!mem.buffer) {
		fprintf(stderr, "Error: Body was empty");
		goto cleanup;
	}
	// Search http response in order to determine text encoding
	temp = strcasestr(mem.buffer, "iso-8859-7");
	if (temp) // strlen("charset") = 7
		if (starts_case_with(temp - 8, "charset") || starts_case_with(temp - 7, "charset"))
			iso = true;

	temp = strcasestr(mem.buffer, "<title");
	if (!temp)
		goto cleanup;

	url_title = temp + 7; // Point url_title to the first title character

	temp = strcasestr(url_title, "</title");
	if (!temp) {
		url_title = NULL;
		goto cleanup;
	}
	*temp = '\0'; // Terminate title string

	// Replace newline characters with spaces
	for (temp = url_title; *temp != '\0'; temp++)
		if (*temp == '\n')
			*temp = ' ';

	// If title string uses ISO 8859-7 encoding then convert it to UTF-8
	// Return value must be freed to avoid memory leak
	if (iso)
		url_title = iso8859_7_to_utf8(url_title);
	else
		url_title = strndup(url_title, TITLELEN);

cleanup:
	free(mem.buffer);
	curl_easy_cleanup(curl);
	return url_title;
}
Exemplo n.º 18
0
/* Called when activating a source. Verifies that the source count is not
 * exceeded and applies any initial parameters.
 */
int connection_complete_source (source_t *source, int response)
{
    ice_config_t *config;

    global_lock ();
    DEBUG1 ("sources count is %d", global.sources);

    config = config_get_config();
    if (global.sources < config->source_limit)
    {
        const char *contenttype;
        const char *expectcontinue;
        mount_proxy *mountinfo;
        format_type_t format_type;

        /* setup format handler */
        contenttype = httpp_getvar (source->parser, "content-type");
        if (contenttype != NULL)
        {
            format_type = format_get_type (contenttype);

            if (format_type == FORMAT_ERROR)
            {
                config_release_config();
                global_unlock();
                if (response)
                {
                    client_send_403 (source->client, "Content-type not supported");
                    source->client = NULL;
                }
                WARN1("Content-type \"%s\" not supported, dropping source", contenttype);
                return -1;
            }
        }
        else
        {
            WARN0("No content-type header, falling back to backwards compatibility mode "
                    "for icecast 1.x relays. Assuming content is mp3.");
            format_type = FORMAT_TYPE_GENERIC;
        }

        if (format_get_plugin (format_type, source) < 0)
        {
            global_unlock();
            config_release_config();
            if (response)
            {
                client_send_403 (source->client, "internal format allocation problem");
                source->client = NULL;
            }
            WARN1 ("plugin format failed for \"%s\"", source->mount);
            return -1;
        }

	/* For PUT support we check for 100-continue and send back a 100 to stay in spec */
	expectcontinue = httpp_getvar (source->parser, "expect");
	if (expectcontinue != NULL)
	{
#ifdef HAVE_STRCASESTR
	    if (strcasestr (expectcontinue, "100-continue") != NULL)
#else
	    WARN0("OS doesn't support case insenestive substring checks...");
	    if (strstr (expectcontinue, "100-continue") != NULL)
#endif
	    {
		client_send_100 (source->client);
	    }
	}

        global.sources++;
        stats_event_args (NULL, "sources", "%d", global.sources);
        global_unlock();

        source->running = 1;
        mountinfo = config_find_mount (config, source->mount, MOUNT_TYPE_NORMAL);
        source_update_settings (config, source, mountinfo);
        config_release_config();
        slave_rebuild_mounts();

        source->shutdown_rwlock = &_source_shutdown_rwlock;
        DEBUG0 ("source is ready to start");

        return 0;
    }
    WARN1("Request to add source when maximum source limit "
            "reached %d", global.sources);

    global_unlock();
    config_release_config();

    if (response)
    {
        client_send_403 (source->client, "too many sources connected");
        source->client = NULL;
    }

    return -1;
}
Exemplo n.º 19
0
/*!
   A toy function to identify windows on the root window.
   This function can potentially be used to identify where
   AFNI windows, for example, are taking screen space and 
   have SUMA avoid overlapping with them.
   The function needs much work. It is not terribly selective
   about what it chases down. 
   See command line  xwininfo -tree -root 
   for full listing from command line, or xwininfo for
   interactive queries.
   For now, we let this rest.
*/
int SUMA_WindowsOnRootDisplay(Display *dd, Window ww, int all)
{
   static char FuncName[]={"SUMA_WindowsOnRootDisplay"};
   Window rr, pr, *cr, jj;
   XWindowAttributes wa;
   unsigned int ncr, wr, hr, bwr, bhr;
   int ii, xr, yr, showgeom=0;
   char *wname=NULL, *sout=NULL;

   /* tell me what windows are displayed and where */
   if (XQueryTree(dd, 
                   ww,
                   &rr, &pr, &cr, &ncr)) {

      if (all) fprintf(stderr,"Have %d childern in query\n", ncr);
      for (ii=0; ii<ncr; ++ii) {
          showgeom = 0;
          XGetWindowAttributes(dd, cr[ii], &wa);
          XTranslateCoordinates (dd, cr[ii], wa.root, 
                  -wa.border_width,
                  -wa.border_width,
                  &xr, &yr, &jj);
         if (XFetchName(dd, cr[ii], &wname)) { 
            /* XGetWMName usage From source of xwininfo.c,
               Not getting advantage over XFetchName for 
               lots more hassle ....*/
            if (wname) {
               sout = SUMA_copy_string(wname);
               XFree(wname);
            } else sout = SUMA_copy_string("no name but fetch OK!");
            if (strcasestr(sout,"afni") ||
                strcasestr(sout,"suma") ) {
                fprintf(stderr,"   brethren %d: %s\n", ii, sout);
                showgeom=1;
            } else {
               if (all) {
                  fprintf(stderr,"   furner %d: %s\n", ii, sout);
                  showgeom=1;
               }
            }
         } else {
            if (all) {
               fprintf(stderr,"   %d: (No name!)\n", ii);
               showgeom = 1;
            }
         }
         if (showgeom) {
            fprintf(stderr,
               "      abs Upper Left X Y %d %d, (rel UL %d %d) W H%d %d, \n", 
                                    xr, yr, wa.x, wa.y, wa.width, wa.height);
             /* 
               Under alternative below, xr and yr are relative UL vals */ 
             #if 0
             if (XGetGeometry(dd, cr[ii], &rr,
                              &xr, &yr, &wr, &hr, &bwr, &bhr)) {
                fprintf(stderr,"       %d %d, %dx%d, %d %d\n", 
                               xr, yr, wr, hr, bwr, bhr);     

             }
             #endif
         }
         if (sout) SUMA_free(sout); sout = NULL;
         SUMA_WindowsOnRootDisplay(dd, cr[ii],all);
      } 
   }
}
Exemplo n.º 20
0
/*
 * This returns a dummy child_process if the transport protocol does not
 * need fork(2), or a struct child_process object if it does.  Once done,
 * finish the connection with finish_connect() with the value returned from
 * this function (it is safe to call finish_connect() with NULL to support
 * the former case).
 *
 * If it returns, the connect is successful; it just dies on errors (this
 * will hopefully be changed in a libification effort, to return NULL when
 * the connection failed).
 */
struct child_process *git_connect(int fd[2], const char *url_orig,
				  const char *prog, int flags)
{
	char *url = xstrdup(url_orig);
	char *host, *path;
	char *end;
	int c;
	struct child_process *conn;
	enum protocol protocol = PROTO_LOCAL;
	int free_path = 0;
	char *port = NULL;
	const char **arg;
	struct strbuf cmd;

	/* Without this we cannot rely on waitpid() to tell
	 * what happened to our children.
	 */
	signal(SIGCHLD, SIG_DFL);

	host = strstr(url, "://");
	if (host) {
		*host = '\0';
		protocol = get_protocol(url);
		host += 3;
		c = '/';
	} else {
		host = url;
		c = ':';
	}

	/*
	 * Don't do destructive transforms with git:// as that
	 * protocol code does '[]' unwrapping of its own.
	 */
	if (host[0] == '[') {
		end = strchr(host + 1, ']');
		if (end) {
			if (protocol != PROTO_GIT) {
				*end = 0;
				host++;
			}
			end++;
		} else
			end = host;
	} else
		end = host;

	path = strchr(end, c);
	if (path && !has_dos_drive_prefix(end)) {
		if (c == ':') {
			protocol = PROTO_SSH;
			*path++ = '\0';
		}
	} else
		path = end;

	if (!path || !*path)
		die("No path specified. See 'man git-pull' for valid url syntax");

	/*
	 * null-terminate hostname and point path to ~ for URL's like this:
	 *    ssh://host.xz/~user/repo
	 */
	if (protocol != PROTO_LOCAL && host != url) {
		char *ptr = path;
		if (path[1] == '~')
			path++;
		else {
			path = xstrdup(ptr);
			free_path = 1;
		}

		*ptr = '\0';
	}

	/*
	 * Add support for ssh port: ssh://host.xy:<port>/...
	 */
	if (protocol == PROTO_SSH && host != url)
		port = get_port(host);

	if (protocol == PROTO_GIT) {
		/* These underlying connection commands die() if they
		 * cannot connect.
		 */
		char *target_host = xstrdup(host);
		if (git_use_proxy(host))
			git_proxy_connect(fd, host);
		else
			git_tcp_connect(fd, host, flags);
		/*
		 * Separate original protocol components prog and path
		 * from extended host header with a NUL byte.
		 *
		 * Note: Do not add any other headers here!  Doing so
		 * will cause older git-daemon servers to crash.
		 */
		packet_write(fd[1],
			     "%s %s%chost=%s%c",
			     prog, path, 0,
			     target_host, 0);
		free(target_host);
		free(url);
		if (free_path)
			free(path);
		return &no_fork;
	}

	conn = xcalloc(1, sizeof(*conn));

	strbuf_init(&cmd, MAX_CMD_LEN);
	strbuf_addstr(&cmd, prog);
	strbuf_addch(&cmd, ' ');
	sq_quote_buf(&cmd, path);
	if (cmd.len >= MAX_CMD_LEN)
		die("command line too long");

	conn->in = conn->out = -1;
	conn->argv = arg = xcalloc(7, sizeof(*arg));
	if (protocol == PROTO_SSH) {
		const char *ssh = getenv("GIT_SSH");
		int putty = ssh && strcasestr(ssh, "plink");
		if (!ssh) ssh = "ssh";

		*arg++ = ssh;
		if (putty && !strcasestr(ssh, "tortoiseplink"))
			*arg++ = "-batch";
		if (port) {
			/* P is for PuTTY, p is for OpenSSH */
			*arg++ = putty ? "-P" : "-p";
			*arg++ = port;
		}
		*arg++ = host;
	}
	else {
		/* remove repo-local variables from the environment */
		conn->env = local_repo_env;
		conn->use_shell = 1;
	}
	*arg++ = cmd.buf;
	*arg = NULL;

	if (start_command(conn))
		die("unable to fork");

	fd[0] = conn->out; /* read from child's stdout */
	fd[1] = conn->in;  /* write to child's stdin */
	strbuf_release(&cmd);
	free(url);
	if (free_path)
		free(path);
	return conn;
}
Exemplo n.º 21
0
static char const * _find_string(char const * big, char const * little,
		gboolean sensitive)
{
	return sensitive ? strstr(big, little) : strcasestr(big, little);
}
Exemplo n.º 22
0
/*
 * GetNextURL - get the next url from html[pos] into result
 *
 * Assumptions:
 *     1. html and base_url are allocated and valid
 *     2. pos = 0 on initial call
 *     3. result is NULL and will be allocated internally
 *
 * Pseudocode:
 *     1. check arguments
 *     2. if pos = 0: remove whitespace from html
 *     3. find hyperlink starting tags "<a" or "<A"
 *     4. find next href attribute "href="
 *     5. find next end tag ">"
 *     6. check that href comes before end tag
 *     7. deal with quoted and unquoted urls
 *     8. determine if url is absolute
 *     9. fixup relative links
 *    10. create new character buffer for result and return it
 */
int GetNextURL(char *html, int pos, char *base_url, char **result)
{
    int bad_link;                            // is this link ill formatted?
    int relative;                            // is this link relative?
    char delim;                              // url delimiter: ' ', ''', '"'
    char *lnk;                               // hyperlink tags
    char *href;                              // href in a tag
    char *end;                               // end of hyperlink tag or url
    char *ptr;                               // absolute vs. relative
    char *hash;                              // hash mark character

    // make sure we have text and base url
    if (!html || !base_url) return -1;

    // condense html, makes parsing easier
    if (pos == 0)
        RemoveWhitespace(html);

    // parse for hyperlinks
    do {
        relative = 0;                        // assume absolute link
        bad_link = 0;                        // assume valid link

        // find tag "<a" or "<A""
        lnk = strcasestr(&html[pos], "<a");

        // no more links on this page
        if (!lnk) { result = NULL; return -1; }


        // find next href after hyperlink tag
        href = strcasestr(lnk, "href=");

        // no more links on this page
        if (!href) { result = NULL; return -1; }

        // find end of hyperlink tag
        end = strchr(lnk, '>');

        // if the href we have is outside the current tag, continue
        if (end && (end < href)) {
            bad_link = 1; pos+=2; continue;
        }

        // move href to beginning of url
        href+=5;

        // something went wrong, just continue
        if (!href) { bad_link=1; pos+=2; continue; }

        // is the url quoted?
        if (*href == '\'' || *href == '"') {  // yes, href="url" or href='url'
            delim = *(href++);               // remember delimiter
            end = strchr(href, delim);       // find next of same delimiter
        }
        else {                               // no, href=url
            end = strchr(href, '>');         // hope: <a ... href=url>
                                             // since we've stripped whitespace
                                             // this could mangle things like:
                                             // <a ... href=url name=val>
        }

        // if there is a # before the end of the url, exclude the #fragment
        hash = strchr(href, '#');
        if (hash && hash < end) {
                end = hash;
        }

        // if we don't know where to end the url, continue
        if (!end) {
            bad_link = 1; pos += 2; continue;
        }

        // have a link now
        if (*href == '#') {                   // internal reference
            bad_link = 1; pos += 2; continue;
        }

        // is the url absolute, i.e, ':' must precede any '/', '?', or '#'
        ptr = strpbrk(href, ":/?#");
        if (!ptr || *ptr != ':') { relative = 1; }
        else if (strncasecmp(href, "http", 4)) { // absolute, but not http(s)
                bad_link = 1; pos += 2; continue;
        }
    } while (bad_link);                       // keep parsing

    // have a good link now
    if (relative) {                           // need to fixup relative links
        *result = FixupRelativeURL(base_url, href, end - href);
        if (!*result) { return -2; }
    } else {
        // create new buffer
        *result = calloc(end-href+1, sizeof(char));

        if (!*result) { return -2; }          // check memory

        // copy over absolute url
        strncpy(*result, href, end - href);
    }

    // return position at the end of the url
    return end - html;
}
Exemplo n.º 23
0
cl_int GLCLDraw::InitContext(int platformnum, int processornum, int GLinterop)
{
   cl_int ret;
   size_t len;
   char extension_data[1024];
   size_t llen;
   size_t extension_len;
   int i;
   
   properties = malloc(16 * sizeof(intptr_t));
   ret = clGetPlatformIDs(8, platform_id, &ret_num_platforms);
   if(ret != CL_SUCCESS) return ret;

   if(ret_num_platforms <= 0) return CL_INVALID_PLATFORM;

   platform_num = platformnum;
   if(platform_num >= ret_num_platforms) platform_num = ret_num_platforms - 1;
   if(platform_num <= 0) platform_num = 0;
   ret = clGetDeviceIDs(platform_id[platform_num], CL_DEVICE_TYPE_ALL, 8, device_id,
                            &ret_num_devices);
   if(ret != CL_SUCCESS) return ret;
   if(ret_num_devices <= 0) {
     XM7_DebugLog(XM7_LOG_DEBUG, "CL : Has no useful device(s).");
     return ret;
   }
   if(ret_num_devices > 8) ret_num_devices = 8;
   if(ret_num_devices <= 0) return CL_INVALID_DEVICE_TYPE;
   XM7_DebugLog(XM7_LOG_DEBUG, "CL : Found %d processors.", ret_num_devices);

   using_device = processornum;
   if(using_device >= ret_num_devices) using_device = ret_num_devices - 1;
   if(using_device <= 0) using_device = 0;

   bCLEnableKhrGLShare = 0;

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

     extension_data[0] = '\0';
     GetDeviceName(extension_data, sizeof(extension_data), i);
     XM7_DebugLog(XM7_LOG_DEBUG, "CL : Processor #%d : Name = %s ", i, extension_data);

     extension_data[0] = '\0';
     clGetDeviceInfo(device_id[i], CL_DEVICE_TYPE,
		     sizeof(cl_ulong), &(device_type[i]), &llen);
     clGetDeviceInfo(device_id[i], CL_DEVICE_LOCAL_MEM_SIZE,
		     sizeof(cl_ulong), &(local_memsize[i]), &llen);
     GetDeviceType(extension_data, sizeof(extension_data), i);
     XM7_DebugLog(XM7_LOG_DEBUG, "CL : Processor #%d : TYPE = %s / Local memory size = %d bytes", i, extension_data, local_memsize[i]);

     extension_data[0] = '\0';
     clGetDeviceInfo(device_id[i], CL_DEVICE_EXTENSIONS,
		   1024, extension_data, &extension_len);
     XM7_DebugLog(XM7_LOG_DEBUG, "CL : Extension features(#%d):%s", i, extension_data);
     if(i == using_device) {
       if(strcasestr(extension_data, "cl_khr_gl_sharing") != NULL) {
	 if(GLinterop != 0) bCLEnableKhrGLShare = -1;
       } else {
	 bCLEnableKhrGLShare = 0;
       }
     }
   }
   
   XM7_DebugLog(XM7_LOG_DEBUG, "CL : Using device #%d", using_device);
   if(bCLEnableKhrGLShare != 0) { // This is only under X11. Must fix.
     XM7_DebugLog(XM7_LOG_DEBUG, "CL : GL Interoperability enabled.");
     properties[0] = CL_GL_CONTEXT_KHR;
     properties[1] = (cl_context_properties)glXGetCurrentContext();
     XM7_DebugLog(XM7_LOG_DEBUG, "CL : GL Context = %08x", glXGetCurrentContext());
     properties[2] = CL_GLX_DISPLAY_KHR;
     properties[3] = (cl_context_properties)glXGetCurrentDisplay();
     XM7_DebugLog(XM7_LOG_DEBUG, "CL : GL Display = %08x", glXGetCurrentDisplay());
     properties[4] = CL_CONTEXT_PLATFORM;
     properties[5] = (cl_context_properties)platform_id[platform_num];
     properties[6] = 0;
   } else {
     XM7_DebugLog(XM7_LOG_DEBUG, "CL : GL Interoperability disabled.");
     properties[0] = CL_CONTEXT_PLATFORM;
     properties[1] = (cl_context_properties)platform_id[platform_num];
     properties[2] = 0;
   }
//   if(device_id == NULL) return -1;
   
   context = clCreateContext(properties, 1, &device_id[using_device], cl_notify_log, NULL, &ret);
   XM7_DebugLog(XM7_LOG_DEBUG, "CL : Created context : STS = %d", ret);
   if(ret != CL_SUCCESS) return ret;
       
   command_queue = clCreateCommandQueue(context, device_id[using_device],
                                         CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, &ret);
   XM7_DebugLog(XM7_LOG_DEBUG, "CL: Created command queue.");
   return ret;
}
Exemplo n.º 24
0
static const char *
guess_from_received_header (notmuch_config_t *config, notmuch_message_t *message)
{
    const char *received,*primary,*by;
    const char **other;
    char *tohdr;
    char *mta,*ptr,*token;
    char *domain=NULL;
    char *tld=NULL;
    const char *delim=". \t";
    size_t i,j,other_len;

    const char *to_headers[] = {"Envelope-to", "X-Original-To"};

    primary = notmuch_config_get_user_primary_email (config);
    other = notmuch_config_get_user_other_email (config, &other_len);

    /* sadly, there is no standard way to find out to which email
     * address a mail was delivered - what is in the headers depends
     * on the MTAs used along the way. So we are trying a number of
     * heuristics which hopefully will answer this question.

     * We only got here if none of the users email addresses are in
     * the To: or Cc: header. From here we try the following in order:
     * 1) check for an Envelope-to: header
     * 2) check for an X-Original-To: header
     * 3) check for a (for <*****@*****.**>) clause in Received: headers
     * 4) check for the domain part of known email addresses in the
     *    'by' part of Received headers
     * If none of these work, we give up and return NULL
     */
    for (i = 0; i < sizeof(to_headers)/sizeof(*to_headers); i++) {
	tohdr = xstrdup(notmuch_message_get_header (message, to_headers[i]));
	if (tohdr && *tohdr) {
	    /* tohdr is potentialy a list of email addresses, so here we
	     * check if one of the email addresses is a substring of tohdr
	     */
	    if (strcasestr(tohdr, primary)) {
		free(tohdr);
		return primary;
	    }
	    for (j = 0; j < other_len; j++)
		if (strcasestr (tohdr, other[j])) {
		    free(tohdr);
		    return other[j];
		}
	    free(tohdr);
	}
    }

    /* We get the concatenated Received: headers and search from the
     * front (last Received: header added) and try to extract from
     * them indications to which email address this message was
     * delivered.
     * The Received: header is special in our get_header function
     * and is always concatenated.
     */
    received = notmuch_message_get_header (message, "received");
    if (received == NULL)
	return NULL;

    /* First we look for a " for <*****@*****.**>" in the received
     * header
     */
    ptr = strstr (received, " for ");
    if (ptr) {
	/* the text following is potentialy a list of email addresses,
	 * so again we check if one of the email addresses is a
	 * substring of ptr
	 */
	if (strcasestr(ptr, primary)) {
	    return primary;
	}
	for (i = 0; i < other_len; i++)
	    if (strcasestr (ptr, other[i])) {
		return other[i];
	    }
    }
    /* Finally, we parse all the " by MTA ..." headers to guess the
     * email address that this was originally delivered to.
     * We extract just the MTA here by removing leading whitespace and
     * assuming that the MTA name ends at the next whitespace.
     * We test for *(by+4) to be non-'\0' to make sure there's
     * something there at all - and then assume that the first
     * whitespace delimited token that follows is the receiving
     * system in this step of the receive chain
     */
    by = received;
    while((by = strstr (by, " by ")) != NULL) {
	by += 4;
	if (*by == '\0')
	    break;
	mta = xstrdup (by);
	token = strtok(mta," \t");
	if (token == NULL) {
	    free (mta);
	    break;
	}
	/* Now extract the last two components of the MTA host name
	 * as domain and tld.
	 */
	domain = tld = NULL;
	while ((ptr = strsep (&token, delim)) != NULL) {
	    if (*ptr == '\0')
		continue;
	    domain = tld;
	    tld = ptr;
	}

	if (domain) {
	    /* Recombine domain and tld and look for it among the configured
	     * email addresses.
	     * This time we have a known domain name and nothing else - so
	     * the test is the other way around: we check if this is a
	     * substring of one of the email addresses.
	     */
	    *(tld-1) = '.';

	    if (strcasestr(primary, domain)) {
		free(mta);
		return primary;
	    }
	    for (i = 0; i < other_len; i++)
		if (strcasestr (other[i],domain)) {
		    free(mta);
		    return other[i];
		}
	}
	free (mta);
    }

    return NULL;
}
Exemplo n.º 25
0
Arquivo: http.c Projeto: mstorsjo/vlc
static int ReadICYMeta( stream_t *p_access )
{
    access_sys_t *p_sys = p_access->p_sys;

    uint8_t buffer;
    char *p, *psz_meta;
    int i_read;

    /* Read meta data length */
    if( ReadData( p_access, &i_read, &buffer, 1 ) )
        return VLC_EGENERIC;
    if( i_read != 1 )
        return VLC_EGENERIC;
    const int i_size = buffer << 4;
    /* msg_Dbg( p_access, "ICY meta size=%u", i_size); */

    psz_meta = malloc( i_size + 1 );
    for( i_read = 0; i_read < i_size; )
    {
        int i_tmp;
        if( ReadData( p_access, &i_tmp, (uint8_t *)&psz_meta[i_read], i_size - i_read ) || i_tmp <= 0 )
        {
            free( psz_meta );
            return VLC_EGENERIC;
        }
        i_read += i_tmp;
    }
    psz_meta[i_read] = '\0'; /* Just in case */

    /* msg_Dbg( p_access, "icy-meta=%s", psz_meta ); */

    /* Now parse the meta */
    /* Look for StreamTitle= */
    p = strcasestr( (char *)psz_meta, "StreamTitle=" );
    if( p )
    {
        p += strlen( "StreamTitle=" );
        if( *p == '\'' || *p == '"' )
        {
            char closing[] = { p[0], ';', '\0' };
            char *psz = strstr( &p[1], closing );
            if( !psz )
                psz = strchr( &p[1], ';' );

            if( psz ) *psz = '\0';
            p++;
        }
        else
        {
            char *psz = strchr( p, ';' );
            if( psz ) *psz = '\0';
        }

        if( !p_sys->psz_icy_title ||
            strcmp( p_sys->psz_icy_title, p ) )
        {
            free( p_sys->psz_icy_title );
            char *psz_tmp = strdup( p );
            p_sys->psz_icy_title = EnsureUTF8( psz_tmp );
            if( !p_sys->psz_icy_title )
                free( psz_tmp );

            msg_Dbg( p_access, "New Icy-Title=%s", p_sys->psz_icy_title );
            if( p_access->p_input_item )
                input_item_SetMeta( p_access->p_input_item, vlc_meta_NowPlaying,
                                    p_sys->psz_icy_title );
        }
    }
    free( psz_meta );

    return VLC_SUCCESS;
}
Exemplo n.º 26
0
int
main(int argc, char **argv)
{
	char					*path, *label, tmp[PATH_MAX];
	char					*shellcmd = NULL, **var;
	const char				*s, *shell;
	int					 opt, flags, keys;
	const struct options_table_entry	*oe;

	if (setlocale(LC_CTYPE, "en_US.UTF-8") == NULL) {
		if (setlocale(LC_CTYPE, "") == NULL)
			errx(1, "invalid LC_ALL, LC_CTYPE or LANG");
		s = nl_langinfo(CODESET);
		if (strcasecmp(s, "UTF-8") != 0 && strcasecmp(s, "UTF8") != 0)
			errx(1, "need UTF-8 locale (LC_CTYPE) but have %s", s);
	}

	setlocale(LC_TIME, "");
	tzset();

	if (**argv == '-')
		flags = CLIENT_LOGIN;
	else
		flags = 0;

	label = path = NULL;
	while ((opt = getopt(argc, argv, "2c:Cdf:lL:qS:uUVv")) != -1) {
		switch (opt) {
		case '2':
			flags |= CLIENT_256COLOURS;
			break;
		case 'c':
			free(shellcmd);
			shellcmd = xstrdup(optarg);
			break;
		case 'C':
			if (flags & CLIENT_CONTROL)
				flags |= CLIENT_CONTROLCONTROL;
			else
				flags |= CLIENT_CONTROL;
			break;
		case 'V':
			printf("%s %s\n", getprogname(), VERSION);
			exit(0);
		case 'f':
			set_cfg_file(optarg);
			break;
		case 'l':
			flags |= CLIENT_LOGIN;
			break;
		case 'L':
			free(label);
			label = xstrdup(optarg);
			break;
		case 'q':
			break;
		case 'S':
			free(path);
			path = xstrdup(optarg);
			break;
		case 'u':
			flags |= CLIENT_UTF8;
			break;
		case 'v':
			log_add_level();
			break;
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	if (shellcmd != NULL && argc != 0)
		usage();

	if ((ptm_fd = getptmfd()) == -1)
		err(1, "getptmfd");
	if (pledge("stdio rpath wpath cpath flock fattr unix getpw sendfd "
	    "recvfd proc exec tty ps", NULL) != 0)
		err(1, "pledge");

	/*
	 * tmux is a UTF-8 terminal, so if TMUX is set, assume UTF-8.
	 * Otherwise, if the user has set LC_ALL, LC_CTYPE or LANG to contain
	 * UTF-8, it is a safe assumption that either they are using a UTF-8
	 * terminal, or if not they know that output from UTF-8-capable
	 * programs may be wrong.
	 */
	if (getenv("TMUX") != NULL)
		flags |= CLIENT_UTF8;
	else {
		s = getenv("LC_ALL");
		if (s == NULL || *s == '\0')
			s = getenv("LC_CTYPE");
		if (s == NULL || *s == '\0')
			s = getenv("LANG");
		if (s == NULL || *s == '\0')
			s = "";
		if (strcasestr(s, "UTF-8") != NULL ||
		    strcasestr(s, "UTF8") != NULL)
			flags |= CLIENT_UTF8;
	}

	global_hooks = hooks_create(NULL);

	global_environ = environ_create();
	for (var = environ; *var != NULL; var++)
		environ_put(global_environ, *var);
	if (getcwd(tmp, sizeof tmp) != NULL)
		environ_set(global_environ, "PWD", "%s", tmp);

	global_options = options_create(NULL);
	global_s_options = options_create(NULL);
	global_w_options = options_create(NULL);
	for (oe = options_table; oe->name != NULL; oe++) {
		if (oe->scope == OPTIONS_TABLE_SERVER)
			options_default(global_options, oe);
		if (oe->scope == OPTIONS_TABLE_SESSION)
			options_default(global_s_options, oe);
		if (oe->scope == OPTIONS_TABLE_WINDOW)
			options_default(global_w_options, oe);
	}

	/*
	 * The default shell comes from SHELL or from the user's passwd entry
	 * if available.
	 */
	shell = getshell();
	options_set_string(global_s_options, "default-shell", 0, "%s", shell);

	/* Override keys to vi if VISUAL or EDITOR are set. */
	if ((s = getenv("VISUAL")) != NULL || (s = getenv("EDITOR")) != NULL) {
		if (strrchr(s, '/') != NULL)
			s = strrchr(s, '/') + 1;
		if (strstr(s, "vi") != NULL)
			keys = MODEKEY_VI;
		else
			keys = MODEKEY_EMACS;
		options_set_number(global_s_options, "status-keys", keys);
		options_set_number(global_w_options, "mode-keys", keys);
	}

	/*
	 * If socket is specified on the command-line with -S or -L, it is
	 * used. Otherwise, $TMUX is checked and if that fails "default" is
	 * used.
	 */
	if (path == NULL && label == NULL) {
		s = getenv("TMUX");
		if (s != NULL && *s != '\0' && *s != ',') {
			path = xstrdup(s);
			path[strcspn(path, ",")] = '\0';
		}
	}
	if (path == NULL && (path = make_label(label)) == NULL) {
		fprintf(stderr, "can't create socket: %s\n", strerror(errno));
		exit(1);
	}
	socket_path = path;
	free(label);

	/* Pass control to the client. */
	exit(client_main(osdep_event_init(), argc, argv, flags, shellcmd));
}
Exemplo n.º 27
0
Arquivo: tmux.c Projeto: chjj/tmux
int
main(int argc, char **argv)
{
	struct passwd	*pw;
	char		*s, *path, *label, *home, **var;
	int	 	 opt, flags, quiet, keys;

#if defined(DEBUG) && defined(__OpenBSD__)
	malloc_options = (char *) "AFGJPX";
#endif

	setlocale(LC_TIME, "");

	quiet = flags = 0;
	label = path = NULL;
	login_shell = (**argv == '-');
	while ((opt = getopt(argc, argv, "2c:Cdf:lL:qS:uUVv")) != -1) {
		switch (opt) {
		case '2':
			flags |= IDENTIFY_256COLOURS;
			break;
		case 'c':
			free(shell_cmd);
			shell_cmd = xstrdup(optarg);
			break;
		case 'C':
			if (flags & IDENTIFY_CONTROL)
				flags |= IDENTIFY_TERMIOS;
			else
				flags |= IDENTIFY_CONTROL;
			break;
		case 'V':
			printf("%s %s\n", __progname, VERSION);
			exit(0);
		case 'f':
			free(cfg_file);
			cfg_file = xstrdup(optarg);
			break;
		case 'l':
			login_shell = 1;
			break;
		case 'L':
			free(label);
			label = xstrdup(optarg);
			break;
		case 'q':
			quiet = 1;
			break;
		case 'S':
			free(path);
			path = xstrdup(optarg);
			break;
		case 'u':
			flags |= IDENTIFY_UTF8;
			break;
		case 'v':
			debug_level++;
			break;
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	if (shell_cmd != NULL && argc != 0)
		usage();

	if (!(flags & IDENTIFY_UTF8)) {
		/*
		 * If the user has set whichever of LC_ALL, LC_CTYPE or LANG
		 * exist (in that order) to contain UTF-8, it is a safe
		 * assumption that either they are using a UTF-8 terminal, or
		 * if not they know that output from UTF-8-capable programs may
		 * be wrong.
		 */
		if ((s = getenv("LC_ALL")) == NULL || *s == '\0') {
			if ((s = getenv("LC_CTYPE")) == NULL || *s == '\0')
				s = getenv("LANG");
		}
		if (s != NULL && (strcasestr(s, "UTF-8") != NULL ||
		    strcasestr(s, "UTF8") != NULL))
			flags |= IDENTIFY_UTF8;
	}

	environ_init(&global_environ);
	for (var = environ; *var != NULL; var++)
		environ_put(&global_environ, *var);

	options_init(&global_options, NULL);
	options_table_populate_tree(server_options_table, &global_options);
	options_set_number(&global_options, "quiet", quiet);

	options_init(&global_s_options, NULL);
	options_table_populate_tree(session_options_table, &global_s_options);
	options_set_string(&global_s_options, "default-shell", "%s", getshell());

	options_init(&global_w_options, NULL);
	options_table_populate_tree(window_options_table, &global_w_options);

	/* Enable UTF-8 if the first client is on UTF-8 terminal. */
	if (flags & IDENTIFY_UTF8) {
		options_set_number(&global_s_options, "status-utf8", 1);
		options_set_number(&global_s_options, "mouse-utf8", 1);
		options_set_number(&global_w_options, "utf8", 1);
	}

	/* Override keys to vi if VISUAL or EDITOR are set. */
	if ((s = getenv("VISUAL")) != NULL || (s = getenv("EDITOR")) != NULL) {
		if (strrchr(s, '/') != NULL)
			s = strrchr(s, '/') + 1;
		if (strstr(s, "vi") != NULL)
			keys = MODEKEY_VI;
		else
			keys = MODEKEY_EMACS;
		options_set_number(&global_s_options, "status-keys", keys);
		options_set_number(&global_w_options, "mode-keys", keys);
	}

	/* Locate the configuration file. */
	if (cfg_file == NULL) {
		home = getenv("HOME");
		if (home == NULL || *home == '\0') {
			pw = getpwuid(getuid());
			if (pw != NULL)
				home = pw->pw_dir;
		}
		xasprintf(&cfg_file, "%s/.tmux.conf", home);
		if (access(cfg_file, R_OK) != 0 && errno == ENOENT) {
			free(cfg_file);
			cfg_file = NULL;
		}
	}

	/*
	 * Figure out the socket path. If specified on the command-line with -S
	 * or -L, use it, otherwise try $TMUX or assume -L default.
	 */
	parseenvironment();
	if (path == NULL) {
		/* If no -L, use the environment. */
		if (label == NULL) {
			if (environ_path != NULL)
				path = xstrdup(environ_path);
			else
				label = xstrdup("default");
		}

		/* -L or default set. */
		if (label != NULL) {
			if ((path = makesocketpath(label)) == NULL) {
				fprintf(stderr, "can't create socket\n");
				exit(1);
			}
		}
	}
	free(label);
	strlcpy(socket_path, path, sizeof socket_path);
	free(path);

#ifdef HAVE_SETPROCTITLE
	/* Set process title. */
	setproctitle("%s (%s)", __progname, socket_path);
#endif

	/* Pass control to the client. */
	ev_base = osdep_event_init();
	exit(client_main(argc, argv, flags));
}
Exemplo n.º 28
0
/*
######################################################################
# defaults
*/
int main(int argc, char **argv) {
int c;
int n;
int hasoffset = 0;

port = PORT;
strncpy(pass,DEFPASS,sizeof(pass));
host[0] = '\0';
resp[0] = resp[1] = 0;
unknown[0] = unknown[1] = 1;
strncpy(mesg,"Data retrieved OK",sizeof(mesg));

/* process arguments */
static struct option options[] = {
	{ "host", 1, 0, 'H' },
	{ "port", 1, 0, 'p' },
	{ "offset", 1, 0, 'o' },
	{ "module", 1, 0, 'c' },
	{ "command", 1, 0, 'c' },
	{ "cmd", 1, 0, 'c' },
	{ "arg", 1, 0, 'a' },
	{ "debug", 0, 0, 'd' },
	{ "timeout", 1, 0, 't' },
	{ "ratio", 0, 0, 'r' },
	{ "password", 1, 0, 'P' },
	{ "compat", 0, 0, 'C' }
};
while(1) {
	c = getopt_long(argc,argv,"CP:H:s:p:o:n:c:v:l:a:dt:rh",options,NULL);
	if(c == -1) break;
	switch(c) {
		case 'H':
		case 's':
			strncpy(host,optarg,sizeof(host)-1); break;
		case 'p':
			port = atoi(optarg); break;
		case 'P':
			strncpy(pass,optarg,sizeof(pass)-1); break;
		case 'o': /* offset */
		case 'n':
			n = 0; if(hasoffset || (cmd[1]>-1) || arg[1]) { n = 1; }
			offset[n] = atoi(optarg);
			hasoffset = 1;
			break;
		case 'c': /* command */
		case 'v':
			n = 0; if(cmd[n]>-1) { n = 1; }
			if(cmd[n]>-1) {
				sprintf(mesg,"You may only specify two commands.");
				outputresp();
				exit(1);
			}
			cmd[n] = getcmd(optarg);
			if(cmd[n]<0) {
				sprintf(mesg,"Invalid command [%s]",optarg);
				outputresp();
				exit(1);
			}
			break;
		case 'l': /* arg */
		case 'a':
			n = 0; if((cmd[1]>-1) || arg[0]) { n = 1; }
			arg[n] = optarg;
			break;
		case 'd':
			debugmode = 1; break;
		case 't':
			timeout = atoi(optarg);
			if(timeout < 1) { timeout = TIMEOUT; }	
			break;
		case 'r':
			ratiomode = 1; break;
		case 'h':
			dohelp(); exit(1);
		case 'C':
			compatmode = 1; break;
		default:
			sprintf(mesg,"Option was not recognised..."); 
			outputresp();
			exit(1);
	} /* switch */
} /* while loop */

if( !port || !host[0] ) {
	sprintf(mesg,"Must specify a valid port and hostname");
	outputresp();
	exit( 1 );
}

/* we need to run a second command only if the args have changed */
if((cmd[1]<0) && !arg[1] && !offset[1]) { offset[1]=1; } /* ? */
if((cmd[1]<0) && arg[1]) { cmd[1] = cmd[0]; }

if(cmd[0]<0) {
	sprintf(mesg,"No command was given.");
	outputresp(); exit(1);
}
/*
# Now we have one or two command to pass to the agent.
# We connect, and send, then listen for the response.
# Repeat for second argument if necessary
*/
#ifdef WITHALARM
/* timeout for program */
signal(SIGALRM,handler);
if(debugmode) { printf("Starting alarm for %d sec\n",timeout); fflush(NULL); }
alarm(timeout);
#endif

/* first, identify remote agent if necessary */
if((cmd[0]==8)||(cmd[1]==8)) {
    if(debugmode) { printf("Testing version\n"); fflush(NULL); }
    makesocket();
    verstr = (char *)malloc(256);
    n = ask(1,(char *)0,(double *)0,0,0,0,verstr);
    close(sock);
    if(! strcasestr(verstr,"nsclient++") ) {
    	if(debugmode) { printf("Setting compat mode\n"); fflush(NULL); }
	compatmode = 1;
    }
}

/* Connect */
if(debugmode) { printf("Starting queries\n"); fflush(NULL); }
makesocket();
n = ask(cmd[0],arg[0],&resp[0],offset[0],ratiomode,0,NULL);
close(sock);
if(n) { outputresp(); exit(0); }
else { unknown[0] = 0; }
if(cmd[1]>-1) {
	makesocket();
	n = ask(cmd[1],arg[1],&resp[1],offset[1],ratiomode,0,NULL);
	close(sock);
	if(n) { outputresp(); exit(0); }
	else { unknown[1] = 0; }
} else {
	makesocket();
	n = ask(-1,(char *)NULL,&resp[1],offset[1],ratiomode,1,NULL);
	close(sock);
	if(!n) { unknown[1] = 0; }
}
#ifdef WITHALARM
alarm(0);
#endif

sprintf(mesg,"Nagios query agent version %s",VERSION);

outputresp();
exit(0);
}
Exemplo n.º 29
0
int64_t
GetImageMetadata(const char *path, char *name)
{
	ExifData *ed;
	ExifEntry *e = NULL;
	ExifLoader *l;
	struct jpeg_decompress_struct cinfo;
	struct jpeg_error_mgr jerr;
	FILE *infile;
	int width=0, height=0, thumb=0;
	char make[32], model[64] = {'\0'};
	char b[1024];
	struct stat file;
	int64_t ret;
	image_s *imsrc;
	metadata_t m;
	uint32_t free_flags = 0xFFFFFFFF;
	memset(&m, '\0', sizeof(metadata_t));

	//DEBUG DPRINTF(E_DEBUG, L_METADATA, "Parsing %s...\n", path);
	if ( stat(path, &file) != 0 )
		return 0;
	strip_ext(name);
	//DEBUG DPRINTF(E_DEBUG, L_METADATA, " * size: %jd\n", file.st_size);

	/* MIME hard-coded to JPEG for now, until we add PNG support */
	m.mime = strdup("image/jpeg");

	l = exif_loader_new();
	exif_loader_write_file(l, path);
	ed = exif_loader_get_data(l);
	exif_loader_unref(l);
	if( !ed )
		goto no_exifdata;

	e = exif_content_get_entry (ed->ifd[EXIF_IFD_EXIF], EXIF_TAG_DATE_TIME_ORIGINAL);
	if( e || (e = exif_content_get_entry(ed->ifd[EXIF_IFD_EXIF], EXIF_TAG_DATE_TIME_DIGITIZED)) )
	{
		m.date = strdup(exif_entry_get_value(e, b, sizeof(b)));
		if( strlen(m.date) > 10 )
		{
			m.date[4] = '-';
			m.date[7] = '-';
			m.date[10] = 'T';
		}
		else {
			free(m.date);
			m.date = NULL;
		}
	}
	else {
		/* One last effort to get the date from XMP */
		image_get_jpeg_date_xmp(path, &m.date);
	}
	//DEBUG DPRINTF(E_DEBUG, L_METADATA, " * date: %s\n", m.date);

	e = exif_content_get_entry(ed->ifd[EXIF_IFD_0], EXIF_TAG_MAKE);
	if( e )
	{
		strncpyt(make, exif_entry_get_value(e, b, sizeof(b)), sizeof(make));
		e = exif_content_get_entry(ed->ifd[EXIF_IFD_0], EXIF_TAG_MODEL);
		if( e )
		{
			strncpyt(model, exif_entry_get_value(e, b, sizeof(b)), sizeof(model));
			if( !strcasestr(model, make) )
				snprintf(model, sizeof(model), "%s %s", make, exif_entry_get_value(e, b, sizeof(b)));
			m.creator = escape_tag(trim(model), 1);
		}
	}
	//DEBUG DPRINTF(E_DEBUG, L_METADATA, " * model: %s\n", model);

	e = exif_content_get_entry(ed->ifd[EXIF_IFD_0], EXIF_TAG_ORIENTATION);
	if( e )
	{
		int rotate;
		switch( exif_get_short(e->data, exif_data_get_byte_order(ed)) )
		{
		case 3:
			rotate = 180;
			break;
		case 6:
			rotate = 90;
			break;
		case 8:
			rotate = 270;
			break;
		default:
			rotate = 0;
			break;
		}
		if( rotate )
			xasprintf(&m.rotation, "%d", rotate);
	}

	if( ed->size )
	{
		/* We might need to verify that the thumbnail is 160x160 or smaller */
		if( ed->size > 12000 )
		{
			imsrc = image_new_from_jpeg(NULL, 0, (char *)ed->data, ed->size, 1, ROTATE_NONE);
			if( imsrc )
			{
 				if( (imsrc->width <= 160) && (imsrc->height <= 160) )
					thumb = 1;
				image_free(imsrc);
			}
		}
		else
			thumb = 1;
	}
	//DEBUG DPRINTF(E_DEBUG, L_METADATA, " * thumbnail: %d\n", thumb);

	exif_data_unref(ed);

no_exifdata:
	/* If SOF parsing fails, then fall through to reading the JPEG data with libjpeg to get the resolution */
	if( image_get_jpeg_resolution(path, &width, &height) != 0 || !width || !height )
	{
		infile = fopen(path, "r");
		if( infile )
		{
			cinfo.err = jpeg_std_error(&jerr);
			jerr.error_exit = libjpeg_error_handler;
			jpeg_create_decompress(&cinfo);
			if( setjmp(setjmp_buffer) )
				goto error;
			jpeg_stdio_src(&cinfo, infile);
			jpeg_read_header(&cinfo, TRUE);
			jpeg_start_decompress(&cinfo);
			width = cinfo.output_width;
			height = cinfo.output_height;
			error:
			jpeg_destroy_decompress(&cinfo);
			fclose(infile);
		}
	}
	//DEBUG DPRINTF(E_DEBUG, L_METADATA, " * resolution: %dx%d\n", width, height);

	if( !width || !height )
	{
		free_metadata(&m, free_flags);
		return 0;
	}
	if( width <= 640 && height <= 480 )
		m.dlna_pn = strdup("JPEG_SM");
	else if( width <= 1024 && height <= 768 )
		m.dlna_pn = strdup("JPEG_MED");
	else if( (width <= 4096 && height <= 4096) || !GETFLAG(DLNA_STRICT_MASK) )
		m.dlna_pn = strdup("JPEG_LRG");
	xasprintf(&m.resolution, "%dx%d", width, height);

	ret = sql_exec(db, "INSERT into DETAILS"
	                   " (PATH, TITLE, SIZE, TIMESTAMP, DATE, RESOLUTION,"
	                    " ROTATION, THUMBNAIL, CREATOR, DLNA_PN, MIME) "
	                   "VALUES"
	                   " (%Q, '%q', %lld, %ld, %Q, %Q, %Q, %d, %Q, %Q, %Q);",
	                   path, name, (long long)file.st_size, file.st_mtime, m.date, m.resolution,
	                   m.rotation, thumb, m.creator, m.dlna_pn, m.mime);
	if( ret != SQLITE_OK )
	{
		fprintf(stderr, "Error inserting details for '%s'!\n", path);
		ret = 0;
	}
	else
	{
		ret = sqlite3_last_insert_rowid(db);
	}
	free_metadata(&m, free_flags);

	return ret;
}
Exemplo n.º 30
0
/* ProcessSSDPRequest()
 * process SSDP M-SEARCH requests and responds to them */
void
ProcessSSDPRequest(int s, unsigned short port)
/*ProcessSSDPRequest(int s, struct lan_addr_s * lan_addr, int n_lan_addr,
                   unsigned short port)*/
{
	int n;
	char bufr[1500];
	socklen_t len_r;
	struct sockaddr_in sendername;
	int i;
	char *st = NULL, *mx = NULL, *man = NULL, *mx_end = NULL;
	int man_len = 0;
	len_r = sizeof(struct sockaddr_in);

	n = recvfrom(s, bufr, sizeof(bufr)-1, 0,
	             (struct sockaddr *)&sendername, &len_r);
	if(n < 0)
	{
		DPRINTF(E_ERROR, L_SSDP, "recvfrom(udp): %s\n", strerror(errno));
		return;
	}
	bufr[n] = '\0';

	if(memcmp(bufr, "NOTIFY", 6) == 0)
	{
		char *loc = NULL, *srv = NULL, *nts = NULL, *nt = NULL;
		int loc_len = 0;
		//DEBUG DPRINTF(E_DEBUG, L_SSDP, "Received SSDP notify:\n%.*s", n, bufr);
		for(i=0; i < n; i++)
		{
			if( bufr[i] == '*' )
				break;
		}
		if( !strcasestr(bufr+i, "HTTP/1.1") )
		{
			return;
		}
		while(i < n)
		{
			while((i < n - 2) && (bufr[i] != '\r' || bufr[i+1] != '\n'))
				i++;
			i += 2;
			if(strncasecmp(bufr+i, "SERVER:", 7) == 0)
			{
				srv = bufr+i+7;
				while(*srv == ' ' || *srv == '\t') srv++;
			}
			else if(strncasecmp(bufr+i, "LOCATION:", 9) == 0)
			{
				loc = bufr+i+9;
				while(*loc == ' ' || *loc == '\t') loc++;
				while(loc[loc_len]!='\r' && loc[loc_len]!='\n') loc_len++;
			}
			else if(strncasecmp(bufr+i, "NTS:", 4) == 0)
			{
				nts = bufr+i+4;
				while(*nts == ' ' || *nts == '\t') nts++;
			}
			else if(strncasecmp(bufr+i, "NT:", 3) == 0)
			{
				nt = bufr+i+3;
				while(*nt == ' ' || *nt == '\t') nt++;
			}
		}
		if( !loc || !srv || !nt || !nts || (strncmp(nts, "ssdp:alive", 10) != 0) ||
		    (strncmp(nt, "urn:schemas-upnp-org:device:MediaRenderer", 41) != 0) )
		{
			return;
		}
		loc[loc_len] = '\0';
		if( (strncmp(srv, "Allegro-Software-RomPlug", 24) == 0) || /* Roku */
		    (strstr(loc, "SamsungMRDesc.xml") != NULL) || /* Samsung TV */
		    (strstrc(srv, "DigiOn DiXiM", '\r') != NULL) ) /* Marantz Receiver */
		{
			/* Check if the client is already in cache */
			i = SearchClientCache(sendername.sin_addr, 1);
			if( i >= 0 )
			{
				if( clients[i].type < EStandardDLNA150 &&
				    clients[i].type != ESamsungSeriesA )
				{
					clients[i].age = time(NULL);
					return;
				}
			}
			ParseUPnPClient(loc);
		}
		return;
	}
	else if(memcmp(bufr, "M-SEARCH", 8) == 0)
	{
		int st_len = 0, mx_len = 0, mx_val = 0;
		//DPRINTF(E_DEBUG, L_SSDP, "Received SSDP request:\n%.*s\n", n, bufr);
		for(i=0; i < n; i++)
		{
			if( bufr[i] == '*' )
				break;
		}
		if( !strcasestr(bufr+i, "HTTP/1.1") )
		{
			return;
		}
		while(i < n)
		{
			while((i < n - 2) && (bufr[i] != '\r' || bufr[i+1] != '\n'))
				i++;
			i += 2;
			if(strncasecmp(bufr+i, "ST:", 3) == 0)
			{
				st = bufr+i+3;
				st_len = 0;
				while(*st == ' ' || *st == '\t') st++;
				while(st[st_len]!='\r' && st[st_len]!='\n') st_len++;
			}
			else if(strncasecmp(bufr+i, "MX:", 3) == 0)
			{
				mx = bufr+i+3;
				mx_len = 0;
				while(*mx == ' ' || *mx == '\t') mx++;
				while(mx[mx_len]!='\r' && mx[mx_len]!='\n') mx_len++;
        			mx_val = strtol(mx, &mx_end, 10);
			}
			else if(strncasecmp(bufr+i, "MAN:", 4) == 0)
			{
				man = bufr+i+4;
				man_len = 0;
				while(*man == ' ' || *man == '\t') man++;
				while(man[man_len]!='\r' && man[man_len]!='\n') man_len++;
			}
		}
		/*DPRINTF(E_INFO, L_SSDP, "SSDP M-SEARCH packet received from %s:%d\n",
	           inet_ntoa(sendername.sin_addr),
	           ntohs(sendername.sin_port) );*/
		if( GETFLAG(DLNA_STRICT_MASK) && (ntohs(sendername.sin_port) <= 1024 || ntohs(sendername.sin_port) == 1900) )
		{
			DPRINTF(E_INFO, L_SSDP, "WARNING: Ignoring invalid SSDP M-SEARCH from %s [bad source port %d]\n",
			   inet_ntoa(sendername.sin_addr), ntohs(sendername.sin_port));
		}
		else if( !man || (strncmp(man, "\"ssdp:discover\"", 15) != 0) )
		{
			DPRINTF(E_INFO, L_SSDP, "WARNING: Ignoring invalid SSDP M-SEARCH from %s [bad MAN header %.*s]\n",
			   inet_ntoa(sendername.sin_addr), man_len, man);
		}
		else if( !mx || mx == mx_end || mx_val < 0 ) {
			DPRINTF(E_INFO, L_SSDP, "WARNING: Ignoring invalid SSDP M-SEARCH from %s [bad MX header %.*s]\n",
			   inet_ntoa(sendername.sin_addr), mx_len, mx);
		}
		else if( st && (st_len > 0) )
		{
			int l;
			int lan_addr_index = 0;
			/* find in which sub network the client is */
			for(i = 0; i<n_lan_addr; i++)
			{
				if( (sendername.sin_addr.s_addr & lan_addr[i].mask.s_addr)
				   == (lan_addr[i].addr.s_addr & lan_addr[i].mask.s_addr))
				{
					lan_addr_index = i;
					break;
				}
			}
			if( i == n_lan_addr )
			{
				DPRINTF(E_DEBUG, L_SSDP, "Ignoring SSDP M-SEARCH on other interface [%s]\n",
					inet_ntoa(sendername.sin_addr));
				return;
			}
			DPRINTF(E_INFO, L_SSDP, "SSDP M-SEARCH from %s:%d ST: %.*s, MX: %.*s, MAN: %.*s\n",
	        	   inet_ntoa(sendername.sin_addr),
	           	   ntohs(sendername.sin_port),
			   st_len, st, mx_len, mx, man_len, man);
			/* Responds to request with a device as ST header */
			for(i = 0; known_service_types[i]; i++)
			{
				l = strlen(known_service_types[i]);
				if(l<=st_len && (0 == memcmp(st, known_service_types[i], l)))
				{
					/* Check version number - must always be 1 currently. */
					if( (st[st_len-2] == ':') && (atoi(st+st_len-1) != 1) )
						break;
					_usleep(random()>>20);
					SendSSDPAnnounce2(s, sendername,
					                  i,
					                  lan_addr[lan_addr_index].str, port);
					break;
				}
			}
			/* Responds to request with ST: ssdp:all */
			/* strlen("ssdp:all") == 8 */
			if(st_len==8 && (0 == memcmp(st, "ssdp:all", 8)))
			{
				for(i=0; known_service_types[i]; i++)
				{
					l = (int)strlen(known_service_types[i]);
					SendSSDPAnnounce2(s, sendername,
					                  i,
					                  lan_addr[lan_addr_index].str, port);
				}
			}
		}