Главная » Просмотр файлов » Symbian OS Communications

Symbian OS Communications (779884), страница 42

Файл №779884 Symbian OS Communications (Symbian Books) 42 страницаSymbian OS Communications (779884) страница 422018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 42)

We should pass in a descriptor containing thename or IP address (depending on which the user entered) that weconnect used to the socket. Note that if the user asked us to connect toa server by name, which we first had to resolve using RHostResolver,that we should pass that name into the SetOpt() call rather than theIP address we got back from DNS. This is because most certificates areissued to servers by name rather than by address, and we are verifyingthat the name in the certificate matches the name of the host to whichwe tried to connect.Then we can initiate a handshake with the remote server, usingStartClientHandshake(). This is an asynchronous call and willonly complete when the handshake completes and the secure connection is established, or there was a failure during connection establishment.If there is pending data to read on the RSocket when this method iscalled, it will complete immediately with the error code KErrSSLSocketBusy.// Start client handshakeerr = iSecureSocket->StartClientHandshake(iStatus);Typically, the client needs to authenticate the server, by checking thecertificate the server provided to see if it chains back to a certificate held190IP AND RELATED TECHNOLOGIESin the local device’s certificate store, and trusted for use with TLS.

Inaddition to this, the server can request that the client also authenticate byproviding a certificate, although this is much less common. In this caseClientCert() can be used to retrieve the client certificate if the serverhas requested one. This API will return a pointer to the current clientcertificate or a null pointer if no suitable certificate is available. A clientcertificate can only be returned after the negotiation is complete.// Get the client certificateCX509Certificate* clientCert = iSecureSocket->ClientCert()Likewise, the client can retrieve the server certificate usingServerCert(). This returns a pointer to the current server certificate, if available. A server certificate can only be returned to the clientafter the negotiation has reached a stage where the certificate has beenreceived and verified.// Get the server certificateCX509Certificate* serverCert = iSecureSocket->ServerCert()It is possible to retrieve the current cipher suite from the server usingCurrentCipherSuite().

This method can only return the currentcipher suite when the server has proposed one, which is after the handshake negotiation is complete. If this method is called before completionof the handshake, the cipher values will be null, or more explicitly[0x00][0x00].// Get the current cipher suiteerr = iSecureSocket->CurrentCipherSuite(cipherBuf);At any time after the initial handshake completes, a renegotiationcan be initiated using StartRenegotiation().

StartRenegotiation() suspends data transmission and reception and restarts thehandshake negotiation. It also creates a new TLS provider object toaccess security services. This is necessary as a new cryptographic tokenmight be selected to create new key material. The session cache is flushedto ensure a new session is created and that entirely new key material isgenerated.// Renegotiate the handshakeiSecureSocket->StartRenegotiation(iStatus);The handshake can be cancelled using the synchronous method CancelHandshake().

The state of the connection cannot be guaranteed,USING THE NETWORK CONNECTION191therefore it is recommended to call Close(). Close() will close thesecure connection by cancelling all outstanding operations and closingthe socket.// Cancel the handshakeiSecureSocket->CancelHandshake();iSecureSocket->Close();Data transferOnce the handshake phase is complete, the secure socket is ready fordata transfer. Only one send operation can be oustanding at a time.

TheSend() will complete with KErrNotReady if called when another sendoperation is still outstanding.// Send some dataiSecureSocket->Send(iBuffer, iStatus);It is also possible to cancel the socket send by using CancelSend()as shown below:// Cancel the SendiSecureSocket->CancelSend();To receive data from the socket, Recv() or RecvOneOrMore() canbe used. Recv() will complete when the descriptor has been filled, whileRecvOneOrMore() will complete when at least one byte has been read,although typically it provides more data than this. These functions areasynchronous and only one Recv() or RecvOneOrMore() operationcan be outstanding at any time. More details and advice on the useof these methods is given in Chapter 3: it’s worth paying particularattention to the fact that Recv() blocks until the supplied descriptoris filled.// receive some data using Recv()iSecureSocket->Recv(iBuffer, iStatus);// receive some data using RecvOneOrMore()iSecureSocket->RecvOneOrMore(iBuffer, iStatus);To cancel a receive, CancelRecv() will cancel any outstanding readoperation:// Cancel the ReceiveiSecureSocket->CancelRecv();192IP AND RELATED TECHNOLOGIESUseful utility interfacesThere are some methods in the CSecureSocket API that aren’t strictlypart of the handshake or data transfer.

