Exemplo n.º 1
0
s32 USBStorage_MountLUN(struct ehci_hcd * ehci, usbstorage_handle *dev, u8 lun) {
	s32 retval;
	int f = handshake_mode;

	if (lun >= dev->max_lun)
		return -EINVAL;
	usb_timeout = 1000 * 1000;
	handshake_mode = 1;

	retval = __usbstorage_start_stop(dev, lun, 1);

#ifdef MEM_PRINT
	s_printf("    start_stop cmd ret %i\n", retval);
#endif
	if (retval < 0)
		goto ret;

	retval = __usbstorage_clearerrors(ehci, dev, lun);
	if (retval < 0)
		goto ret;
	usb_timeout = 1000 * 1000;
	retval = USBStorage_Inquiry(ehci, dev, lun);
#ifdef MEM_PRINT
	s_printf("    Inquiry ret %i\n", retval);
#endif
	if (retval < 0)
		goto ret;
	retval = USBStorage_ReadCapacity(ehci, dev, lun, &dev->sector_size[lun], &dev->n_sector[lun]);
#ifdef MEM_PRINT
	s_printf("    ReadCapacity ret %i\n", retval);
#endif
ret:
	handshake_mode = f;
	return retval;
}
Exemplo n.º 2
0
static s32 __usbstorage_clearerrors(struct ehci_hcd * ehci, usbstorage_handle *dev, u8 lun) {
	s32 retval;
	u8 cmd[16];
	u8 *sense = USB_Alloc(SCSI_SENSE_REPLY_SIZE);
	u8 status = 0;
	memset(cmd, 0, sizeof (cmd));
	cmd[0] = SCSI_TEST_UNIT_READY;
	int n;

	if (!sense) return -ENOMEM;



	for (n = 0; n < 5; n++) {

		retval = __cycle(ehci, dev, lun, NULL, 0, cmd, 6, 1, &status, NULL);

#ifdef MEM_PRINT
		s_printf("    SCSI_TEST_UNIT_READY %i# ret %i\n", n, retval);
#endif

		if (retval == -ENODEV) goto error;


		if (retval == 0) break;
	}
	if (retval < 0) goto error;


	if (status != 0) {
		cmd[0] = SCSI_REQUEST_SENSE;
		cmd[1] = lun << 5;
		cmd[4] = SCSI_SENSE_REPLY_SIZE;
		cmd[5] = 0;
		memset(sense, 0, SCSI_SENSE_REPLY_SIZE);
		retval = __cycle(ehci, dev, lun, sense, SCSI_SENSE_REPLY_SIZE, cmd, 6, 0, NULL, NULL);

#ifdef MEM_PRINT
		s_printf("    SCSI_REQUEST_SENSE ret %i\n", retval);
#endif

		if (retval < 0) goto error;

		status = sense[2] & 0x0F;

#ifdef MEM_PRINT
		s_printf("    SCSI_REQUEST_SENSE status %x\n", status);
#endif


		if (status == SCSI_SENSE_NOT_READY || status == SCSI_SENSE_MEDIUM_ERROR || status == SCSI_SENSE_HARDWARE_ERROR)
			retval = USBSTORAGE_ESENSE;
	}
error:
	USB_Free(sense);
	return retval;
}
Exemplo n.º 3
0
static void WritePrepTag(HTTP_STREAM *stream, const char *tag, const char *val, const char *prepend)
{
    if (val) {
        s_printf(stream, "<%s>", tag);
        if (prepend && *val == '+') {
            val++;
            s_puts(prepend, stream);
        }
        s_printf(stream, "%s</%s>\r\n", val, tag);
    }
}
Exemplo n.º 4
0
char *dtostrf (double val, signed char width, unsigned char prec, char *sout) {
  char fmt[20];
  
  int whole = val;
  float mantissa = val - whole;

  int32_t frac = mantissa * powf(10, prec);
  if(frac < 0) frac = -frac;

  s_printf(fmt, "%%0%dd.%%0%dd", width, prec);
  s_printf(sout, fmt, whole, frac);
  return sout;
}
Exemplo n.º 5
0
/*!
 * \brief Transmit a redirection page.
 */
