コード例 #1
0
ファイル: position.c プロジェクト: dreiss/M1-Android
/* Returns the number of frames actually skipped, -1 on error.
 *
 * Values in header are not changed if retval!=nframes.
 * This is not necessary because gethdr() doesn't clobber
 * the contents of header, but I don't want to rely on that. 
 */
int ffwd(struct AUDIO_HEADER *header, int nframes)
{
int cnt=0,g;
int hsize,bitrate,fs,mean_frame_size;
struct AUDIO_HEADER tmp;
	memcpy(&tmp,header,sizeof(tmp));

	while (cnt < nframes) {
	        if (tmp.ID)
        	        if (tmp.mode==3) hsize=21;
                	else hsize=36;
        	else
                	if (tmp.mode==3) hsize=13;
               	 	else  hsize=21;
                if (tmp.protection_bit==0) hsize+=2;
		if ((g=dummy_getinfo(hsize)))  /* dummy_getinfo: reads hsize-4 bytes */
			switch (g) {
                        case GETHDR_EOF: return cnt;
			case GETHDR_ERR:
			default:	return -1;
                        }

	        bitrate=t_bitrate[tmp.ID][3-tmp.layer][tmp.bitrate_index];
        	fs=t_sampling_frequency[tmp.ID][tmp.sampling_frequency];		
	        if (tmp.ID) mean_frame_size=144000*bitrate/fs;
	        else mean_frame_size=72000*bitrate/fs;
		fillbfr(mean_frame_size + tmp.padding_bit - hsize);

		if ((g=gethdr(&tmp))) 
			switch (g) {
			case GETHDR_EOF: return cnt;
			case GETHDR_ERR:
			default:	return -1;
			}
		cnt++;
	}	

	memcpy(header,&tmp,sizeof(tmp));		
	return cnt;
}
コード例 #2
0
int wget_main(int argc UNUSED_PARAM, char **argv)
{
    char buf[512];
    struct host_info server, target;
    len_and_sockaddr *lsa;
    unsigned opt;
    int redir_limit;
    char *proxy = NULL;
    char *dir_prefix = NULL;
#if ENABLE_FEATURE_WGET_LONG_OPTIONS
    char *post_data;
    char *extra_headers = NULL;
    llist_t *headers_llist = NULL;
#endif
    FILE *sfp;                      /* socket to web/ftp server         */
    FILE *dfp;                      /* socket to ftp server (data)      */
    char *fname_out;                /* where to direct output (-O)      */
    int output_fd = -1;
    bool use_proxy;                 /* Use proxies if env vars are set  */
    const char *proxy_flag = "on";  /* Use proxies if env vars are set  */
    const char *user_agent = "Wget";/* "User-Agent" header field        */

    static const char keywords[] ALIGN1 =
        "content-length\0""transfer-encoding\0""chunked\0""location\0";
    enum {
        KEY_content_length = 1, KEY_transfer_encoding, KEY_chunked, KEY_location
    };
#if ENABLE_FEATURE_WGET_LONG_OPTIONS
    static const char wget_longopts[] ALIGN1 =
        /* name, has_arg, val */
        "continue\0"         No_argument       "c"
        "spider\0"           No_argument       "s"
        "quiet\0"            No_argument       "q"
        "output-document\0"  Required_argument "O"
        "directory-prefix\0" Required_argument "P"
        "proxy\0"            Required_argument "Y"
        "user-agent\0"       Required_argument "U"
        /* Ignored: */
        // "tries\0"            Required_argument "t"
        // "timeout\0"          Required_argument "T"
        /* Ignored (we always use PASV): */
        "passive-ftp\0"      No_argument       "\xff"
        "header\0"           Required_argument "\xfe"
        "post-data\0"        Required_argument "\xfd"
        /* Ignored (we don't do ssl) */
        "no-check-certificate\0" No_argument   "\xfc"
        ;
#endif

    INIT_G();

#if ENABLE_FEATURE_WGET_LONG_OPTIONS
    applet_long_options = wget_longopts;
#endif
    /* server.allocated = target.allocated = NULL; */
    opt_complementary = "-1" IF_FEATURE_WGET_LONG_OPTIONS(":\xfe::");
    opt = getopt32(argv, "csqO:P:Y:U:" /*ignored:*/ "t:T:",
                   &fname_out, &dir_prefix,
                   &proxy_flag, &user_agent,
                   NULL, /* -t RETRIES */
                   NULL /* -T NETWORK_READ_TIMEOUT */
                   IF_FEATURE_WGET_LONG_OPTIONS(, &headers_llist)
                   IF_FEATURE_WGET_LONG_OPTIONS(, &post_data)
                  );
#if ENABLE_FEATURE_WGET_LONG_OPTIONS
    if (headers_llist) {
        int size = 1;
        char *cp;
        llist_t *ll = headers_llist;
        while (ll) {
            size += strlen(ll->data) + 2;
            ll = ll->link;
        }
        extra_headers = cp = xmalloc(size);
        while (headers_llist) {
            cp += sprintf(cp, "%s\r\n", (char*)llist_pop(&headers_llist));
        }
    }
#endif

    /* TODO: compat issue: should handle "wget URL1 URL2..." */

    target.user = NULL;
    parse_url(argv[optind], &target);

    /* Use the proxy if necessary */
    use_proxy = (strcmp(proxy_flag, "off") != 0);
    if (use_proxy) {
        proxy = getenv(target.is_ftp ? "ftp_proxy" : "http_proxy");
        if (proxy && proxy[0]) {
            server.user = NULL;
            parse_url(proxy, &server);
        } else {
            use_proxy = 0;
        }
    }
    if (!use_proxy) {
        server.port = target.port;
        if (ENABLE_FEATURE_IPV6) {
            server.host = xstrdup(target.host);
        } else {
            server.host = target.host;
        }
    }

    if (ENABLE_FEATURE_IPV6)
        strip_ipv6_scope_id(target.host);

    /* Guess an output filename, if there was no -O FILE */
    if (!(opt & WGET_OPT_OUTNAME)) {
        fname_out = bb_get_last_path_component_nostrip(target.path);
        /* handle "wget http://kernel.org//" */
        if (fname_out[0] == '/' || !fname_out[0])
            fname_out = (char*)"index.html";
        /* -P DIR is considered only if there was no -O FILE */
        if (dir_prefix)
            fname_out = concat_path_file(dir_prefix, fname_out);
    } else {
        if (LONE_DASH(fname_out)) {
            /* -O - */
            output_fd = 1;
            opt &= ~WGET_OPT_CONTINUE;
        }
    }
#if ENABLE_FEATURE_WGET_STATUSBAR
    G.curfile = bb_get_last_path_component_nostrip(fname_out);
#endif

    /* Impossible?
    if ((opt & WGET_OPT_CONTINUE) && !fname_out)
    	bb_error_msg_and_die("can't specify continue (-c) without a filename (-O)");
    */

    /* Determine where to start transfer */
    if (opt & WGET_OPT_CONTINUE) {
        output_fd = open(fname_out, O_WRONLY);
        if (output_fd >= 0) {
            G.beg_range = xlseek(output_fd, 0, SEEK_END);
        }
        /* File doesn't exist. We do not create file here yet.
         * We are not sure it exists on remove side */
    }

    redir_limit = 5;
resolve_lsa:
    lsa = xhost2sockaddr(server.host, server.port);
    if (!(opt & WGET_OPT_QUIET)) {
        char *s = xmalloc_sockaddr2dotted(&lsa->u.sa);
        fprintf(stderr, "Connecting to %s (%s)\n", server.host, s);
        free(s);
    }
establish_session:
    if (use_proxy || !target.is_ftp) {
        /*
         *  HTTP session
         */
        char *str;
        int status;

        /* Open socket to http server */
        sfp = open_socket(lsa);

        /* Send HTTP request */
        if (use_proxy) {
            fprintf(sfp, "GET %stp://%s/%s HTTP/1.1\r\n",
                    target.is_ftp ? "f" : "ht", target.host,
                    target.path);
        } else {
            if (opt & WGET_OPT_POST_DATA)
                fprintf(sfp, "POST /%s HTTP/1.1\r\n", target.path);
            else
                fprintf(sfp, "GET /%s HTTP/1.1\r\n", target.path);
        }

        fprintf(sfp, "Host: %s\r\nUser-Agent: %s\r\n",
                target.host, user_agent);

#if ENABLE_FEATURE_WGET_AUTHENTICATION
        if (target.user) {
            fprintf(sfp, "Proxy-Authorization: Basic %s\r\n"+6,
                    base64enc_512(buf, target.user));
        }
        if (use_proxy && server.user) {
            fprintf(sfp, "Proxy-Authorization: Basic %s\r\n",
                    base64enc_512(buf, server.user));
        }
#endif

        if (G.beg_range)
            fprintf(sfp, "Range: bytes=%"OFF_FMT"u-\r\n", G.beg_range);
#if ENABLE_FEATURE_WGET_LONG_OPTIONS
        if (extra_headers)
            fputs(extra_headers, sfp);

        if (opt & WGET_OPT_POST_DATA) {
            char *estr = URL_escape(post_data);
            fprintf(sfp, "Content-Type: application/x-www-form-urlencoded\r\n");
            fprintf(sfp, "Content-Length: %u\r\n" "\r\n" "%s",
                    (int) strlen(estr), estr);
            /*fprintf(sfp, "Connection: Keep-Alive\r\n\r\n");*/
            /*fprintf(sfp, "%s\r\n", estr);*/
            free(estr);
        } else
#endif
        {   /* If "Connection:" is needed, document why */
            fprintf(sfp, /* "Connection: close\r\n" */ "\r\n");
        }

        /*
         * Retrieve HTTP response line and check for "200" status code.
         */
read_response:
        if (fgets(buf, sizeof(buf), sfp) == NULL)
            bb_error_msg_and_die("no response from server");

        str = buf;
        str = skip_non_whitespace(str);
        str = skip_whitespace(str);
        // FIXME: no error check
        // xatou wouldn't work: "200 OK"
        status = atoi(str);
        switch (status) {
        case 0:
        case 100:
            while (gethdr(buf, sizeof(buf), sfp /*, &n*/) != NULL)
                /* eat all remaining headers */;
            goto read_response;
        case 200:
        /*
        Response 204 doesn't say "null file", it says "metadata
        has changed but data didn't":

        "10.2.5 204 No Content
        The server has fulfilled the request but does not need to return
        an entity-body, and might want to return updated metainformation.
        The response MAY include new or updated metainformation in the form
        of entity-headers, which if present SHOULD be associated with
        the requested variant.

        If the client is a user agent, it SHOULD NOT change its document
        view from that which caused the request to be sent. This response
        is primarily intended to allow input for actions to take place
        without causing a change to the user agent's active document view,
        although any new or updated metainformation SHOULD be applied
        to the document currently in the user agent's active view.

        The 204 response MUST NOT include a message-body, and thus
        is always terminated by the first empty line after the header fields."

        However, in real world it was observed that some web servers
        (e.g. Boa/0.94.14rc21) simply use code 204 when file size is zero.
        */
        case 204:
            break;
        case 300:	/* redirection */
        case 301:
        case 302:
        case 303:
            break;
        case 206:
            if (G.beg_range)
                break;
        /* fall through */
        default:
            bb_error_msg_and_die("server returned error: %s", sanitize_string(buf));
        }

        /*
         * Retrieve HTTP headers.
         */
        while ((str = gethdr(buf, sizeof(buf), sfp /*, &n*/)) != NULL) {
            /* gethdr converted "FOO:" string to lowercase */
            smalluint key;
            /* strip trailing whitespace */
            char *s = strchrnul(str, '\0') - 1;
            while (s >= str && (*s == ' ' || *s == '\t')) {
                *s = '\0';
                s--;
            }
            key = index_in_strings(keywords, buf) + 1;
            if (key == KEY_content_length) {
                G.content_len = BB_STRTOOFF(str, NULL, 10);
                if (G.content_len < 0 || errno) {
                    bb_error_msg_and_die("content-length %s is garbage", sanitize_string(str));
                }
                G.got_clen = 1;
                continue;
            }
            if (key == KEY_transfer_encoding) {
                if (index_in_strings(keywords, str_tolower(str)) + 1 != KEY_chunked)
                    bb_error_msg_and_die("transfer encoding '%s' is not supported", sanitize_string(str));
                G.chunked = G.got_clen = 1;
            }
            if (key == KEY_location && status >= 300) {
                if (--redir_limit == 0)
                    bb_error_msg_and_die("too many redirections");
                fclose(sfp);
                G.got_clen = 0;
                G.chunked = 0;
                if (str[0] == '/')
                    /* free(target.allocated); */
                    target.path = /* target.allocated = */ xstrdup(str+1);
                /* lsa stays the same: it's on the same server */
                else {
                    parse_url(str, &target);
                    if (!use_proxy) {
                        server.host = target.host;
                        /* strip_ipv6_scope_id(target.host); - no! */
                        /* we assume remote never gives us IPv6 addr with scope id */
                        server.port = target.port;
                        free(lsa);
                        goto resolve_lsa;
                    } /* else: lsa stays the same: we use proxy */
                }
                goto establish_session;
            }
        }
//		if (status >= 300)
//			bb_error_msg_and_die("bad redirection (no Location: header from server)");

        /* For HTTP, data is pumped over the same connection */
        dfp = sfp;

    } else {
        /*
         *  FTP session
         */
        sfp = prepare_ftp_session(&dfp, &target, lsa);
    }

    if (opt & WGET_OPT_SPIDER) {
        if (ENABLE_FEATURE_CLEAN_UP)
            fclose(sfp);
        return EXIT_SUCCESS;
    }

    if (output_fd < 0) {
        int o_flags = O_WRONLY | O_CREAT | O_TRUNC | O_EXCL;
        /* compat with wget: -O FILE can overwrite */
        if (opt & WGET_OPT_OUTNAME)
            o_flags = O_WRONLY | O_CREAT | O_TRUNC;
        output_fd = xopen(fname_out, o_flags);
    }

    retrieve_file_data(dfp, output_fd);
    xclose(output_fd);

    if (dfp != sfp) {
        /* It's ftp. Close it properly */
        fclose(dfp);
        if (ftpcmd(NULL, NULL, sfp, buf) != 226)
            bb_error_msg_and_die("ftp error: %s", sanitize_string(buf+4));
        /* ftpcmd("QUIT", NULL, sfp, buf); - why bother? */
    }

    return EXIT_SUCCESS;
}
コード例 #3
0
ファイル: client.c プロジェクト: BrettKoenig/ServerInC
int main(int argc, char *argv[]) {

  int serverPort, sd, rc, n, echoLen, flags, error, timeOut, fd, seqnum, totalseq, rcvdNumber;
  struct sockaddr_in cliAddr, remoteServAddr, echoServAddr;
  struct hostent *h;
  char msg[MAX_MSG], *msgptr;


  /* check command line args */
  if(argc<4) {
    printf("usage : %s <sender_hostname> <sender_portnumber> <filename> \n", argv[0]);
    exit(1);
  }

  /* get server IP address (no check if input is IP address or DNS name */
  h = gethostbyname(argv[1]);
  if(h==NULL) {
    printf("%s: unknown host '%s' \n", argv[0], argv[1]);
    exit(1);
  }

  printf("%s: sending data to '%s' (IP : %s) \n", argv[0], h->h_name,
	 inet_ntoa(*(struct in_addr *)h->h_addr_list[0]));

  remoteServAddr.sin_family = h->h_addrtype;
  memcpy((char *) &remoteServAddr.sin_addr.s_addr,
	 h->h_addr_list[0], h->h_length);
  serverPort = atoi(argv[2]);
  remoteServAddr.sin_port = htons(serverPort);

  /* socket creation */
  sd = socket(AF_INET,SOCK_DGRAM,0);
  if(sd<0) {
    printf("%s: cannot open socket \n",argv[0]);
    exit(1);
  }

  /* bind any port */
  cliAddr.sin_family = AF_INET;
  cliAddr.sin_addr.s_addr = htonl(INADDR_ANY);
  cliAddr.sin_port = htons(0);

  rc = bind(sd, (struct sockaddr *) &cliAddr, sizeof(cliAddr));
  if(rc<0) {
    printf("%s: cannot bind port\n", argv[0]);
    exit(1);
  }

  flags = 0;
  timeOut = 100; // ms

  /* send data */
  rc = sendto(sd, argv[3], strlen(argv[3])+1, flags,
	(struct sockaddr *) &remoteServAddr,
	sizeof(remoteServAddr));

  if(rc<0) {
    printf("%s: cannot send data \n",argv[0]);
    close(sd);
    exit(1);
  }

  /* open file for writing */
  fd = open(argv[3], O_WRONLY | O_CREAT);

  /* retrieve and process packets */
  while(1) {
    /* init buffer */
    memset(msg,0x0,MAX_MSG);

    while (!isReadable(sd,&error,timeOut)) printf(".");
    printf("\n");

    /* receive echoed message */
    echoLen = sizeof(echoServAddr);
    n = recvfrom(sd, msg, MAX_MSG + 2 * HEADER_FIELD_LENGTH, flags,
      (struct sockaddr *) &echoServAddr, &echoLen);
    rcvdNumber++;

    if(n<0) {
      printf("%s: cannot receive data \n",argv[0]);
    }

    /* process message header */
    msgptr = msg;
    seqnum = gethdr(msgptr);
    msgptr += HEADER_FIELD_LENGTH;
    totalseq = gethdr(msgptr);
    msgptr += HEADER_FIELD_LENGTH;

    /* print received message */
    printf("%s: Received Seq# %d : %d of %d from %s:UDP%u \n",
      argv[0],(seqnum+1)%2,seqnum,totalseq,inet_ntoa(echoServAddr.sin_addr),
      ntohs(echoServAddr.sin_port));

    /* print message to file */
    write(fd, msgptr, strlen(msgptr));

   //use SendTo here for ACK

    /* halt if all packets received */
    if (seqnum == totalseq) {
      printf("%d of %d packets received", rcvdNumber, totalseq);
      break;
    }
  }

  /* close file */
  close(fd);

  return 1;

}
コード例 #4
0
ファイル: wget.c プロジェクト: martinbj2008/busybox
static void download_one_url(const char *url)
{
	bool use_proxy;                 /* Use proxies if env vars are set  */
	int redir_limit;
	len_and_sockaddr *lsa;
	FILE *sfp;                      /* socket to web/ftp server         */
	FILE *dfp;                      /* socket to ftp server (data)      */
	char *proxy = NULL;
	char *fname_out_alloc;
	char *redirected_path = NULL;
	struct host_info server;
	struct host_info target;

	server.allocated = NULL;
	target.allocated = NULL;
	server.user = NULL;
	target.user = NULL;

	parse_url(url, &target);

	/* Use the proxy if necessary */
	use_proxy = (strcmp(G.proxy_flag, "off") != 0);
	if (use_proxy) {
		proxy = getenv(target.is_ftp ? "ftp_proxy" : "http_proxy");
		use_proxy = (proxy && proxy[0]);
		if (use_proxy)
			parse_url(proxy, &server);
	}
	if (!use_proxy) {
		server.port = target.port;
		if (ENABLE_FEATURE_IPV6) {
			//free(server.allocated); - can't be non-NULL
			server.host = server.allocated = xstrdup(target.host);
		} else {
			server.host = target.host;
		}
	}

	if (ENABLE_FEATURE_IPV6)
		strip_ipv6_scope_id(target.host);

	/* If there was no -O FILE, guess output filename */
	fname_out_alloc = NULL;
	if (!(option_mask32 & WGET_OPT_OUTNAME)) {
		G.fname_out = bb_get_last_path_component_nostrip(target.path);
		/* handle "wget http://kernel.org//" */
		if (G.fname_out[0] == '/' || !G.fname_out[0])
			G.fname_out = (char*)"index.html";
		/* -P DIR is considered only if there was no -O FILE */
		if (G.dir_prefix)
			G.fname_out = fname_out_alloc = concat_path_file(G.dir_prefix, G.fname_out);
		else {
			/* redirects may free target.path later, need to make a copy */
			G.fname_out = fname_out_alloc = xstrdup(G.fname_out);
		}
	}
#if ENABLE_FEATURE_WGET_STATUSBAR
	G.curfile = bb_get_last_path_component_nostrip(G.fname_out);
#endif

	/* Determine where to start transfer */
	G.beg_range = 0;
	if (option_mask32 & WGET_OPT_CONTINUE) {
		G.output_fd = open(G.fname_out, O_WRONLY);
		if (G.output_fd >= 0) {
			G.beg_range = xlseek(G.output_fd, 0, SEEK_END);
		}
		/* File doesn't exist. We do not create file here yet.
		 * We are not sure it exists on remote side */
	}

	redir_limit = 5;
 resolve_lsa:
	lsa = xhost2sockaddr(server.host, server.port);
	if (!(option_mask32 & WGET_OPT_QUIET)) {
		char *s = xmalloc_sockaddr2dotted(&lsa->u.sa);
		fprintf(stderr, "Connecting to %s (%s)\n", server.host, s);
		free(s);
	}
 establish_session:
	/*G.content_len = 0; - redundant, got_clen = 0 is enough */
	G.got_clen = 0;
	G.chunked = 0;
	if (use_proxy || !target.is_ftp) {
		/*
		 *  HTTP session
		 */
		char *str;
		int status;


		/* Open socket to http server */
		sfp = open_socket(lsa);

		/* Send HTTP request */
		if (use_proxy) {
			fprintf(sfp, "GET %stp://%s/%s HTTP/1.1\r\n",
				target.is_ftp ? "f" : "ht", target.host,
				target.path);
		} else {
			if (option_mask32 & WGET_OPT_POST_DATA)
				fprintf(sfp, "POST /%s HTTP/1.1\r\n", target.path);
			else
				fprintf(sfp, "GET /%s HTTP/1.1\r\n", target.path);
		}

		fprintf(sfp, "Host: %s\r\nUser-Agent: %s\r\n",
			target.host, G.user_agent);

		/* Ask server to close the connection as soon as we are done
		 * (IOW: we do not intend to send more requests)
		 */
		fprintf(sfp, "Connection: close\r\n");

#if ENABLE_FEATURE_WGET_AUTHENTICATION
		if (target.user) {
			fprintf(sfp, "Proxy-Authorization: Basic %s\r\n"+6,
				base64enc(target.user));
		}
		if (use_proxy && server.user) {
			fprintf(sfp, "Proxy-Authorization: Basic %s\r\n",
				base64enc(server.user));
		}
#endif

		if (G.beg_range != 0)
			fprintf(sfp, "Range: bytes=%"OFF_FMT"u-\r\n", G.beg_range);

#if ENABLE_FEATURE_WGET_LONG_OPTIONS
		if (G.extra_headers)
			fputs(G.extra_headers, sfp);

		if (option_mask32 & WGET_OPT_POST_DATA) {
			fprintf(sfp,
				"Content-Type: application/x-www-form-urlencoded\r\n"
				"Content-Length: %u\r\n"
				"\r\n"
				"%s",
				(int) strlen(G.post_data), G.post_data
			);
		} else
#endif
		{
			fprintf(sfp, "\r\n");
		}

		fflush(sfp);

		/*
		 * Retrieve HTTP response line and check for "200" status code.
		 */
 read_response:
		fgets_and_trim(sfp);

		str = G.wget_buf;
		str = skip_non_whitespace(str);
		str = skip_whitespace(str);
		// FIXME: no error check
		// xatou wouldn't work: "200 OK"
		status = atoi(str);
		switch (status) {
		case 0:
		case 100:
			while (gethdr(sfp) != NULL)
				/* eat all remaining headers */;
			goto read_response;
		case 200:
/*
Response 204 doesn't say "null file", it says "metadata
has changed but data didn't":

"10.2.5 204 No Content
The server has fulfilled the request but does not need to return
an entity-body, and might want to return updated metainformation.
The response MAY include new or updated metainformation in the form
of entity-headers, which if present SHOULD be associated with
the requested variant.

If the client is a user agent, it SHOULD NOT change its document
view from that which caused the request to be sent. This response
is primarily intended to allow input for actions to take place
without causing a change to the user agent's active document view,
although any new or updated metainformation SHOULD be applied
to the document currently in the user agent's active view.

The 204 response MUST NOT include a message-body, and thus
is always terminated by the first empty line after the header fields."

However, in real world it was observed that some web servers
(e.g. Boa/0.94.14rc21) simply use code 204 when file size is zero.
*/
		case 204:
			if (G.beg_range != 0) {
				/* "Range:..." was not honored by the server.
				 * Restart download from the beginning.
				 */
				reset_beg_range_to_zero();
			}
			break;
		case 300:  /* redirection */
		case 301:
		case 302:
		case 303:
			break;
		case 206: /* Partial Content */
			if (G.beg_range != 0)
				/* "Range:..." worked. Good. */
				break;
			/* Partial Content even though we did not ask for it??? */
			/* fall through */
		default:
			bb_error_msg_and_die("server returned error: %s", sanitize_string(G.wget_buf));
		}

		/*
		 * Retrieve HTTP headers.
		 */
		while ((str = gethdr(sfp)) != NULL) {
			static const char keywords[] ALIGN1 =
				"content-length\0""transfer-encoding\0""location\0";
			enum {
				KEY_content_length = 1, KEY_transfer_encoding, KEY_location
			};
			smalluint key;

			/* gethdr converted "FOO:" string to lowercase */

			/* strip trailing whitespace */
			char *s = strchrnul(str, '\0') - 1;
			while (s >= str && (*s == ' ' || *s == '\t')) {
				*s = '\0';
				s--;
			}
			key = index_in_strings(keywords, G.wget_buf) + 1;
			if (key == KEY_content_length) {
				G.content_len = BB_STRTOOFF(str, NULL, 10);
				if (G.content_len < 0 || errno) {
					bb_error_msg_and_die("content-length %s is garbage", sanitize_string(str));
				}
				G.got_clen = 1;
				continue;
			}
			if (key == KEY_transfer_encoding) {
				if (strcmp(str_tolower(str), "chunked") != 0)
					bb_error_msg_and_die("transfer encoding '%s' is not supported", sanitize_string(str));
				G.chunked = 1;
			}
			if (key == KEY_location && status >= 300) {
				if (--redir_limit == 0)
					bb_error_msg_and_die("too many redirections");
				fclose(sfp);
				if (str[0] == '/') {
					free(redirected_path);
					target.path = redirected_path = xstrdup(str+1);
					/* lsa stays the same: it's on the same server */
				} else {
					parse_url(str, &target);
					if (!use_proxy) {
						free(server.allocated);
						server.allocated = NULL;
						server.host = target.host;
						/* strip_ipv6_scope_id(target.host); - no! */
						/* we assume remote never gives us IPv6 addr with scope id */
						server.port = target.port;
						free(lsa);
						goto resolve_lsa;
					} /* else: lsa stays the same: we use proxy */
				}
				goto establish_session;
			}
		}
//		if (status >= 300)
//			bb_error_msg_and_die("bad redirection (no Location: header from server)");

		/* For HTTP, data is pumped over the same connection */
		dfp = sfp;

	} else {
コード例 #5
0
ファイル: sustrip.c プロジェクト: JOravetz/SeisUnix
main(int argc, char **argv)
{
	string head;	/* name of file holding headers		*/
	FILE *headfp;	/* ... its file pointer			*/
	string outpar;	/* name of file holding output parfile	*/
	FILE *outparfp;	/* ... its file pointer			*/
	int ns;		/* number of data samples on the segys	*/
	int nsbytes;	/* ... in bytes				*/
	int ftn;	/* fortran flag				*/
	int ntr = 0;	/* number of traces written		*/
	FILE *infp=stdin, *outfp=stdout;


	/* Initialize */
	initargs(argc, argv);
	askdoc(1);


	switch(filestat(STDOUT)) {
	case BADFILETYPE:
		warn("stdout is illegal filetype");
		selfdoc();
	break;
	case TTY:
		warn("stdout can't be tty");
		selfdoc();
	break;
	}

	/* Get parameters */
	if (!getparstring("head"  , &head))	head   = "/dev/null";
	if (!getparstring("outpar", &outpar))	outpar = "/dev/tty" ;
	if (!getparint   ("ftn"   , &ftn))	ftn = 0;
	if (ftn != 0 && ftn != 1)  err("ftn=%d must be 0 or 1", ftn);


	/* Open files to save headers and parameters */
	headfp = efopen(head, "w");
	if( (outparfp = fopen(outpar,"w"))==NULL ) outparfp = stderr;

	/*
	outparfp = efopen(outpar, "w");
	*/

	fseek2g(infp,0,1);
        fseek2g(outfp,0,1);

	/* read id header and save in head */
	gethdr(&ch,&bh);
	fputhdr(headfp,&ch,&bh);

	/* Get info from first trace */
	if (!gettr(&tr)) err("can't get first trace");
	ns = tr.ns;
	nsbytes = ns * FSIZE;


	/* Write the data portion of the records--if the ftn	*/
	/* option is selected, write an int before and after	*/
	/* each trace giving the length of the trace in bytes	*/
	/* as per the Fortran unformatted record format.	*/
	do {

		if (ftn) efwrite(&nsbytes, ISIZE, 1, stdout);
		efwrite(tr.data, FSIZE, ns, stdout);
		if (ftn) efwrite(&nsbytes, ISIZE, 1, stdout);

		efwrite(&tr, 1, HDRBYTES, headfp);

		++ntr;

	} while (gettr(&tr));

	/* Make par file for headerless file */
	fprintf(outparfp, "n1=%d n2=%d d1=%f\n", tr.ns, ntr, 
		(float)tr.dt/1000000.0);


	return EXIT_SUCCESS;
}
コード例 #6
0
ファイル: s_input.c プロジェクト: yeonsh/Amoeba
input ()
{
    int     infile;
    int     n;
    long    dist;
    int     nfd;
    int     stat, slen;
    char    otherbuf[S_BSIZE];
    char    tempbuf[24];
    char    *fromptr, *toptr, *ccptr, *subjptr, *bccptr, *otherptr;
    sigtype     (*old1) (),
	    (*old2) (),
	    (*old3) ();
    register int    i;

    printf ("SND  (%s)\n", verdate);

	bccflag = 0;
	dropen(DRBEGIN);

/*	Set up headers to be written into the draft file	*/
	fromptr = from;
	toptr = to;
	ccptr = cc;
	subjptr = subject;
	bccptr = bcc;
	otherptr = otherbuf;

	strcpy(from, signature);
	strcpy(otherptr, fromname);
	strcat(otherptr, fromptr);
	strcpy(fromptr, otherptr);

	strcpy(otherptr, toname);
	strcat(otherptr, toptr);
	strcpy(toptr, otherptr);

	strcpy(otherptr, ccname);
	strcat(otherptr, ccptr);
	strcpy(ccptr, otherptr);

	slen = strlen( subjname ); 
	strcpy(otherptr, subjname);
	strcat(otherptr, subjptr);
	strcpy(subjptr, otherptr);
	
/*	Write the header info to the draft file		*/

	if(write(drffd, fromptr, strlen(fromptr)) < 0)
	{
		printf("Cannot write draft %s\n", drffile);
		s_exit(-1);
	}
	write(drffd, "\n", 1);
	write(drffd, toptr, strlen(toptr));
	write(drffd, "\n", 1);
	write(drffd, ccptr, strlen(ccptr));
	write(drffd, "\n", 1);

/*	If there are blind carbon copies write the necessary header b.s. */
	if(bcc[0] != '\0')
	{
		strcpy(otherptr, bccname);
		strcat(otherptr, bccptr);
		strcpy(bccptr, otherptr);
		write(drffd, bccptr, strlen(subjptr));
		write(drffd, "\n", 1);


		bccflag = 1;
	}
	if( strlen( subject ) > slen )
	{
		char newsubj[S_BSIZE], *p, *pnt;
		char *index();
		int plc;

		newsubj[0] = '\0';
		pnt = subjptr;
		while( (p = index(pnt,'\n')) != 0 )
		{
			*p++ = '\0';
			plc = strlen(newsubj);
			sprintf( &newsubj[plc],"%s\n%s",pnt," ");
			pnt = p;
		}
		strcat( newsubj, pnt );
		strcpy( subjptr, newsubj );
	}
	write(drffd, subjptr, strlen(subjptr));
	write(drffd, "\n\n", 2);

/*	If there is a forwarded message		*/
	if (inclfile[0] != '\0')
	{                             /* tack file to end of message        */
		body = TRUE;
		strcpy (bigbuf, inclfile);
		infile = open (bigbuf, 0);
		if (inclfile[0] != '\0')
			inclfile[0] = '\0';
		if (infile < 0)
			printf ("can't open: '%s'\n", bigbuf);
		dropen (DREND);
		body = TRUE;
		while ((i = read (infile, bigbuf, BBSIZE - 1)) > 0)
			write (drffd, bigbuf, i);
		(void) close (infile);
	}

edit:

	fflush (stdout);

        drclose ();

        old1 =  signal (SIGHUP, SIG_IGN); /* ignore signals intended for edit */
        old2 =  signal (SIGINT, SIG_IGN);
        old3 =  signal (SIGQUIT, SIG_IGN);

/*	Crank up the editor now that the draft file is set-up	*/
        if (fork () == 0)
        {
	    signal (SIGHUP, old1);
	    signal (SIGINT, orig);
	    signal (SIGQUIT, old3);

            execlp (editor, editor, drffile, (char *)0);

	    fprintf (stderr,"can't execute\n");
	    s_exit (-1);
        }
        wait (&stat);
        body = TRUE;	/* Don't know but assume he created a draft */
        lastsend = 0;
        signal (SIGHUP, old1);     /* restore signals */
        signal (SIGINT, old2);
        signal (SIGQUIT, old3);

        fflush (stdout);
        signal (SIGINT, SIG_IGN);
        signal (SIGQUIT, SIG_IGN);

	dropen(DRBEGIN);
	
/*	Rip the header information from the draft file and
**	take care of any aliases
**	Algorithm:
**	Read each header line (function grabaddr), keeping track of the 
**	number of characters read.  Handle the aliases (function doalias).
**	Open a new file descriptor which points to the beginning of the
**	draft file.  Read the draft file from the point where the header
**	information leaves off while writing to the draft from the beginning.
**	This effectively reads the header info, then shifts the body of the
**	message up to the top of the draft, overwriting the header.
*/

	dist = gethdr( fromptr, toptr, ccptr, bccptr, subjptr );

	doalias( toptr );
	doalias( ccptr );
	doalias( bccptr );

	if(chmod(drffile, 0600) < 0)
	{
		fprintf(stderr,"Unable to make draft writable %s.\n", drffile);
		s_exit(-1);
	}
	if((nfd = open(drffile, 2, 600)) < 0)
	{
		fprintf(stderr,"Could not open draft %s\n", drffile);
		s_exit(-1);
	}
	if(lseek(nfd, 0L, 0) < 0)
	{
		fprintf(stderr,"Lseek failed on draft %s\n", drffile);
		s_exit(-1);
	}
	if(lseek(drffd, dist-1, 0) < 0)
	{
		fprintf(stderr,"Lseek failed on draft %s\n", drffile);
		s_exit(-1);
	}

	dist = 0L;
	while((i = read(drffd, bigbuf, BBSIZE -1)) > 0)
		dist += write(nfd, bigbuf, i);

	if(truncate(drffile, dist) < 0)
	{
		fprintf(stderr,"Truncate failed on draft %s\n", drffile);
		s_exit(-1);
	}

	if(chmod(drffile, 0400) < 0)
		fprintf(stderr,"Unable to make draft %s writable.\n",drffile);
	
	(void) close( nfd );

    setjmp (savej);
    nsent = 0;
/*
**	MAIN COMMAND INTERPRETER LOOP
*/
    for (;;)
    {
    	char *cp;

	signal (SIGINT, onint3);
	printf ("Command or ?: ");
	fflush (stdout);
	aborted = FALSE;
	if (fgets (bigbuf, BBSIZE, stdin) == NULL)
	    goto byebye;
    	if (cp = index(bigbuf, '\n'))
    	    *cp = '\0';

/*	"Set" option	*/
	if( strncmp( "set", bigbuf, 3) == 0){
		char *av[NARGS];

		i = sstr2arg(bigbuf, 20, av, " \t");
		if( i == 1 ) {	/* tell him what the current options are */
			printf(" Copyfile  - '%s'\n", copyfile);
			printf(" Signature - '%s'\n", signature);
			printf(" Aliases   - '%s'\n", aliasfilename);
			printf(" Editor    - '%s'\n", editor);
			printf(" Checker   - '%s'\n", checker);
			printf(" Subargs   - '%s'\n", subargs);

			if(qflag == 0 && cflag == 1)
				printf(" File copy option is on\n");
			if(qflag == 1 && cflag == 0)
				printf(" File copy on confirmation only\n");
			continue;
		}
		if( (i = picko( av[1] ) ) < 0) {
			fprintf(stderr,"Option '%s' is invalid.\n", av[1]);
			continue;
		}
		select_o( i, &av[1] );
		continue;
	}
	compress (bigbuf, bigbuf);
				  /* so prefix works on multi-words     */
	if (bigbuf[0] == '\0')
	    continue;             /* just hit newline                   */

	signal (SIGINT, onint);

	for (i = 0; !isnull (bigbuf[i]); i++)
	    bigbuf[i] = uptolow (bigbuf[i]);

	if (prefix ("bcc", bigbuf))
	{
	    getaddr (bccname, bcc, YES, locname);
	    bccflag = 1;	
	    continue;
	}

/*	"Edit" option (grandfathered to also accept "v" for visual edit) */

	if (prefix ("edit body", bigbuf) || prefix("visual edit body", bigbuf))
	{
		dropen( DRBEGIN );
    		if((tmpfd = open(tmpdrffile, 2, 0600)) < 0)
    		{
    			fprintf(stderr,"Cannot open temporary draft file %s\n", tmpdrffile);
    			s_exit(-1);
    		}

    		if(lseek(tmpfd, 0L, 0) < 0)
    		{
    			fprintf(stderr,"Lseek failed on temporary draft file %s\n", tmpdrffile);
    			s_exit(-1);
    		}

    		if(chmod(drffile, 0600) < 0)
    			fprintf(stderr,"Could not make draft %s writable\n", drffile);

		/* 	Write the header info to the temporary draft	*/
		dist = 0L;
		dist += write(tmpfd, fromname, strlen( fromname ));
    		dist += write(tmpfd, from, strlen( from ));
    		dist += write(tmpfd, "\n", 1);
    		dist += write(tmpfd, toname, strlen( toname ));
    		dist += write(tmpfd, to, strlen( to ));
    		dist += write(tmpfd, "\n", 1);
    		dist += write(tmpfd, ccname, strlen( ccname ));
    		dist += write(tmpfd, cc, strlen( cc ));
    		dist += write(tmpfd, "\n", 1);
    		if(bccflag)
    		{
    			dist += write(tmpfd, bccname, strlen( bccname ));
    			dist += write(tmpfd, bcc, strlen( bcc ));
    			dist += write(tmpfd, "\n", 1);
    		}
    		dist += write(tmpfd, subjname, strlen( subjname ));
    		dist += write(tmpfd, subject, strlen( subject ));
    		dist += write(tmpfd, "\n", 1);

		if(lseek(drffd, 0L, 0) < 0)
		{
		 	fprintf(stderr,"Lseek failed on draft %s\n", drffile);
		 	s_exit(-1);
		}
    		if(lseek(tmpfd, 0L, 2) < 0)
    		{
    			fprintf(stderr,"Lseek failed on temporary draft\n");
    			s_exit(-1);
    		}

		/*	Write the body into the temp. draft	*/
    		while((i = read(drffd, bigbuf, BBSIZE-1)) > 0)
    			dist += write(tmpfd, bigbuf, i);

    		if(truncate( tmpdrffile, dist) < 0)
    		{
    			fprintf(stderr,"Could not truncate temporary draft\n");
    			s_exit(-1);
    		}

    		if(lseek(tmpfd, 0L, 0) < 0)
    			fprintf(stderr,"Lseek failed on temporary draft\n");
    		if(lseek(drffd, 0L, 0) < 0)
    			fprintf(stderr,"Lseek failed on draft %s\n", drffile);
    		
    		dist = 0L;
		/*	Copy temp. draft which contains headers and
		**	body back into draft file
		*/
    		while((i = read(tmpfd, bigbuf, BBSIZE-1)) > 0)
    			dist += write(drffd, bigbuf, i);

    		if(truncate( drffile, dist ) < 0)
    			fprintf(stderr,"Could not truncate draft %s\n", drffile);
    		if(truncate( tmpdrffile, 0 ) < 0)
    			fprintf(stderr,"Could not truncate temporary draft\n");
    		if(close( tmpfd ) < 0)
    			fprintf(stderr,"Could not close temporary draft\n");
    		if(lseek(drffd, 0L, 0) < 0)
    			fprintf(stderr,"Lseek failed on draft %s\n", drffile);
    		if(chmod(drffile, 0400) < 0)
    			fprintf(stderr,"Could not protect draft %s\n", drffile);
		/*	Fire-up the editor	*/
		goto edit;
	}
/*	"File include" option	*/
	if (prefix ("file include", bigbuf))
	{
	    printf ("File: ");
	    gather (bigbuf, BBSIZE - 1);
	    if (bigbuf[0] == '\0')
		continue;

	    infile = open (bigbuf, 0);
	    if (inclfile[0] != '\0')
	    {                     /* and include file                   */
		inclfile[0] = '\0';
	    }
	    if (infile < 0)
	    {
		fprintf(stderr,"can't open: '%s'\n", bigbuf);
		continue;
	    }
	    dropen (DREND);
	    body = TRUE;
	    while ((i = read (infile, bigbuf, BBSIZE - 1)) > 0)
		write (drffd, bigbuf, i);
	    (void) close (infile);
	    printf (" ...included\n");
	    continue;
	}
/*	"Program run" option	*/
	if (prefix ("program run", bigbuf))
	{
	    printf ("Program: ");
	    fflush (stdout);
	    if (gets (tempbuf) == NULL)
		continue;
	    drclose ();

	    /* ignore signals intended for subprocess */
	    old1 = signal (SIGHUP, SIG_IGN);
	    old2 = signal (SIGINT, SIG_IGN);
	    old3 = signal (SIGQUIT, SIG_IGN);

	    if (fork () == 0)
	    {
		signal (SIGHUP, old1);
		signal (SIGINT, orig);
		signal (SIGQUIT, old3);
		execlp ("sh", "send-shell", "-c", tempbuf, (char *)0);
		fprintf(stderr,"can't execute\n");
		s_exit (-1);
	    }
	    wait (&stat);
	    signal (SIGHUP, old1);     /* restore signals */
	    signal (SIGINT, old2);
	    signal (SIGQUIT, old3);
	    dropen (DREND);
	    continue;
	}
/*	"quit" option	*/
	if (prefix ("quit", bigbuf) ||
		prefix ("bye", bigbuf))
	{
    byebye: 
	    if ( body && !nsent)
	    {
		printf ("Without sending draft");
		if (confirm ())
		    return;
		else
		    continue;
	    }
	    drclose ();
	    return;
	}
/*	"review message" option	*/
	if (prefix ("review message", bigbuf))
	{
		dropen( DRBEGIN );
		/*	Put header info into temp. draft	*/
		if((nfd = open(tmpdrffile, 2, 0600)) < 0)
		{
			fprintf(stderr,"Can't open temporary file\n");
			s_exit(-1);
		}
		if(lseek(nfd, 0L, 0) < 0)
		{
			fprintf(stderr,"Lseek failed on temporary file\n");
			s_exit(-1);
		}
		if(write(nfd, fromname, strlen( fromname )) < 0)
		{
			fprintf(stderr,"Cannot write temporary file\n");
			s_exit(-1);
		}
		write(nfd, from, strlen( from ));
		write(nfd, "\n", 1);
		if(to[0] != '\0')
		{
			write(nfd, toname, strlen( toname ));
			write(nfd, to, strlen( to ));
			write(nfd, "\n", 1);
		}
		else if(bccflag)
		{
			write(nfd, toname, strlen( toname ));
			write(nfd, "list: ;", 7);
			write(nfd, "\n", 1);
		}
		if(cc[0] != '\0')
		{
			write(nfd, ccname, strlen( ccname ));
			write(nfd, cc, strlen( cc ));
			write(nfd, "\n", 1);
		}
		if(bccflag)
		{
			write(nfd, bccname, strlen( bccname ));
			write(nfd, bcc, strlen( bcc ));
			write(nfd, "\n", 1);
		}			
		if(subject[0] != '\0')
		{
			write(nfd, subjname, strlen( subjname ));
			write(nfd, subject, strlen( subject ));
			write(nfd, "\n", 1);
		}

		if(lseek(drffd, 0L, 0) < 0)
			fprintf(stderr,"Lseek failed on draft %s\n", drffile);
	/*	Write the body into the temp. file	*/
		while((i = read(drffd, bigbuf, BBSIZE - 1)) > 0)
			write(nfd, bigbuf, i);
		drclose();
	   if(pflag)
	   {
		(void) close( nfd );
			
		    /* ignore signals intended for subprocess */
		    old1 = signal (SIGHUP, SIG_IGN);
		    old2 = signal (SIGINT, SIG_IGN);
		    old3 = signal (SIGQUIT, SIG_IGN);
		/*	Start-up "more" program on the temp. draft	*/
		    if (fork () == 0)
		    {
			signal (SIGHUP, old1);
			signal (SIGINT, orig);
			signal (SIGQUIT, old3);
			execlp ("more", "-c", tmpdrffile, 0);
			fprintf(stderr,"can't execute\n");
			s_exit (-1);
		    }
		    wait (&stat);
		    signal (SIGHUP, old1);     /* restore signals */
		    signal (SIGINT, old2);
		    signal (SIGQUIT, old3);

	   }
	   else	/*	If the paging option is off, just show it */
	   {
		if( lseek(nfd, 0L, 0) < 0 )
			fprintf(stderr, "Lseek failed on temporary draft.\n");

		while((i = read(nfd, bigbuf, BBSIZE - 1)) > 0)
			write( 1, bigbuf, i);

		(void) close( nfd );
	   }
	   if(truncate(tmpdrffile, 0) < 0)
		fprintf(stderr,"truncate failed on temp. draft\n");

	   fflush( stdout );
	   continue;
	}
/*	"Check spelling" option	*/
	if (prefix ("check spelling", bigbuf))
	{
	    drclose ();

	    old1 =  signal (SIGHUP, SIG_IGN); /* ignore signals intended for cheker */
	    old2 =  signal (SIGINT, SIG_IGN);
	    old3 =  signal (SIGQUIT, SIG_IGN);

	    if (fork () == 0)
	    {
		signal (SIGHUP, old1);
		signal (SIGINT, orig);
		signal (SIGQUIT, old3);
		execlp (checker, checker, drffile, (char *)0);
		fprintf(stderr,"can't execute\n");
		s_exit (-1);
	    }
	    wait (&stat);
	    signal (SIGHUP, old1);     /* restore signals */
	    signal (SIGINT, old2);
	    signal (SIGQUIT, old3);
	    dropen (DREND);
	    continue;
	}
/*	"Post message" option	*/
	if (prefix ("post message", bigbuf) ||
		prefix ("send message", bigbuf))
	{
	    if (lastsend && lastsend == body)
	    {
		printf ("Without changing anything");
		if (!confirm ())
		    break;
	    }
	    signal (SIGINT, onint2);
	    if( qflag == 1 ){
		printf(" Do you want a file copy of this message ?  ");
		fflush(stdout);
		fgets(tempbuf, sizeof(tempbuf), stdin );
		if( tempbuf[0] == 'y' || tempbuf[0] == 'Y' || tempbuf[0] == '\n')
			cflag = 1;
	    	else
	    		cflag = 0;
	    }
	    post ();
	    if ( qflag == 1 )
		cflag = 0;

/* *** auto-exit, upon successfull send, since draft is saved *** */

	    goto byebye;
	}
/*	help	*/
	if (prefix ("?", bigbuf))
	{
	    printf ("bcc\n");
	    printf ("bye\n");
	    printf ("check spelling\n");
	    printf ("edit body\n");
	    printf ("file include\n");
	    printf ("program run\n");
	    printf ("quit\n");
	    printf ("review message\n");
	    printf ("send message\n");
	    printf ("set [option] [option value]\n");
	    continue;
	}

	printf (" unknown command (type ? for help)\n");
    }				  /* end of loop */
}
コード例 #7
0
/*
 * Read the input files; write the output file; display information.
 */
static void
btxld(const char *iname)
{
    char name[FILENAME_MAX];
    struct btx_hdr btx, btxle;
    struct hdr ihdr, ohdr;
    unsigned int ldr_size, cwr;
    int fdi[3], fdo, i;

    ldr_size = 0;

    for (i = I_LDR; i <= I_CLNT; i++) {
	fname = i == I_LDR ? lname : i == I_BTX ? bname : iname;
	if ((fdi[i] = open(fname, O_RDONLY)) == -1)
	    err(2, "%s", fname);
	switch (i) {
	case I_LDR:
	    gethdr(fdi[i], &ihdr);
	    if (ihdr.fmt != F_BIN)
		Warn(fname, "Loader format is %s; processing as %s",
		     fmtlist[ihdr.fmt], fmtlist[F_BIN]);
	    ldr_size = ihdr.size;
	    break;
	case I_BTX:
	    getbtx(fdi[i], &btx);
	    break;
	case I_CLNT:
	    gethdr(fdi[i], &ihdr);
	    if (ihdr.org && ihdr.org != BTX_PGSIZE)
		Warn(fname,
		     "Client origin is 0x%x; expecting 0 or 0x%x",
		     ihdr.org, BTX_PGSIZE);
	}
    }
    memset(&ohdr, 0, sizeof(ohdr));
    ohdr.fmt = format;
    ohdr.text = ldr_size;
    ohdr.data = btx.btx_textsz + ihdr.size;
    ohdr.org = lentry;
    ohdr.entry = lentry;
    cwr = 0;
    if (wpage > 0 || (wpage == -1 && !(ihdr.flags & IMPURE))) {
	if (wpage > 0)
	    cwr = wpage;
	else {
	    cwr = howmany(ihdr.text, BTX_PGSIZE);
	    if (cwr > BTX_MAXCWR)
		cwr = BTX_MAXCWR;
	}
    }
    if (ppage > 0 || (ppage && wpage && ihdr.org >= BTX_PGSIZE)) {
	btx.btx_flags |= BTX_MAPONE;
	if (!cwr)
	    cwr++;
    }
    btx.btx_pgctl -= cwr;
    btx.btx_entry = Eflag ? centry : ihdr.entry;
    if ((size_t)snprintf(name, sizeof(name), "%s.tmp", oname) >= sizeof(name))
	errx(2, "%s: Filename too long", oname);
    if ((fdo = open(name, O_CREAT | O_TRUNC | O_WRONLY, 0666)) == -1)
	err(2, "%s", name);
    if (!(tname = strdup(name)))
	err(2, NULL);
    puthdr(fdo, &ohdr);
    for (i = I_LDR; i <= I_CLNT; i++) {
	fname = i == I_LDR ? lname : i == I_BTX ? bname : iname;
	switch (i) {
	case I_LDR:
	    copy(fdi[i], fdo, ldr_size, 0);
	    seekx(fdo, ohdr.size += ohdr.text);
	    break;
	case I_BTX:
	    btxle = btx;
	    btxle.btx_pgctl = htole16(btxle.btx_pgctl);
	    btxle.btx_textsz = htole16(btxle.btx_textsz);
	    btxle.btx_entry = htole32(btxle.btx_entry);
	    writex(fdo, &btxle, sizeof(btxle));
	    copy(fdi[i], fdo, btx.btx_textsz - sizeof(btx),
		 sizeof(btx));
	    break;
	case I_CLNT:
	    copy(fdi[i], fdo, ihdr.size, 0);
	    if (ftruncate(fdo, ohdr.size += ohdr.data))
		err(2, "%s", tname);
	}
	if (close(fdi[i]))
	    err(2, "%s", fname);
    }
    if (close(fdo))
	err(2, "%s", tname);
    if (rename(tname, oname))
	err(2, "%s: Can't rename to %s", tname, oname);
    tname = NULL;
    if (verbose) {
	printf(binfo, btx.btx_majver, btx.btx_minver, btx.btx_textsz,
	       BTX_ORIGIN(btx), BTX_ENTRY(btx), BTX_MAPPED(btx) *
	       BTX_PGSIZE / 0x100000, !!(btx.btx_flags & BTX_MAPONE),
	       BTX_MAPPED(btx) - btx.btx_pgctl - BTX_PGBASE /
	       BTX_PGSIZE - BTX_MAPPED(btx) * 4 / BTX_PGSIZE);
	printf(cinfo, fmtlist[ihdr.fmt], ihdr.size, ihdr.text,
	       ihdr.data, ihdr.bss, ihdr.entry);
	printf(oinfo, fmtlist[ohdr.fmt], ohdr.size, ohdr.text,
	       ohdr.data, ohdr.org, ohdr.entry);
    }
}
コード例 #8
0
ファイル: wget.c プロジェクト: sutajiokousagi/netv-recovery
FILE *start_wget(char *url, int *total)
{
	char buf[512];
	struct host_info server, target;
	len_and_sockaddr *lsa;
	int redir_limit;
#if ENABLE_FEATURE_WGET_LONG_OPTIONS
	char *post_data;
	char *extra_headers = NULL;
	llist_t *headers_llist = NULL;
#endif
	FILE *sfp;                      /* socket to web/ftp server         */
	int use_proxy = 0;              /* Use proxies if env vars are set  */
	const char *user_agent = "Wget";/* "User-Agent" header field        */
	struct globals state;
	char *str;
	int status;
    bzero(&state, sizeof(state));

	static const char keywords[] =
		"content-length\0""transfer-encoding\0""chunked\0""location\0";
	enum {
		KEY_content_length = 1, KEY_transfer_encoding, KEY_chunked, KEY_location
	};

	target.user = NULL;
	parse_url(url, &target);

	state.timeout_seconds = 900;
	server.port = target.port;
	server.host = target.host;

#if 0
	if (opt & WGET_OPT_CONTINUE) {
		output_fd = open(fname_out, O_WRONLY);
		if (output_fd >= 0) {
			state.beg_range = xlseek(output_fd, 0, SEEK_END);
		}
		/* File doesn't exist. We do not create file here yet.
		 * We are not sure it exists on remove side */
	}
#endif

	redir_limit = 5;
 resolve_lsa:
	lsa = xhost2sockaddr(server.host, server.port);
 establish_session:
	/*
	 *  HTTP session
	 */

	/* Open socket to http server */
	sfp = open_socket(lsa);
	if (!sfp) {
		ERROR("Couldn't connect to %s:%d", server.host, server.port);
		return NULL;
	}

	/* Send HTTP request */
	fprintf(sfp, "GET /%s HTTP/1.1\r\n", target.path);

	fprintf(sfp, "Host: %s\r\nUser-Agent: %s\r\n",
		target.host, user_agent);

	/* Ask server to close the connection as soon as we are done
	 * (IOW: we do not intend to send more requests)
	 */
	fprintf(sfp, "Connection: close\r\n");

	if (state.beg_range)
		fprintf(sfp, "Range: bytes=%lu-\r\n", state.beg_range);

	fprintf(sfp, "\r\n");
	fflush(sfp);


	/*
	 * Retrieve HTTP response line and check for "200" status code.
	 */
 read_response:
	if (fgets(buf, sizeof(buf), sfp) == NULL)
		ERROR("no response from server");

	str = buf;
	str = skip_non_whitespace(str);
	str = skip_whitespace(str);
	// FIXME: no error check
	// xatou wouldn't work: "200 OK"
	status = atoi(str);
	switch (status) {
	case 0:
	case 100:
		while (gethdr(buf, sizeof(buf), sfp /*, &n*/) != NULL)
			/* eat all remaining headers */;
		goto read_response;
	case 200:
/*
Response 204 doesn't say "null file", it says "metadata
has changed but data didn't":

"10.2.5 204 No Content
The server has fulfilled the request but does not need to return
an entity-body, and might want to return updated metainformation.
The response MAY include new or updated metainformation in the form
of entity-headers, which if present SHOULD be associated with
the requested variant.

If the client is a user agent, it SHOULD NOT change its document
view from that which caused the request to be sent. This response
is primarily intended to allow input for actions to take place
without causing a change to the user agent's active document view,
although any new or updated metainformation SHOULD be applied
to the document currently in the user agent's active view.

The 204 response MUST NOT include a message-body, and thus
is always terminated by the first empty line after the header fields."

However, in real world it was observed that some web servers
(e.g. Boa/0.94.14rc21) simply use code 204 when file size is zero.
*/
	case 204:
		break;
	case 300:  /* redirection */
	case 301:
	case 302:
	case 303:
		break;
	case 206:
		if (state.beg_range)
			break;
		/* fall through */
	default:
		ERROR("server returned error: %s", sanitize_string(buf));
	}

	/*
	 * Retrieve HTTP headers.
	 */
	while ((str = gethdr(buf, sizeof(buf), sfp /*, &n*/)) != NULL) {
		/* gethdr converted "FOO:" string to lowercase */
		smalluint key;
		/* strip trailing whitespace */
		char *s = strchrnul(str, '\0') - 1;
		while (s >= str && (*s == ' ' || *s == '\t')) {
			*s = '\0';
			s--;
		}
		key = index_in_strings(keywords, buf) + 1;
		if (key == KEY_content_length) {
			state.content_len = strtoul(str, NULL, 10);
			state.total_len   = strtoul(str, NULL, 10);
			if (state.content_len < 0 || errno) {
				ERROR("content-length %s is garbage", sanitize_string(str));
			}
			state.got_clen = 1;
			continue;
		}
		if (key == KEY_transfer_encoding) {
			if (index_in_strings(keywords, str_tolower(str)) + 1 != KEY_chunked)
				ERROR("transfer encoding '%s' is not supported", sanitize_string(str));
			state.chunked = state.got_clen = 1;
		}
		if (key == KEY_location && status >= 300) {
			if (--redir_limit == 0)
				ERROR("too many redirections");
			fclose(sfp);
			state.got_clen = 0;
			state.chunked = 0;
			if (str[0] == '/')
				/* free(target.allocated); */
				target.path = /* target.allocated = */ strdup(str+1);
				/* lsa stays the same: it's on the same server */
			else {
				parse_url(str, &target);
				if (!use_proxy) {
					server.host = target.host;
					server.port = target.port;
					free(lsa);
					goto resolve_lsa;
				} /* else: lsa stays the same: we use proxy */
			}
			goto establish_session;
		}
	}
//		if (status >= 300)
//			ERROR("bad redirection (no Location: header from server)");


	if (total)
		*total = state.content_len;
	ndelay_off(fileno(sfp));
	clearerr(sfp);
	return sfp;
#if 0
	if (retrieve_file_data(&state, sfp, progress, handle, data))
		return -1;
	handle(data, NULL, 0);

	return EXIT_SUCCESS;
#endif
}
コード例 #9
0
ファイル: audio.c プロジェクト: BitchX/BitchX-SVN
/* 
 * TODO: add some kind of error reporting here
 */
void play(char *inFileStr)
{
char *f;
long totalframes = 0;
long tseconds = 0;
struct AUDIO_HEADER header;
int bitrate, fs, g, cnt = 0;

	while ((f = new_next_arg(inFileStr, &inFileStr)))
	{
		if (!f || !*f)
			return;	
		if ((in_file=fopen(f,"r"))==NULL) 
		{
			if (!do_hook(MODULE_LIST, "AMP ERROR open %s", f))
				put_it("Could not open file: %s\n", f);
			continue;
		}



		filesize = file_size(f);
		initialise_globals();

		if ((g=gethdr(&header))!=0) 
		{
			report_header_error(g);
			continue;
		}

		if (header.protection_bit==0) 
			getcrc();

		if (setup_audio(&header)!=0) 
		{
			yell("Cannot set up audio. Exiting");
			continue;
		}
	
		filesize -= sizeof(header);

		switch (header.layer)
		{
			case 1:
			{
				if (layer3_frame(&header,cnt)) 
				{
					yell(" error. blip.");
					continue;
				}
				break;
			} 
			case 2:
			{
				if (layer2_frame(&header,cnt)) 
				{
					yell(" error. blip.");
					continue;
				}
				break;
			}
			default:
				continue;
		}

		bitrate=t_bitrate[header.ID][3-header.layer][header.bitrate_index];
	       	fs=t_sampling_frequency[header.ID][header.sampling_frequency];

	        if (header.ID) 
        		framesize=144000*bitrate/fs;
	       	else 
       			framesize=72000*bitrate/fs;



		totalframes = (filesize / (framesize + 1)) - 1;
		tseconds = (totalframes * 1152/
		    t_sampling_frequency[header.ID][header.sampling_frequency]);
                
		if (A_AUDIO_PLAY)
		{
			char *p = strrchr(f, '/');
			if (!p) p = f; else p++;
			if (!do_hook(MODULE_LIST, "AMP PLAY %lu %lu %s", tseconds, filesize, p))
				bitchsay("Playing: %s\n", p);
		}

		/*
		 * 
		 */
		if (!(fseek(in_file, 0, SEEK_END)))
		{
			char id3_tag[256];
			if (!fseek(in_file, -128, SEEK_END) && (fread(id3_tag,128, 1, in_file) == 1))
			{
				if (!strncmp(id3_tag, "TAG", 3))
					print_id3_tag(in_file, id3_tag);
			}
			fseek(in_file,0,SEEK_SET);
		}
		decodeMPEG(&header);
		do_hook(MODULE_LIST, "AMP CLOSE %s", f);
		close_audio();
		fclose(in_file);
	}
}
コード例 #10
0
ファイル: guicontrol.c プロジェクト: berkus/nemesis
int decodeMPEG_2(int inFilefd)
{
  struct AUDIO_HEADER header;
  int cnt,g,err=0;
  TControlMsg message;


  if ((in_file=fdopen(inFilefd,"r"))==NULL) {
    return(1);
  }

  append=data=nch=0; /* initialize globals */

  GUI_STOPPED = FALSE;
  GUI_PLAYING = TRUE;
  GUI_FD_TO_PLAY = -1;
  
  for (cnt=0;;cnt++) {
    if ((g=gethdr(&header))!=0) {
      switch (g) {
      case GETHDR_ERR: die("error reading mpeg bitstream. exiting.\n");
	break;
      case GETHDR_NS : warn("this is a file in MPEG 2.5 format, which is not defined\n");
	warn("by ISO/MPEG. It is \"a special Fraunhofer format\".\n");
	warn("amp does not support this format. sorry.\n");
	break;
      case GETHDR_FL1: warn("ISO/MPEG layer 1 is not supported by amp (yet).\n");
	break;
      case GETHDR_FF : warn("free format bitstreams are not supported. sorry.\n");
	break;	
      case GETHDR_SYN: warn("oops, we're out of sync.\n");
	break;
      default: 
      }
      break;
    }
    
    if (!(cnt%10)){
    GUIstatusDisplay(cnt);
    }

    if(get_msg(&message) >= 0)
      {
	int pflag = 0;
	cnt = parse_msg(&message,&header,cnt);
        if (GUI_PAUSE) {
                int flags;
                pflag = 1;
#if 0
                /* Set stdin to blocking */
                if((flags = fcntl(STDIN_FILENO, F_GETFL, 0)) < 0)
                        perror("fcntl");
                flags ^= O_NONBLOCK;
                if(fcntl(STDIN_FILENO, F_SETFL, flags) < 0)
                        perror("fcntl");
#endif
        }
	while(GUI_PAUSE){
	  if(get_msg(&message) >= 0)
	    cnt = parse_msg(&message,&header,cnt);
	}
        if (pflag) {
                int flags;
                /* Set stdin to non-blocking */
#if 0
                if((flags = fcntl(STDIN_FILENO, F_GETFL, 0)) < 0)
                        perror("fcntl");
                flags |= O_NONBLOCK;
                if(fcntl(STDIN_FILENO, F_SETFL, flags) < 0)
                        perror("fcntl");
#endif
        }
	if (GUI_STOP || (GUI_FD_TO_PLAY != -1)){
	  break;
	}
      }

    /* crc is read just to get out of the way.
     */
    if (header.protection_bit==0) getcrc();
    
    if (!cnt && A_AUDIO_PLAY) { /* setup the audio when we have the frame info */

      if (AUDIO_BUFFER_SIZE==0)
	audioOpen(t_sampling_frequency[header.ID][header.sampling_frequency],
		  (header.mode!=3),
		  A_SET_VOLUME);
      else
	audioBufferOpen(t_sampling_frequency[header.ID][header.sampling_frequency],(header.mode!=3),A_SET_VOLUME);
    }
    
    if (layer3_frame(&header,cnt)) {
      warn(" error. blip.\n");
      err=1;
      break;
    } 
    
  }
  fclose(in_file);
  if (A_AUDIO_PLAY)
    if (AUDIO_BUFFER_SIZE!=0)
      audioBufferClose();
    else
      audioClose();
  else
    fclose(out_file);
  if (!(GUI_STOP) && (GUI_FD_TO_PLAY == -1)) {
    /* We've reached the end of the track, notify the jukebox...
     */
    TControlMsg rmsg;
    
    rmsg.type = MSG_NEXT;
    rmsg.data = 0;    
    send_msg(&rmsg, TRUE);
  }

  GUI_STOPPED = TRUE;
  GUI_PLAYING = FALSE;
  return(err);
}