They are documented here forcompleteness.FlushSessionCache() This is used to support abbreviated handshakes. This method is used as an indication that the client does notintend to reuse an existing session. As such it allows the client to specifywhether a new or existing session will be used in the handshake negotiation. Note, however, that there is no means of indicating the success orfailure of this operation to the client.// Flush the session cachesecureSocket->FlushSessionCache();SetDialogMode() and DialogMode() These methods are usedto set and get the untrusted certificate dialog mode.

It determines if adialog is displayed when an untrusted certificate is received. There aretwo modes of operation that are specified as part of the TDialogModeenumeration:• EDialogModeAttended, all untrusted certificates result in a userdialog.• EDialogModeUnattended, untrusted certificates are cancelledwithout user confirmation.// Set the dialog mode to EDialogModeAttendederr = iSecureSocket->SetDialogMode(EDialogModeAttended);// check error code!// Get the dialog modeTDialogMode dialogMode = iSecureSocket->DialogMode();SetProtocol() and Protocol() These synchronous methods getand set the protocol in use.

Presently, this can be either ‘‘SSL3.0’’ or‘‘TLS1.0’’.When Protocol() is called before the handshake has taken place,the protocol name returned is the one that will be proposed in theconnection. However, once the handshake has taken place, and thesecure connection has been established, the protocol name returned isthe one that is actually being used.For instance, the ‘‘TLS1.0’’ protocol may be proposed, but if thehandshake takes place and the remote end doesn’t support TLS1.0, thenthe protocol used would be SSL3.0.INFORMATION GATHERING AND CONNECTION MANAGEMENT193The SetProtocol() method sets the protocol version that will beproposed in the connection.

Setting ‘‘TLS1.0’’ means that a connectioncan still fall back to SSL3.0 if required. Setting ‘‘SSL3.0’’ means thatTLS1.0 will not be available for use, even if the remote end only supportsTLS1.0.// Set the protocol to TLS1.0_LIT(KSSLProtocol,"tls1.0");err=iSecureSocket->SetProtocol(KSSLProtocol);// check error code// Get the protocolconst TUint KMaxTlsProtocolNameSize = 8;TBuf<KMaxTlsProtocolNameSize> protocol;err=iSecureSocket->Protocol(protocol);// check error code6.5 Information Gathering and Connection ManagementRConnection also allows an application to gather information aboutthe state of their network connection, as well as information about othernetwork connections in the system.

Probably the most important of theseis the state of the current connection’ which is published through progressnotifications.6.5.1 Progress NotificationsIt is possible to track the progress of the current network connectionusing ProgressNotification(). During the connection and disconnection procedure, the connection will go through various stages eachof which will produce a notification of progress.

This is extremely useful,as it allows a user interface to give feedback to the user on the currentstatus of the connection. Whilst connection setup may be a long-runningoperation, each individual step is considerably shorter. This means thatthe user can be provided with much better feedback that the connection establishment is making progress rather than stalled.

Applicationscan drive these UI updates by subscribing to progress notifications andupdating the UI as each new progress notification arrives.Each bearer technology provides its own set of progress notificationsfor any bearer specific states, but there are also generic stages which willbe common to all bearers.

The generic stages, and the transitions betweenthem are shown in Figure 6.8.These generic stages are defined in nifvar.h:• KConnectionUninitialised – the start and end stage. The connection has not yet been attempted or a previous connection has beenterminated.194IP AND RELATED TECHNOLOGIESUserpromptedStartingselectionFinishedselectionCancelledUninitializedConnectionfailureLink layeropenClosedStartingclose= connection activeData transfertemporarilyblockedFigure 6.8 Connection progress stages• KStartingSelection – the IAP to be used for the network connection is being selected. This is where the user will be prompted ifnecessary.• KFinishedSelection – the IAP has been selected, the networkconnection can be attempted using the parameters configured in theIAP settings.

Характеристики

Тип файла
PDF-файл
Размер
3,18 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Почему делать на заказ в разы дороже, чем купить готовую учебную работу на СтудИзбе? Наши учебные работы продаются каждый год, тогда как большинство заказов выполняются с нуля. Найдите подходящий учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6354
Авторов
на СтудИзбе
312
Средний доход
с одного платного файла
Обучение Подробнее