int HttpSendRedirection(HTTPD_SESSION *hs, int code, ...)
{
    va_list ap;
    int len;
    char *cp;
    char *loc;

    va_start(ap, code);
    for (len = 0; (cp = va_arg(ap, char *)) != NULL; len += strlen(cp));
    va_end(ap);
    loc = malloc(len + 1);
    if (loc) {
        static const char body[] =
                "<html><body><a href=\"%s\">Continue</a></body></html>\r\n";
        HTTP_STREAM *sp = hs->s_stream;

        HttpSendHeaderTop(hs, code);

        va_start(ap, code);
        for (*loc = '\0'; (cp = va_arg(ap, char *)) != NULL; strcat(loc, cp));
        va_end(ap);

#if HTTP_VERSION >= 0x10
        s_vputs(sp, ct_Location, ": ", loc, "\r\n", NULL);
        HttpSendHeaderBottom(hs, "text", "html", sizeof(body) - 1 + strlen(loc) - 2);
#endif

        s_printf(sp, body, loc);
        s_flush(sp);
        free(loc);
    }
    return 0;
}
Exemplo n.º 6
0
void HttpSendStreamError(HTTP_STREAM *stream, int status, const char *realm)
{
    static const char body[] = "<HTML><HEAD><TITLE>%d %s</TITLE></HEAD><BODY>%d %s</BODY></HTML>\r\n";
    const char *text = HttpResponseText(status);

    HttpSendStreamHeaderTop(stream, status);
#if HTTP_VERSION >= 0x10
    if (realm) {
        static const char auth_fmt_P[] = "WWW-Authenticate: Basic realm=\"%s\"\r\n";
        s_printf(stream, auth_fmt_P, realm);
    }
    HttpSendStreamHeaderBottom(stream, "text", "html", HTTP_CONN_CLOSE, sizeof(body) - 1 + 2 * (1 + strlen(text) - 2));
#endif
    s_printf(stream, body, status, text, status, text);
    s_flush(stream);
}
Exemplo n.º 7
0
void CFtpDialog::ChangeDirectory()
{
	if (fSocket < 0)
	{
		beep();
		return;
	}

	try
	{
		s_printf(fSocketFD, "cwd %s\r\n", fPath);

		GetReply();

		if (*fReply != '2')
			THROW(("Changing directory failed.\n%s", fReply));

		ListDirectory();
	}
	catch (HErr& err)
	{
		err.DoError();
	}

	GetPWD();
} // CFtpDialog::ChangeDirectory
Exemplo n.º 8
0
static int CgiClock(HTTPD_SESSION *hs)
{
    time_t now;
    const struct tm *ltm;

#if defined(NUT_OS)
    NutSleep(1000);
#elif defined(_WIN32)
    Sleep(1000);
#else
#warning Unknown OS, sleep missing
#endif

    HttpSendHeaderTop(hs, 200);
    s_puts("Cache-Control: no-cache, must-revalidate\r\n", hs->s_stream);
    s_puts("Content-Type: text/html; charset=iso-8859-1\r\n", hs->s_stream);
    s_puts("Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n", hs->s_stream);
    chprintf((BaseSequentialStream *)&itm_port, "%s\n", "****CgiClock****");
    HttpSendHeaderBottom(hs, "text", "html", -1);

    time(&now);
    ltm = localtime(&now);
    s_printf(hs->s_stream, "{\"time\": \"%02d:%02d:%02d\"}\r\n", ltm->tm_hour, ltm->tm_min, ltm->tm_sec);
    s_flush(hs->s_stream);

    return 0;
}
Exemplo n.º 9
0
FILE *xopen_file( char *fn, char *mode )
{
    int buf = s_printf( 0,0, "%s/%s",  rc_key_value("files","datadir"), fn );

    FILE *fp= fopen( m_buf(buf), mode );
    if( !fp ) WARN("cannot access File %s", fn); 
    m_free(buf);
    return fp;
}
Exemplo n.º 10
0
int				ft_printf(const char *format, ...)
{
	ini_printf();
	va_start(sgt_printf()->args, format);
	s_printf((char *)format);
	va_end(sgt_printf()->args);
	replace_color(sgt_printf()->buffer, sgt_printf()->len);
	write(1, sgt_printf()->buffer, sgt_printf()->len);
	ft_strdel(&sgt_printf()->buffer);
	return (sgt_printf()->len);
}
Exemplo n.º 11
0
void log_status(struct ehci_hcd * ehci, char *s) {
	u32 status = ehci_readl(&ehci->regs->status);
	u32 statusp = ehci_readl(&ehci->regs->port_status[0]);

	s_printf("    log_status  (%s)\n", s);
	s_printf("    status: %x %s%s%s%s%s%s%s%s%s%s\n",
			status,
			(status & STS_ASS) ? " Async" : "",
			(status & STS_PSS) ? " Periodic" : "",
			(status & STS_RECL) ? " Recl" : "",
			(status & STS_HALT) ? " Halt" : "",
			(status & STS_IAA) ? " IAA" : "",
			(status & STS_FATAL) ? " FATAL" : "",
			(status & STS_FLR) ? " FLR" : "",
			(status & STS_PCD) ? " PCD" : "",
			(status & STS_ERR) ? " ERR" : "",
			(status & STS_INT) ? " INT" : ""
			);

	s_printf("    status port: %x\n", statusp);
}
Exemplo n.º 12
0
FILE *open_cachfile(int write)
{
    const char *s;
    if ((s = getenv("HOME")) == NULL) {
        s = getpwuid(getuid())->pw_dir;
    }
    if( s==NULL ) s="/tmp";

    int fn = s_printf( 0,0, "%s/%s", s, SETTINGS.cache_dir );

    FILE *fp = fopen( m_buf(fn), write ? "w" : "r" );
    m_free(fn);
    return fp;
}
Exemplo n.º 13
0
int				ft_asprintf(char **ret, const char *format, ...)
{
	ini_printf();
	va_start(sgt_printf()->args, format);
	s_printf((char *)format);
	va_end(sgt_printf()->args);
	replace_color(sgt_printf()->buffer, sgt_printf()->len);
	ft_strdel(ret);
	if ((*ret = (char *)malloc((sgt_printf()->len + 1) * sizeof(char))) == NULL)
		return (-1);
	ft_memcpy(*ret, sgt_printf()->buffer, sgt_printf()->len);
	(*ret)[sgt_printf()->len] = '\0';
	ft_strdel(&sgt_printf()->buffer);
	return (sgt_printf()->len);
}
Exemplo n.º 14
0
void HttpSendStreamHeaderTop(HTTP_STREAM *stream, int status)
{
#if HTTP_VERSION >= 0x10
    static const char fmt_P[] = "HTTP/%d.%d %d %s\r\nServer: uHTTP 0.0\r\n";

    s_printf(stream, fmt_P, HTTP_MAJOR_VERSION, HTTP_MINOR_VERSION, status, HttpResponseText(status));

#if !defined(HTTPD_EXCLUDE_DATE)
    {
        time_t now = time(NULL);
        s_vputs(stream, ct_Date, ": ", Rfc1123TimeString(gmtime(&now)), " GMT\r\n", NULL);
    }
#endif
#endif
}
Exemplo n.º 15
0
/*
 * Generate ID for FIDO messages without ^AMSGID, using date and CRC over
 * From, To and Subject.
 */
char *s_msgid_default(Message *msg)
{
    /*
     * Compute CRC for strings from, to, subject
     */
    crc32_init();
    crc32_compute(msg->name_from, strlen(msg->name_from));
    crc32_compute(msg->name_to  , strlen(msg->name_to  ));
    crc32_compute(msg->subject  , strlen(msg->subject  ));

    return s_printf("<NOMSGID_%d=3A%d=2F%d.%d_%s_%08lx@%s>",
		    msg->node_orig.zone, msg->node_orig.net,
		    msg->node_orig.node, msg->node_orig.point,
		    date("%y%m%d_%H%M%S", &msg->date), crc32_value(),
		    msgid_domain(msg->node_orig.zone));
}
Exemplo n.º 16
0
/*!
 * \brief Send device description.
 *
 * This uHTTP CGI function will be registered when UpnpRegisterDeviceTree()
 * is called for the first time.
 */
static int UpnpCgiDeviceDescription(HTTPD_SESSION *hs)
{
    HTTP_STREAM *stream = hs->s_stream;
    SSDP_DEVICE *sdev = NULL;
    SSDP_SERVICE *ssvc;
    char *type;

    type = HttpArgParseFirst(&hs->s_req);
    if (type) {
        for (sdev = device_registration; sdev; sdev = sdev->sdev_next) {
            if (strcmp(sdev->sdev_type, type) == 0) {
                break;
            }
        }
    }
    if (sdev) {
        UPNP_DEVICE_INFO *udev = sdev->sdev_info;

        XmlHead(hs->s_stream);
        s_puts("<root xmlns=\"urn:schemas-upnp-org:device-1-0\">\r\n", hs->s_stream);
        SpecVersion(stream);

        s_puts("<device>\r\n", stream);
        s_printf(stream, "<deviceType>urn:%s:device:%s:1</deviceType>\r\n", sdev->sdev_domain, sdev->sdev_type);
        WriteTag(stream, "friendlyName", udev->udev_name);
        WriteTag(stream, "manufacturer", udev->udev_mnf->umnf_name);
        WritePrepTag(stream, "manufacturerURL", udev->udev_mnf->umnf_url, "http://");
        WriteTag(stream, "modelDescription", udev->udev_mdl->umdl_desc);
        WriteTag(stream, "modelName", udev->udev_mdl->umdl_name);
        WriteTag(stream, "modelNumber", udev->udev_mdl->umdl_num);
        WritePrepTag(stream, "modelURL", udev->udev_mdl->umdl_url, "http://");
        WriteTag(stream, "UDN", sdev->sdev_uuid);
        if (sdev->sdev_svc) {
            s_puts("<serviceList>\r\n", stream);
            for (ssvc = sdev->sdev_svc; ssvc; ssvc = ssvc->ssvc_next) {
                UPNP_SERVICE_INFO *usvc = sdev->sdev_svc->ssvc_info;

                s_puts("<service>\r\n", stream);
                s_printf(stream, "<serviceType>urn:schemas-upnp-org:service:%s:1</serviceType>\r\n", sdev->sdev_svc->ssvc_type);
                s_printf(stream, "<serviceId>urn:upnp-org:serviceId:%s:1</serviceId>\r\n", sdev->sdev_svc->ssvc_type);
                s_printf(stream, "<SCPDURL>%s?%s=%s</SCPDURL>", usvc->usvc_url_scpd, sdev->sdev_type, ssvc->ssvc_type);
                s_printf(stream, "<controlURL>%s?%s=%s</controlURL>", usvc->usvc_url_ctrl, sdev->sdev_type, ssvc->ssvc_type);
                s_printf(stream, "<eventSubURL>%s?%s=%s</eventSubURL>", usvc->usvc_url_event, sdev->sdev_type, ssvc->ssvc_type);
                s_puts("</service>\r\n", stream);
            }
            s_puts("</serviceList>\r\n", stream);
        }
        WriteTag(stream, "presentationURL", udev->udev_presentation);
        s_puts("</device>\r\n", stream);
        s_puts("</root>\r\n", stream);
    }
    s_flush(stream);

    return 0;
}
Exemplo n.º 17
0
Arquivo: main.c Projeto: saiyn/OSAL
static void print_version(const char *version)
{
	s_printf("\r\n***************************************************\r\n");
#ifdef NAD_C378
	s_printf("*      NAD C378\r\n");
#else
	s_printf("*      NAD C358\r\n");
#endif
	s_printf("*      version:%s\r\n",version);
	s_printf("*      Created: %s %s \r\n", __DATE__, __TIME__);
	s_printf("***************************************************\r\n");
	
}
Exemplo n.º 18
0
void sconsole_sis(void){

    if((strcmppgm2ram(ARG_1, cmd[0]) == 0) && (QUA_ARG == 2)){
        
        s_printf();

    } else if((strcmppgm2ram(ARG_1, cmd[1]) == 0) && (QUA_ARG == 2)){

        s_tty();

    } else if((strcmppgm2ram(ARG_1, cmd[2]) == 0) && (QUA_ARG == 2)){

        s_stack();

    } else if((strcmppgm2ram(ARG_1, cmd[3]) == 0) && (QUA_ARG == 2)){

        tempo_hum();

    } else if(strcmppgm2ram(ARG_1, cmd[4]) == 0 && (QUA_ARG > 2)){

        s_lcd();

    } else if(strcmppgm2ram(ARG_1, cmd[5]) == 0 && (QUA_ARG == 2)){

        s_ip();

    } else if(strcmppgm2ram(ARG_1, cmd[6]) == 0 && (QUA_ARG == 2)){

        lcd_qmsg("rc_conf");
        rc_test();

    } else if(strcmppgm2ram(ARG_1, cmd[7]) == 0 && (QUA_ARG == 2)){

        s_redes();

    } else {

        s_erro_argumentos();
        
    }
}
Exemplo n.º 19
0
void CFtpDialog::GetPWD()
{
	if (fSocket < 0)
	{
		beep();
		return;
	}

	try
	{
		s_printf(fSocketFD, "PWD\r\n");

		GetReply();

		if (*fReply != '2')
			THROW(("Could not get current working directory.\n%s", fReply));

		char *e;
		int n;

		if (sscanf(fReply, "%*d \"%n%s\"", &n, fPath) == 1)
		{
			strcpy(fPath, fReply + n);
			if ((e = strchr(fPath, '"')) != NULL) *e = 0;

			strcat(fPath, "/");
		}
		else
			strcpy(fPath, "/error!!!");

		UpdateDirectoryPopup();
	}
	catch (HErr& e)
	{
		strcpy(fPath, "/");
		throw;
	}
} // CFtpDialog::GetPWD
Exemplo n.º 20
0
static int SendResult(HTTPD_SESSION *hs, char *first, char *last)
{
    static const char head[] =
        "<html>"
        "<head>"
        "<title>Form Result</title>"
        "</head>";
    static const char body[] =
        "<body>"
        "<p>Hello %s %s!</p>"
        "<a href=\"/index.html\">back</a>"
        "</body>"
        "<html>";

    HttpSendHeaderTop(hs, 200);
    HttpSendHeaderBottom(hs, "text", "html", -1);

    s_puts(head, hs->s_stream);
    s_printf(hs->s_stream, body, first, last);
    s_flush(hs->s_stream);

    return 0;
}
Exemplo n.º 21
0
void HttpSendStreamHeaderBottom(HTTP_STREAM *stream, char *type, char *subtype, int conn, long bytes)
{
#if HTTP_VERSION >= 0x10
    if (type && subtype) {
        s_vputs(stream, ct_Content_Type, ": ", type, "/", subtype, "\r\n", NULL);
    }
    if (bytes >= 0) {
        s_printf(stream, "%s: %ld\r\n", ct_Content_Length, bytes);
    }
#if HTTP_VERSION >= 0x11
#if HTTP_KEEP_ALIVE_REQ
    if (conn != HTTP_CONN_KEEP_ALIVE)
#endif
    {
        s_puts("Connection: close\r\n", stream);
    }
#elif HTTP_KEEP_ALIVE_REQ
    if (conn == HTTP_CONN_KEEP_ALIVE) {
        s_puts("Connection: keep-alive\r\n", stream);
    }
#endif
    s_puts("\r\n", stream);
#endif
}
Exemplo n.º 22
0
s32 USBStorage_Open(ehci_device_data * device_data) {
	s32 retval = -1;
	u8 conf, *max_lun = NULL;
	u32 iConf, iInterface, iEp;
	static usb_devdesc udd;
	usb_configurationdesc *ucd;
	usb_interfacedesc *uid;
	usb_endpointdesc *ued;
	
	struct ehci_hcd * ehci = device_data->__ehci;
	usbstorage_handle *dev = &device_data->__usbfd;
	struct ehci_device *fd = device_data->__dev;

	device_data->__lun = 16; // select bad LUN

	max_lun = USB_Alloc(1);
	if (max_lun == NULL) return -ENOMEM;

	memset(dev, 0, sizeof (*dev));

	dev->tag = TAG_START;
	dev->usb_fd = fd;


	retval = USB_GetDescriptors(ehci, dev->usb_fd, &udd);

#ifdef MEM_PRINT
	s_printf("USBStorage_Open(): USB_GetDescriptors %i\n", retval);
#ifdef MEM_PRINT
	log_status(ehci, "after USB_GetDescriptors");
#endif

#endif

	if (retval < 0)
		goto free_and_return;

	/*
	// test device changed without unmount (prevent device write corruption)
	if (ums_init_done) {
		if (my_memcmp((void *) &_old_udd, (void *) &udd, sizeof (usb_devdesc) - 4)) {
			USB_Free(max_lun);
			USB_FreeDescriptors(&udd);
#ifdef MEM_PRINT
			s_printf("USBStorage_Open(): device changed!!!\n");

#endif
			return -ENODEV;
		}
	}
	 */ 
	_old_udd = udd;
	try_status = -128;
	for (iConf = 0; iConf < udd.bNumConfigurations; iConf++) {
		ucd = &udd.configurations[iConf];
		for (iInterface = 0; iInterface < ucd->bNumInterfaces; iInterface++) {
			uid = &ucd->interfaces[iInterface];
			//      debug_printf("interface %d, class:%x subclass %x protocol %x\n",iInterface,uid->bInterfaceClass,uid->bInterfaceSubClass, uid->bInterfaceProtocol);
			if (uid->bInterfaceClass == USB_CLASS_MASS_STORAGE &&
					(uid->bInterfaceSubClass == MASS_STORAGE_SCSI_COMMANDS
					|| uid->bInterfaceSubClass == MASS_STORAGE_RBC_COMMANDS
					|| uid->bInterfaceSubClass == MASS_STORAGE_ATA_COMMANDS
					|| uid->bInterfaceSubClass == MASS_STORAGE_QIC_COMMANDS
					|| uid->bInterfaceSubClass == MASS_STORAGE_UFI_COMMANDS
					|| uid->bInterfaceSubClass == MASS_STORAGE_SFF8070_COMMANDS) &&
					uid->bInterfaceProtocol == MASS_STORAGE_BULK_ONLY && uid->bNumEndpoints >= 2) {

				dev->ata_protocol = 0;
				if (uid->bInterfaceSubClass != MASS_STORAGE_SCSI_COMMANDS || uid->bInterfaceSubClass != MASS_STORAGE_RBC_COMMANDS)
					dev->ata_protocol = 1;

#ifdef MEM_PRINT
				s_printf("USBStorage_Open(): interface subclass %i ata_prot %i \n", uid->bInterfaceSubClass, dev->ata_protocol);

#endif
				dev->ep_in = dev->ep_out = 0;
				for (iEp = 0; iEp < uid->bNumEndpoints; iEp++) {
					ued = &uid->endpoints[iEp];
					if (ued->bmAttributes != USB_ENDPOINT_BULK)
						continue;

					if (ued->bEndpointAddress & USB_ENDPOINT_IN)
						dev->ep_in = ued->bEndpointAddress;
					else
						dev->ep_out = ued->bEndpointAddress;
				}
				if (dev->ep_in != 0 && dev->ep_out != 0) {
					dev->configuration = ucd->bConfigurationValue;
					dev->interface = uid->bInterfaceNumber;
					dev->altInterface = uid->bAlternateSetting;

					goto found;
				}
			} else {


				if (uid->endpoints != NULL)
					USB_Free(uid->endpoints);
				uid->endpoints = NULL;
				if (uid->extra != NULL)
					USB_Free(uid->extra);
				uid->extra = NULL;

				if (uid->bInterfaceClass == USB_CLASS_HUB) {
					retval = USBSTORAGE_ENOINTERFACE;
					try_status = -20000;

					USB_FreeDescriptors(&udd);

					goto free_and_return;
				}

				if (uid->bInterfaceClass == USB_CLASS_MASS_STORAGE &&
						uid->bInterfaceProtocol == MASS_STORAGE_BULK_ONLY && uid->bNumEndpoints >= 2) {
					try_status = -(10000 + uid->bInterfaceSubClass);
				}
			}
		}
	}

#ifdef MEM_PRINT
	s_printf("USBStorage_Open(): cannot find any interface!!!\n");

#endif
	USB_FreeDescriptors(&udd);
	retval = USBSTORAGE_ENOINTERFACE;
	debug_printf("cannot find any interface\n");
	goto free_and_return;

found:
	USB_FreeDescriptors(&udd);

	retval = USBSTORAGE_EINIT;
	try_status = -1201;

#ifdef MEM_PRINT
	s_printf("USBStorage_Open(): conf: %x altInterface: %x\n", dev->configuration, dev->altInterface);

#endif

	if (USB_GetConfiguration(ehci, dev->usb_fd, &conf) < 0)
		goto free_and_return;
	try_status = -1202;

#ifdef MEM_PRINT
	log_status(ehci, "after USB_GetConfiguration");
#endif

#ifdef MEM_PRINT
	if (conf != dev->configuration)
		s_printf("USBStorage_Open(): changing conf from %x\n", conf);

#endif
	if (/*conf != dev->configuration &&*/ USB_SetConfiguration(ehci, dev->usb_fd, dev->configuration) < 0)
		goto free_and_return;

	try_status = -1203;
	if (dev->altInterface != 0 && USB_SetAlternativeInterface(ehci, dev->usb_fd, dev->interface, dev->altInterface) < 0)
		goto free_and_return;

	try_status = -1204;

#ifdef MEM_PRINT
	log_status(ehci, "Before USBStorage_Reset");
#endif
	retval = USBStorage_Reset(ehci, dev);
#ifdef MEM_PRINT
	log_status(ehci, "After USBStorage_Reset");
#endif
	if (retval < 0)
		goto free_and_return;



	/*	retval = __USB_CtrlMsgTimeout(dev, (USB_CTRLTYPE_DIR_DEVICE2HOST | USB_CTRLTYPE_TYPE_CLASS | USB_CTRLTYPE_REC_INTERFACE), USBSTORAGE_GET_MAX_LUN, 0, dev->interface, 1, max_lun);
		if(retval < 0 )
			dev->max_lun = 1;
		else
			dev->max_lun = (*max_lun+1);


		if(retval == USBSTORAGE_ETIMEDOUT)*/

	/* NOTE: from usbmassbulk_10.pdf "Devices that do not support multiple LUNs may STALL this command." */
	dev->max_lun = 8; // max_lun can be from 1 to 16, but some devices do not support lun

	retval = USBSTORAGE_OK;

	/*if(dev->max_lun == 0)
		dev->max_lun++;*/

	/* taken from linux usbstorage module (drivers/usb/storage/transport.c) */
	/*
	 * Some devices (i.e. Iomega Zip100) need this -- apparently
	 * the bulk pipes get STALLed when the GetMaxLUN request is
	 * processed.   This is, in theory, harmless to all other devices
	 * (regardless of if they stall or not).
	 */
	//USB_ClearHalt(dev->usb_fd, dev->ep_in);
	//USB_ClearHalt(dev->usb_fd, dev->ep_out);

	dev->buffer = USB_Alloc(MAX_TRANSFER_SIZE + 16);

	if (dev->buffer == NULL) {
		retval = -ENOMEM;
		try_status = -1205;
	} else retval = USBSTORAGE_OK;

free_and_return:

	if (max_lun != NULL) USB_Free(max_lun);

	if (retval < 0) {
		if (dev->buffer != NULL)
			USB_Free(dev->buffer);
		memset(dev, 0, sizeof (*dev));

#ifdef MEM_PRINT
		s_printf("USBStorage_Open(): try_status %i\n", try_status);

#endif
		return retval;
	}

#ifdef MEM_PRINT
	s_printf("USBStorage_Open(): return 0\n");

#endif

	return 0;
}
Exemplo n.º 23
0
void CFtpDialog::ListDirectory()
{
	if (fSocket < 0)
	{
		beep();
		return;
	}

	for (int i = fListView->CountItems() - 1; i >= 0; i--)
		delete fListView->RemoveItem(i);

	int data = 0;

	try
	{
		struct sockaddr_in saData;
		struct sockaddr_in saCmd;

		data = socket(AF_INET, SOCK_STREAM, 0);
		if (data < 0)
			THROW(("Failed to get socket: %s", strerror(errno)));

		memset(&saData, 0, sizeof(saData));
		saData.sin_family = AF_INET;
		socklen_t size = sizeof(saData);

		bool passive = IsOn("pssv");
		if (passive) {
			// switch to passive mode
			s_printf(fSocketFD, "pasv\r\n");
		} else {
			FailSockErr(bind(data, (struct sockaddr *)&saData, sizeof(saData)));
			FailSockErr(listen(data, 5));
			// [zooey]: calling getsockname() on a socket that has been bound to
			// IN_ADDR_ANY (the wildcard-address) will *not* return any IP-address,
			// as this will only be setup by the system during connect or accept.
			// 	[refer to W.R. Stevens - Unix Network Programming, Vol 1, p. 92]
			// BeOS R5 however, *does* fill in the IP-address at this stage (that's
			// why this code worked for R5 but didn't work for BONE).
			// In order to fix this problem, we simply use the IP-address of the
			// command-socket for the PORT-command:
			//
			// fetch port from data-socket:
			FailSockErr(getsockname(data, (struct sockaddr *)&saData, &size));
			unsigned char *pap = (unsigned char *)&saData.sin_port;
			// fetch ip-address from cmd-socket:
			FailSockErr(getsockname(fSocketFD->sSocket, (struct sockaddr *)&saCmd, 
											&size));
			unsigned char *sap = (unsigned char *)&saCmd.sin_addr.s_addr;
			// combine both into the PORT-command:
			s_printf(fSocketFD, "port %d,%d,%d,%d,%d,%d\r\n", sap[0], sap[1], 
						sap[2], sap[3], pap[0], pap[1]);
		}

		int state = 1;
		SOCK* dsf = NULL;

		while (state)
		{
			GetReply();

			switch (state)
			{
				case 1:
					if (passive) {
						unsigned int sap[4];
						unsigned int pap[2];
						if (*fReply != '2')
							THROW(("Pasv command failed: %s", fReply));
						char* pos = strchr(fReply,'(');
						if (!pos)
							THROW(("Answer to Pasv has unknown format: %s", fReply));
						int cnt = sscanf(pos+1, "%u,%u,%u,%u,%u,%u", 
											  &sap[0], &sap[1], &sap[2], &sap[3], 
											  &pap[0], &pap[1]);
						if (cnt != 6)
							THROW(("Could not parse answer to Pasv (%d of 6): %s", 
									 cnt, fReply));
						char ipAddr[20];
						sprintf(ipAddr, "%d.%d.%d.%d", sap[0], sap[1], sap[2], sap[3]);
						saData.sin_port = htons(pap[0]*256+pap[1]);
						saData.sin_addr.s_addr = inet_addr(ipAddr);
						FailOSErr(connect(data, (struct sockaddr *)&saData, sizeof(saData)));
						dsf = s_open(data, "r+");
					} else {
						if (*fReply != '2')
							THROW(("Port command failed: %s", fReply));
					}
					s_printf(fSocketFD, "list\r\n");
					state = 2;
					break;

				case 2:
					if (*fReply == '1')
					{
						int ds = 0;
						if (!passive) {
							FailSockErr(ds = accept(data, (struct sockaddr *)&saData, &size));
							dsf = s_open(ds, "r+");
						}

						try
						{
							CFtpListItem *item;
							char s[256];
							bool showAll = IsOn("dotf");
							int  entryCount = 0;

							while (s_gets(s, 256, dsf))
							{
								entryCount++;
								item = new CFtpListItem(this, s);
								if (item->IsValid() && (showAll || !item->IsDotFile()))
								{
									fListView->AddItem(item);
								}
								else
									delete item;
							}
							if (entryCount == 0)
								THROW(("Could not get listing."));

							fListView->Invalidate();
							UpdateIfNeeded();
							s_close(dsf);
							if (!passive)
								closesocket(ds);
						}
						catch (HErr& e)
						{
							EnableUpdates();
							s_close(dsf);
							closesocket(ds);
							throw;
						}

						state = 3;
					}
					else
						THROW(("Failed to get listing: %s", fReply));
					break;

				case 3:
					if (*fReply != '2')
						THROW(("Something went wrong fetching the directory listing"));
					state = 0;
					break;
			}
		}

		closesocket(data);
	}
	catch (HErr& e)
	{
		if (data) closesocket(data);
		e.DoError();
	}
} // CFtpDialog::ListDirectory
Exemplo n.º 24
0
void CFtpDialog::Connect()
{
	try
	{
		if (fSocket >= 0)
		{
			if (fSocketFD) s_close(fSocketFD);
			closesocket(fSocket);
		}

		fSocket = socket(AF_INET, SOCK_STREAM, 0);
		if (fSocket < 0)
			THROW(("Failed to get socket: %s", strerror(errno)));

		fSocketFD = s_open(fSocket, "r+");
		FailNil(fSocketFD);

		SetDefaultButton(static_cast<BButton*>(FindView("ok  ")));

		struct hostent *host;
		if ((host = gethostbyname(GetText("srvr"))) == NULL)
		{
			fServerName->MarkAsInvalid(true);
			THROW(("Failed to get server address: %s", strerror(errno)));
		}

		struct sockaddr_in sa;
		sa.sin_family = AF_INET;
		sa.sin_port = htons(21);
		sa.sin_addr.s_addr = *(unsigned int *)host->h_addr;

		if (connect(fSocket, (struct sockaddr *)&sa, sizeof(sa)) < 0)
		{
			if (!(errno == ECONNREFUSED || errno == ETIMEDOUT || errno == ENETUNREACH))
				fServerName->MarkAsInvalid(true);

			THROW(("Failed to connect to the host: %s", strerror(errno)));
		}

		int state = 1;
		while (state)
		{
			GetReply();

			switch (state)
			{
				case 1:
					if (*fReply != '2')
						THROW(("Connect failed: %s", fReply));
					s_printf(fSocketFD, "user %s\r\n", GetText("user"));
					state = 2;
					break;

				case 2:
					if (*fReply == '3')
					{
						s_printf(fSocketFD, "pass %s\r\n", GetText("pass"));
						state = 3;
						break;
					}
					else if (*fReply != '2' && *fReply != '5')
						THROW(("Failed to login: %s", fReply));

					// fall thru

				case 3:
					if (*fReply == '5')
						THROW(("Incorrect username/password.\n%s", fReply));
					if (state == 3 && *fReply != '2')
						THROW(("Failed to login: %s", fReply));

					state = 0;
					break;
			}
		}

		gPrefs->SetPrefString(prf_S_LastFtpUser, GetText("user"));
		gPrefs->SetPrefString(prf_S_LastFtpServer, GetText("srvr"));
		sfPassword = GetText("pass");

		GetPWD();
	}
	catch (HErr& e)
	{
		e.DoError();
		s_close(fSocketFD); fSocketFD = NULL;
		closesocket(fSocket); fSocket = -1;

		SetDefaultButton(static_cast<BButton*>(FindView("cnct")));
	}

	if (fSocketFD)
		ListDirectory();
} // CFtpDialog::Connect
Exemplo n.º 25
0
s32 USBStorage_Init(void) {
	int i, j, retries = 1;
	//	debug_printf("usbstorage init %d\n", ums_init_done);
	if (!ums_init_done)
	{
		_ehci_device_count = 0;
		init_ehci_device_struct();
	}
	struct ehci_hcd *ehci = &ehci_hcds[0];

	try_status = -1;

	for (j = 0; j < EHCI_HCD_COUNT; j++) {

		for (i = 0; i < ehci->num_port; i++) {
			struct ehci_device *dev = &ehci->devices[i];

retry:
			dev->port = i;
			if (dev->id != 0 && dev->busy == 0) {
				handshake_mode = 1;
				if (ehci_reset_port(ehci, i) >= 0) {

					//ehci_device_data * device_data = find_ehci_data(ehci);
					
					ehci_device_data * device_data = &_ehci_data[_ehci_device_count];
					dev->busy = 1;
					device_data->__ehci = ehci;
					device_data->__dev = dev;					

					if (USBStorage_Try_Device(device_data) == 0) {
						printf("EHCI bus %d device %d: vendor %04X product %04X : Mass-Storage Device\n", j, dev->id, device_data->__vid, device_data->__pid);

						first_access = TRUE;
						handshake_mode = 0;
						ums_init_done = 1;
						unplug_device = 0;
						//__bdev=register_bdev(NULL, &usb2mass_ops, "uda");
						//register_disc_interface(&usb2mass_ops);
						device_data->__ready = 1;
						if (mount_usb_device)						
							mount_usb_device(_ehci_device_count);						
						_ehci_device_count++;
#ifdef MEM_PRINT
						s_printf("USBStorage_Init() Ok\n");

#endif

						//return 0;
					}
				}
			} else if (dev->busy == 0) {
				u32 status;
				handshake_mode = 1;
				status = ehci_readl(&ehci->regs->port_status[i]);

#ifdef MEM_PRINT
				s_printf("USBStorage_Init() status %x\n", status);

#endif

				if (status & 1) {
					if (ehci_reset_port2(ehci, i) < 0) {
						ehci_msleep(100);
						ehci_reset_port(ehci, i);
					}
					if (retries) {
						retries--;
						goto retry;
					}
				}
			}
		}

		ehci++;
	}

	return try_status;
}
Exemplo n.º 26
0
static s32 __usbstorage_reset(struct ehci_hcd * ehci, usbstorage_handle *dev, int hard_reset) {
	s32 retval;
	u32 old_usb_timeout = usb_timeout;
	usb_timeout = 1000 * 1000;
	//int retry = hard_reset;
	int retry = 0; //first try soft reset
retry:
	if (retry >= 1) {
		u8 conf;
		debug_printf("reset device..\n");
		retval = ehci_reset_device(ehci, dev->usb_fd);
		ehci_msleep(10);
		if (retval == -ENODEV) return retval;

		if (retval < 0 && retval != -7004)
			goto end;
		// reset configuration
		if (USB_GetConfiguration(ehci, dev->usb_fd, &conf) < 0)
			goto end;
		if (/*conf != dev->configuration &&*/ USB_SetConfiguration(ehci, dev->usb_fd, dev->configuration) < 0)
			goto end;
		if (dev->altInterface != 0 && USB_SetAlternativeInterface(ehci, dev->usb_fd, dev->interface, dev->altInterface) < 0)
			goto end;
		
		
		
		// find the device with the same ehci ptr
		ehci_device_data * _device_data = find_ehci_data(ehci);
		
		if (_device_data->__lun != 16) {
			if (USBStorage_MountLUN(ehci, &_device_data->__usbfd, _device_data->__lun) < 0)
				goto end;
		}
	}
	debug_printf("usbstorage reset..\n");
	retval = __USB_CtrlMsgTimeout(ehci, dev, (USB_CTRLTYPE_DIR_HOST2DEVICE | USB_CTRLTYPE_TYPE_CLASS | USB_CTRLTYPE_REC_INTERFACE), USBSTORAGE_RESET, 0, dev->interface, 0, NULL);

#ifdef MEM_PRINT
	s_printf("usbstorage reset: Reset ret %i\n", retval);

#endif

	/* FIXME?: some devices return -7004 here which definitely violates the usb ms protocol but they still seem to be working... */
	if (retval < 0 && retval != -7004)
		goto end;


	/* gives device enough time to process the reset */
	ehci_msleep(10);


	debug_printf("clear halt on bulk ep..\n");
	retval = USB_ClearHalt(ehci, dev->usb_fd, dev->ep_in);

#ifdef MEM_PRINT
	s_printf("usbstorage reset: clearhalt in ret %i\n", retval);

#endif
	if (retval < 0)
		goto end;
	ehci_msleep(10);
	retval = USB_ClearHalt(ehci, dev->usb_fd, dev->ep_out);

#ifdef MEM_PRINT
	s_printf("usbstorage reset: clearhalt in ret %i\n", retval);

#endif
	if (retval < 0)
		goto end;
	ehci_msleep(50);
	usb_timeout = old_usb_timeout;
	return retval;

end:
	if (retval == -ENODEV) return retval;
#ifdef HOMEBREW
	if (disable_hardreset) return retval;
	if (retry < 1) { //only 1 hard reset
		ehci_msleep(100);
		debug_printf("retry with hard reset..\n");
		retry++;
		goto retry;
	}
#else
	if (retry < 5) {
		ehci_msleep(100);
		debug_printf("retry with hard reset..\n");

		retry++;
		goto retry;
	}
#endif
	usb_timeout = old_usb_timeout;
	return retval;
}
Exemplo n.º 27
0
/*!
 * \brief Send service description.
 *
 * This uHTTP CGI function will be registered when UpnpRegisterDeviceTree()
 * is called for the first time.
 */
static int UpnpCgiServiceDescription(HTTPD_SESSION *hs)
{
    SSDP_SERVICE *ssvc = NULL;
    SSDP_DEVICE *sdev = NULL;
    HTTP_STREAM *stream = hs->s_stream;
    const char *dev_type;

    dev_type = HttpArgParseFirst(&hs->s_req);
    if (dev_type) {
        const char *svc_type = HttpArgValue(&hs->s_req);

        if (dev_type) {
            for (sdev = device_registration; sdev; sdev = sdev->sdev_next) {
                if (strcmp(sdev->sdev_type, dev_type) == 0) {
                    for (ssvc = sdev->sdev_svc; ssvc; ssvc = ssvc->ssvc_next) {
                        if (strcmp(ssvc->ssvc_type, svc_type) == 0) {
                            break;
                        }
                    }
                    break;
                }
            }
        }
    }
    if (ssvc) {
        SOAP_PROCEDURE *act;
        UPNP_VARIABLE *stv;
        UPNP_SERVICE_INFO *usvc = ssvc->ssvc_info;

        XmlHead(hs->s_stream);
        s_puts("<scpd xmlns=\"urn:schemas-upnp-org:service-1-0\">\r\n", stream);
        SpecVersion(stream);

        act = usvc->usvc_proc;
        if (act) {
            s_puts("<actionList>\r\n", stream);
            do {
                s_puts("<action>\r\n", stream);
                WriteTag(stream, "name", act->proc_name);
                if (act->proc_argi || act->proc_argo) {
                    SOAP_ARG *arg;

                    s_puts("<argumentList>\r\n", stream);
                    for (arg = act->proc_argi; arg; arg = arg->arg_next) {
                        s_puts("<argument>\r\n", stream);
                        WriteTag(stream, "name", arg->arg_name);
                        WriteTag(stream, "relatedStateVariable", ((UPNP_VARIABLE *) arg->arg_info)->ustv_name);
                        WriteTag(stream, "direction", "in");
                        s_puts("</argument>\r\n", stream);
                    }
                    for (arg = act->proc_argo; arg; arg = (SOAP_ARG *) arg->arg_next) {
                        s_puts("<argument>\r\n", stream);
                        WriteTag(stream, "name", arg->arg_name);
                        WriteTag(stream, "relatedStateVariable", ((UPNP_VARIABLE *) arg->arg_info)->ustv_name);
                        WriteTag(stream, "direction", "out");
                        s_puts("</argument>\r\n", stream);
                    }
                    s_puts("</argumentList>\r\n", stream);
                }
                s_puts("</action>\r\n", stream);
            } while ((act = act->proc_next) != NULL);
            s_puts("</actionList>\r\n", stream);
        }

        stv = usvc->usvc_stv;
        if (stv) {
            s_puts("<serviceStateTable>\r\n", stream);
            do {
                s_printf(stream, "<stateVariable sendEvents=\"%s\">\r\n", stv->ustv_events ? "yes" : "no");
                WriteTag(stream, "name", stv->ustv_name);
                WriteTag(stream, "dataType", UpnpVarTypeString(stv->ustv_type));
                WriteTag(stream, "defaultValue", stv->ustv_default);
                s_puts("</stateVariable>\r\n", stream);
            } while((stv = stv->ustv_next) != NULL);
            s_puts("</serviceStateTable>\r\n", stream);
        }
        s_puts("</scpd>\r\n", stream);
    }
    s_flush(stream);

    return 0;
}
Exemplo n.º 28
0
int s_printflt(double f, int places)
{
	char buf[32];
	return s_printf("%s", s_ftosb(buf, f, places));
}
Exemplo n.º 29
0
void CFtpStream::Automaton(int action)
{
	int ctrl = 0, data = 0, r;
	char msg[1024];
	SOCK *csSock = NULL;
	
	try
	{
		if (! fURL.IsValid())
			THROW(("The data to connect is not complete"));
		
		ctrl = socket(AF_INET, SOCK_STREAM, 0);
		if (ctrl < 0)
			THROW(("Failed to get socket: %s", strerror(errno)));
		data = socket(AF_INET, SOCK_STREAM, 0);
		if (data < 0)
			THROW(("Failed to get socket: %s", strerror(errno)));
		
		csSock = s_open(ctrl, "r+");
		
		struct hostent *host;
		if ((host = gethostbyname(fURL.Server())) == NULL)
			THROW(("Failed to get server address: %s", strerror(errno)));
		
		struct sockaddr_in sa;
		sa.sin_family = AF_INET;
		sa.sin_port = htons(21);
		sa.sin_addr.s_addr = *(unsigned int *)host->h_addr;
		
		FailOSErr(connect(ctrl, (struct sockaddr *)&sa, sizeof(sa)));
		
		mail_pop_account pa;
		string username, password;

		username = strlen(fURL.Username()) ? fURL.Username() : "anonymous";

		if (strlen(fURL.Password()))
			password = fURL.Password();
		else if (get_pop_account(&pa) == B_OK)
			password = pa.reply_to;
		else
			password = "******";
		
		struct sockaddr_in saData;
		memset(&saData, 0, sizeof(saData));
		saData.sin_family = AF_INET;

		int state = 1;
		while (state)
		{
			GetReply(csSock, r, msg);

			switch (state)
			{
				case 1:
					if ((r / 100) != 2)
						THROW(("Connect failed: %s", msg));
					s_printf(csSock, "user %s\r\n", username.c_str());
					state = 2;
					break;
				
				case 2:
					if ((r / 100) == 3)
					{
						s_printf(csSock, "pass %s\r\n", password.c_str());
						state = 3;
						break;
					}
					else if ((r / 100) != 2 && (r / 100) != 5)
						THROW(("Failed to login: %s", msg));

					// fall thru
				
				case 3:
					if ((r / 100) == 5)
					{
						bool ok;
						
						CLogin *l = DialogCreator<CLogin>::CreateDialog(NULL);
						FailNil(l);

						l->Connect(fURL.Server(), username, password, &ok);
						
						if (ok)
						{
							s_printf(csSock, "noop\r\n");
							state = 1;
							continue;
						}
						else
							THROW((0));
					}
					else if (state == 3 && (r / 100) != 2)
						THROW(("Failed to login: %s", msg));
					else if (strlen(fURL.Path()))
					{
						s_printf(csSock, "cwd %s\r\n", fURL.Path());
						state = 4;
						break;
					}
		
					// fall thru
				
				case 4:
				{
					if (state == 4 && (r / 100) != 2)
						THROW(("Failed to change directory: %s", msg));
					
					if (fPassive) {
						// switch to passive mode
						s_printf(csSock, "pasv\r\n");
					} else {
						FailSockErr(bind(data, (struct sockaddr *)&saData, sizeof(saData)));
						FailSockErr(listen(data, 5));
						// [zooey]: calling getsockname() on a socket that has been bound to 
						// IN_ADDR_ANY (the wildcard-address) will *not* return any IP-address,
						// as this will only be setup by the system during connect or accept.
						// 		[refer to W.R. Stevens - Unix Network Programming, Vol 1, p. 92]
						// BeOS R5 however, *does* fill in the IP-address at this stage (that's
						// why this code worked for R5 but didn't work for BONE).
						// In order to fix this problem, we simply use the IP-address of the
						// command-socket for the PORT-command:
						socklen_t size = sizeof(saData);
						// fetch port from data-socket:
						FailSockErr(getsockname(data, (struct sockaddr *)&saData, &size));
						unsigned char *pap = (unsigned char *)&saData.sin_port;
						// fetch ip-address from cmd-socket:
						FailSockErr(getsockname(csSock->sSocket, (struct sockaddr *)&sa, &size));
						unsigned char *sap = (unsigned char *)&sa.sin_addr.s_addr;
						s_printf(csSock, "port %d,%d,%d,%d,%d,%d\r\n", sap[0], sap[1], sap[2], sap[3], pap[0], pap[1]);
					}
					state = 5;
					break;
				}
				case 5:
					if (fPassive) {
						unsigned int sap[4];
						unsigned int pap[2];
						if ((r / 100) != 2)
							THROW(("Pasv command failed: %s", msg));
						char* pos = strchr(msg,'(');
						if (!pos)
							THROW(("Answer to Pasv has unknown format: %s", msg));
						int cnt = sscanf(pos+1, "%u,%u,%u,%u,%u,%u", 
											  &sap[0], &sap[1], &sap[2], &sap[3], 
											  &pap[0], &pap[1]);
						if (cnt != 6)
							THROW(("Could not parse answer to Pasv (%d of 6): %s", 
									 cnt, msg));
						char ipAddr[20];
						sprintf(ipAddr, "%d.%d.%d.%d", sap[0], sap[1], sap[2], sap[3]);
						saData.sin_port = htons(pap[0]*256+pap[1]);
						saData.sin_addr.s_addr = inet_addr(ipAddr);
						FailOSErr(connect(data, (struct sockaddr *)&saData, sizeof(saData)));
					} else {
						if ((r / 100) != 2)
							THROW(("Port command failed: %s", msg));
					}
					if (action == 1)
					{
						s_printf(csSock, "retr %s\r\n", fURL.File());
						state = 6;
					}
					else
					{
						s_printf(csSock, "stor %s\r\n", fURL.File());
						state = 7;
					}
					break;
				
				case 6:
					if ((r / 100) == 1)
					{
						int ds;
						socklen_t size = sizeof(sa);
						if (fPassive)
							ds = data;
						else
							FailSockErr(ds = accept(data, (struct sockaddr *)&sa, &size));
						
						try
						{
							do
							{
								FailSockErr(r = recv(ds, msg, 1024, 0));
								if (r)
									fData.Write(msg, r);
							}
							while (r);

							closesocket(ds);
						}
						catch (HErr& e)
						{
							closesocket(ds);
							throw;
						}
						
						state = 8;
					}
					else
						THROW(("Failed to retrieve file: %s", msg));
					break;
					
				case 7:
					if ((r / 100) == 1)
					{
						int ds;
						socklen_t size = sizeof(sa);
						if (fPassive)
							ds = data;
						else
							FailSockErr(ds = accept(data, (struct sockaddr *)&sa, &size));
						
						try
						{
							FailSockErr(send(ds, fData.Buffer(), fData.BufferLength(), 0));
							closesocket(ds);
						}
						catch (HErr& e)
						{
							closesocket(ds);
							throw;
						}
						
						state = 8;
					}
					else
						THROW(("Failed to store file: %s", msg));
					break;

				case 8:
					if ((r / 100) != 2)
						THROW(("Failed to %s file: %s", action == 1 ? "retrieve" : "store",  msg));
					s_printf(csSock, "quit\r\n");
					state = 0;
					break;

			}
		}
		
		s_close(csSock);
		if (!fPassive)
			closesocket(data);
		closesocket(ctrl);
	}
	catch (HErr& e)
	{
		if (csSock) s_close(csSock);
		if (ctrl) closesocket(ctrl);
		if (data) closesocket(data);

		throw;
	}
} /* CFtpStream::Automaton */
Exemplo n.º 30
0
int main() {
	int sockfd, tempF;
	uint8_t sockopen = 0;
	uint16_t i;
	uint8_t netbuf[32], tempFstr[8];

	WDTCTL = WDTPW | WDTHOLD;
        DCOCTL = CALDCO_16MHZ;
        BCSCTL1 = CALBC1_16MHZ;
        BCSCTL2 = 0x00;
        BCSCTL3 = LFXT1S_2;
        __delay_cycles(160000);

	uartcli_begin(uartbuf, 8);
	wiznet_init();

	while (wiznet_phystate() < 0)
		__delay_cycles(160000);

	wiznet_ip_bin_w_reg(W52_SUBNETMASK, w52_const_subnet_classC);
	wiznet_ip_str_w_reg(W52_SOURCEIP, "10.104.115.180");
	wiznet_ip_str_w_reg(W52_GATEWAY, "10.104.115.1");

	sockfd = wiznet_socket(IPPROTO_TCP);
	if (sockfd < 0)
		LPM4;
	uartcli_print_str("wiznet_socket(): "); uartcli_println_int(sockfd);

	res1 = wiznet_bind(sockfd, 80);  // Bind port 80
	if (res1 < 0)
		LPM4;

	while(1) {
		if (!sockopen) {
			res1 = wiznet_accept(sockfd);
			uartcli_print_str("accept; "); uartcli_println_int(res1);
			if (!res1 || res1 == -EISCONN)
				sockopen = 1;
		} else {
			res1 = wiznet_recv(sockfd, netbuf, 32, 1);
			uartcli_print_str("RECV: "); uartcli_println_int(res1);
			//wiznet_debug_uart(sockfd);
			switch (res1) {
				case -ENOTCONN:
				case -ENETDOWN:
					sockopen = 0;
					break;
				case -EAGAIN:
					break;
				default:
					for (i=0; i < res1-3; i++) {
						if (netbuf[i] == '\r' && netbuf[i+1] == '\n' && netbuf[i+2] == '\r' && netbuf[i+3] == '\n') {
							// Request submitted by client; server sends reply
							tempF = adc_temp_read();
							i = s_printf(tempFstr, "%d F", tempF);

							strcpy(netbuf, "HTTP/1.1 200 OK\r\n");
							wiznet_send(sockfd, netbuf, strlen(netbuf), 0);
							strcpy(netbuf, "Content-Type: text/plain\r\n");
							wiznet_send(sockfd, netbuf, strlen(netbuf), 0);
							s_printf(netbuf, "Content-Length: %d\r\n\r\n", i);
							wiznet_send(sockfd, netbuf, strlen(netbuf), 0);
							if (wiznet_send(sockfd, tempFstr, strlen(tempFstr), 1) < 0) {
								sockopen = 0;
							}
							wiznet_quickbind(sockfd);  // Close client connection & re-establish port 80 binding
						}
					}
			}
		}
		if (wiznet_irq_getsocket() == -EAGAIN && !wiznet_recvsize(sockfd)) {  // No IRQs pending
			uartcli_println_str("LPM0;");
			LPM0;
			uartcli_println_str("wake;");
		}
	}

	return 0;
}